Files
clean-architecture-frontend…/scripts/lib/v8-coverage-counter-semantics.ts
DongHyeonka 0c3c9d3351
frontend-quality-gates / merge / static checks (pull_request) Canceled after 0s
frontend-quality-gates / merge / tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / browser tests (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Canceled after 0s
frontend-quality-gates / external-vulnerability-provider (pull_request) Canceled after 0s
frontend-quality-gates / external-provenance-provider (pull_request) Canceled after 0s
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Canceled after 0s
frontend-quality-gates / deploy-promoted-release (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Canceled after 0s
frontend-quality-gates / main / checker self-tests (pull_request) Canceled after 0s
fix(coverage): 위험 커버리지가 "use strict" 밖의 지시문을 문장으로 센다
문제: 0bb1f0af에서 모듈을 Babel AST로 읽게 바꾼 뒤, 파일 맨 위의
지시문(`"use client";`)을 세지 않는다. Babel은 지시문을
`program.directives`에 두고 `body`에 넣지 않는다(ESTree 변환은 body에
넣었다). V8 coverage는 `"use client"`를 문장 1개로 세고 `"use strict"`는
세지 않는다(desktop에서 실제 V8 실행으로 확인). 그래서 지시문과 타입만
있는 모듈이 counterless로 분류되고 coverage에는 문장이 잡혀, 파생
프로젝트에서 risk-coverage가 거짓으로 실패한다. 지금 `src/`에는
지시문이 없어 375개 대조에서 보이지 않았다. 새 눈 리뷰(fe-testing
렌즈)가 찾았다.

고른 방법: `"use strict"`가 아닌 지시문이 있으면 counter-bearing이다.
check:v8-coverage-counter-semantics의 fixture에 지시문 모듈 둘
(`use client`는 counter-bearing, `use strict`는 counterless)을 더해,
분류기가 기대는 V8 동작을 실제 실행으로 고정한다. risk-coverage 시험도
같은 두 모듈을 분류한다.

위험·한계: 예전 분류(ESTree)는 `"use strict"`만 있는 모듈을
counter-bearing으로 봤다. 이제 V8과 같이 counterless다.

검증(desktop): risk-coverage·risk-coverage-files·counter-semantics 시험
통과, check:v8-coverage-counter-semantics PASS(2 counter-bearing,
8 counterless), check:types·eslint rc=0. 변이: 지시문 규칙을 빼면
「matches the observed V8 counterless …」가 `directive-use-client.ts`를
counterless로 받아 실패. 로그 /tmp/claude-gates/w2fe2-dir1·2·4/.

Fixes: 0bb1f0afc0 ("perf(coverage): 위험 커버리지 모듈 목록을 Babel 파서와 동기 fs로 만든다")
2026-11-12 22:45:48 +09:00

315 lines
10 KiB
TypeScript

import { execFile } from "node:child_process";
import {
cp,
mkdtemp,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { rootAnchoredGlobs } from "./coverage-scope.ts";
const execFileAsync = promisify(execFile);
const coverageMetrics = [
"lines",
"statements",
"functions",
"branches",
] as const;
/** Modules V8 gives at least one counter: code, and a directive prologue. */
const counterBearingModules = Object.freeze([
"src/directive-use-client.ts",
"src/runtime.ts",
] as const);
const counterlessModules = Object.freeze([
"src/directive-use-strict.ts",
"src/import-empty.ts",
"src/import-side-effect.ts",
"src/import-type-empty.ts",
"src/import-value.ts",
"src/reexport-named.ts",
"src/reexport-star.ts",
"src/type-only.ts",
] as const);
const expectedModules: readonly string[] = Object.freeze(
[...counterBearingModules, ...counterlessModules].sort(),
);
const childOutputLimit = 1_800;
/**
* The fixture is copied into a folder whose name ends in `src` and has glob
* characters. Vitest matches coverage patterns anywhere in an absolute path,
* so an unanchored `src/**` also counts the fixture's root-level
* `outside-src.ts`, which the row-set check then reports as additional. The
* repository's own coverage patterns are anchored the same way
* (vitest.config.ts, scripts/lib/coverage-scope.ts).
*/
const fixtureCheckoutName = "checkout (copy)-src";
type ChildOutput = Readonly<{ stdout: string; stderr: string }>;
type ChildInput = Readonly<{
repositoryRoot: string;
ownedRoot: string;
fixtureRoot: string;
configPath: string;
}>;
type CheckerOptions = Readonly<{
repositoryRoot?: string;
createOwnedRoot?: () => Promise<string>;
runVitest?: (input: ChildInput) => Promise<ChildOutput>;
}>;
export type V8CoverageCounterSemantics = Readonly<{
counterBearingModules: readonly string[];
counterlessModules: readonly string[];
}>;
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function hasErrorCode(error: unknown, code: string): boolean {
return isRecord(error) && error.code === code;
}
function normalizeSummaryPath(value: string, fixtureRoot: string): string {
const relative = path.isAbsolute(value) ? path.relative(fixtureRoot, value) : value;
const normalized = relative.split(path.sep).join("/");
if (
normalized.length === 0 ||
normalized === ".." ||
normalized.startsWith("../") ||
path.posix.isAbsolute(normalized)
) {
throw new TypeError(`V8 coverage row is outside the owned fixture: ${value}`);
}
return normalized;
}
function coverageCounter(
value: unknown,
label: string,
): Readonly<{ total: number; covered: number; skipped: number; pct: number }> {
if (!isRecord(value)) throw new TypeError(`${label} must be an object`);
const { total, covered, skipped, pct } = value;
if (
typeof total !== "number" ||
!Number.isSafeInteger(total) ||
typeof covered !== "number" ||
!Number.isSafeInteger(covered) ||
typeof skipped !== "number" ||
!Number.isSafeInteger(skipped) ||
typeof pct !== "number" ||
!Number.isFinite(pct) ||
total < 0 ||
covered < 0 ||
skipped < 0 ||
covered + skipped > total
) {
throw new TypeError(`${label} contains invalid coverage counters`);
}
const expectedPercentage =
total === 0 ? 100 : Math.floor((covered / total) * 10_000) / 100;
if (pct !== expectedPercentage) {
throw new TypeError(`${label} contains invalid coverage counters`);
}
return { total, covered, skipped, pct };
}
function coverageRow(
value: unknown,
label: string,
): Readonly<Record<(typeof coverageMetrics)[number], ReturnType<typeof coverageCounter>>> {
if (!isRecord(value)) throw new TypeError(`${label} must be an object`);
return Object.fromEntries(
coverageMetrics.map((metric) => [
metric,
coverageCounter(value[metric], `${label}.${metric}`),
]),
) as Readonly<
Record<(typeof coverageMetrics)[number], ReturnType<typeof coverageCounter>>
>;
}
export function assertV8CoverageCounterSemantics(
value: unknown,
fixtureRoot: string,
): V8CoverageCounterSemantics {
if (!isRecord(value)) throw new TypeError("V8 coverage summary must be an object");
coverageRow(value.total, "V8 coverage total");
const rows = new Map<string, ReturnType<typeof coverageRow>>();
for (const [producerPath, producerRow] of Object.entries(value)) {
if (producerPath === "total") continue;
const normalizedPath = normalizeSummaryPath(producerPath, fixtureRoot);
if (rows.has(normalizedPath)) {
throw new TypeError(`V8 coverage row is duplicated: ${normalizedPath}`);
}
rows.set(
normalizedPath,
coverageRow(producerRow, `V8 coverage row ${normalizedPath}`),
);
}
const actualModules = [...rows.keys()].sort();
const missing = expectedModules.filter((modulePath) => !rows.has(modulePath));
const additional = actualModules.filter(
(modulePath) => !expectedModules.includes(modulePath),
);
if (missing.length > 0 || additional.length > 0) {
throw new Error(
`V8 coverage row set mismatch; missing: ${missing.join(", ") || "none"}; additional: ${additional.join(", ") || "none"}`,
);
}
for (const modulePath of counterBearingModules) {
const row = rows.get(modulePath)!;
if (!coverageMetrics.some((metric) => row[metric].total > 0)) {
throw new Error(`V8 module is not counter-bearing: ${modulePath}`);
}
}
for (const modulePath of counterlessModules) {
const row = rows.get(modulePath)!;
const exactAllZero = coverageMetrics.every((metric) => {
const counter = row[metric];
return (
counter.total === 0 &&
counter.covered === 0 &&
counter.skipped === 0 &&
counter.pct === 100
);
});
if (!exactAllZero) {
throw new Error(
`V8 counterless module must have exact all-zero counters: ${modulePath}`,
);
}
}
return Object.freeze({
counterBearingModules: Object.freeze([...counterBearingModules]),
counterlessModules: Object.freeze([...counterlessModules]),
});
}
function boundedChildOutput(value: unknown): string {
const output =
typeof value === "string"
? value
: value instanceof Uint8Array
? new TextDecoder().decode(value)
: "";
if (output.length <= childOutputLimit) return output;
return `${output.slice(0, childOutputLimit)}\n[truncated ${output.length - childOutputLimit} characters]`;
}
async function defaultRunVitest(input: ChildInput): Promise<ChildOutput> {
const result = await execFileAsync(
process.execPath,
[
path.join(input.repositoryRoot, "node_modules/vitest/vitest.mjs"),
"run",
"--config",
input.configPath,
"--coverage",
"--reporter=dot",
"--no-color",
],
{
cwd: input.fixtureRoot,
encoding: "utf8",
timeout: 30_000,
maxBuffer: 256 * 1024,
},
);
return { stdout: result.stdout, stderr: result.stderr };
}
function assertOwnedTemporaryRoot(value: string): string {
const temporaryRoot = path.resolve(tmpdir());
const ownedRoot = path.resolve(value);
const relative = path.relative(temporaryRoot, ownedRoot);
if (
relative.length === 0 ||
relative === ".." ||
relative.startsWith(`..${path.sep}`) ||
path.isAbsolute(relative)
) {
throw new TypeError(`V8 coverage fixture root is not an owned temp path: ${ownedRoot}`);
}
return ownedRoot;
}
export async function checkV8CoverageCounterSemantics(
options: CheckerOptions = {},
): Promise<V8CoverageCounterSemantics> {
const repositoryRoot = path.resolve(options.repositoryRoot ?? process.cwd());
const createOwnedRoot =
options.createOwnedRoot ??
(() => mkdtemp(path.join(tmpdir(), "v8-counter-semantics-")));
const runVitest = options.runVitest ?? defaultRunVitest;
const ownedRoot = assertOwnedTemporaryRoot(await createOwnedRoot());
const fixtureSource = path.join(
repositoryRoot,
"tests/fixtures/v8-coverage-counter-semantics",
);
const fixtureRoot = path.join(ownedRoot, fixtureCheckoutName);
const configPath = path.join(fixtureRoot, "vitest.config.mjs");
const reportsDirectory = path.join(ownedRoot, "coverage");
try {
await cp(fixtureSource, fixtureRoot, { recursive: true });
await writeFile(
configPath,
`export default ${JSON.stringify(
{
root: fixtureRoot,
test: {
globals: true,
include: ["counter-semantics.fixture.ts"],
setupFiles: [],
coverage: {
provider: "v8",
reportsDirectory,
reporter: ["json-summary"],
include: rootAnchoredGlobs(fixtureRoot, ["src/**/*.ts"]),
},
},
},
null,
2,
)};\n`,
"utf8",
);
try {
await runVitest({ repositoryRoot, ownedRoot, fixtureRoot, configPath });
} catch (error) {
const record = isRecord(error) ? error : {};
throw new Error(
`V8 coverage counter semantics child Vitest failed\nstdout:\n${boundedChildOutput(record.stdout)}\nstderr:\n${boundedChildOutput(record.stderr)}`,
{ cause: error },
);
}
const summaryPath = path.join(reportsDirectory, "coverage-summary.json");
let summaryText: string;
try {
summaryText = await readFile(summaryPath, "utf8");
} catch (error) {
if (hasErrorCode(error, "ENOENT")) {
throw new Error("V8 coverage counter semantics coverage summary is missing", {
cause: error,
});
}
throw error;
}
let summary: unknown;
try {
summary = JSON.parse(summaryText) as unknown;
} catch (error) {
throw new TypeError("V8 coverage counter semantics summary is invalid JSON", {
cause: error,
});
}
return assertV8CoverageCounterSemantics(summary, fixtureRoot);
} finally {
await rm(ownedRoot, { recursive: true, force: true });
}
}