Files
DongHyeonka 52e7d2c745 fix(fixture): design-system·diagnostics 음성 fixture를 파일마다 거절한다
FE-GATE-029는 check:design-system:fixture와 check:diagnostics:fixture가
exit 1과 머리말을 내면 통과로 센다. 거절된 파일이 하나만 있어도 그
조건이 채워진다. 그래서 검사기에서 진짜 규칙(TSX의 raw palette·hue
mix·inline style, direct console·민감 context)을 지워도 029가 초록이었다.
fixture 폴더에서만 도는 표식 규칙(TOOLTIP_ONLY_REQUIRED_INFORMATION,
UNKNOWN_DIAGNOSTIC_EVENT)이 자기 파일을 늘 거절했기 때문이다.

check-i18n.ts가 하던 파일별 판정을 scripts/lib/fixture-rejection.ts로
옮기고 세 검사기가 같이 쓴다. fixture 모드에서 어느 failure도 이름을
대지 않는 fixture 파일이 있거나 fixture 파일이 하나도 없으면, 그 목록을
찍고 exit 2로 끝난다. 029는 exit 1을 기대하므로 실패한다. 파일 이름은
경로 경계로 맞춘다(a.ts가 a.tsx·b/a.ts에 맞지 않는다). i18n 판정은
endsWith에서 이 판정으로 바뀌어 조금 엄격해진다.

표식 규칙 둘을 지운다. tooltip-only.tsx는 그 표식 말고 거절할 규칙이
없어 지운다. headless-vendor-import.tsx·hue-mix.tsx를 더하고,
raw-palette.tsx는 inline style 없이 SVG fill로 바꿔 fixture 하나가 규칙
하나에 걸리게 한다. direct-console.ts에서는 표식 문자열을 뺀다. fe-design-system
스킬이 지운 tooltip 규칙을 있는 것처럼 적던 줄도 고친다.

버린 안: gates.json의 expectedDiagnosticId를 규칙 문구로 좁히기. 항목
범위가 029 정의를 바꾸지 말라고 하고, 규칙이 여럿이라 문구 하나로는
다 못 본다.

한계: 파일마다 「failure가 하나라도 있는지」를 본다. fixture 하나에 서로
다른 규칙 둘이 걸리면 하나를 지워도 다른 하나가 거절한다. 지금 fixture는
규칙 하나씩이고 시험이 failure 목록을 그대로 단언하지만, 새 fixture에
그것을 강제하지는 않는다. check-i18n.ts가 helper를 부르는지 단언하는
시험은 없다(main에도 없다).

시험: design-system-rules.test.ts·fixture-rejection.test.ts가 임시
root에서 검사기를 돌려, fixture마다 기대한 failure만 나오는지와 거절되지
않는 파일을 더하면 exit 2와 그 파일이 찍히는지 본다. helper는 경로 경계·
빈 폴더를 단위로 본다. timeout은 desktop에서 잰 가장 긴 값(test:unit
1,038 ms)이다. design-system 쪽 두 시험(가장 긴 719 ms)은 기존 describe의
3,540 ms 안이다. RED·GREEN은 PR 본문에 적는다.

Refs: REV-FE-0002
2026-11-21 08:56:32 +09:00

179 lines
6.6 KiB
TypeScript

import { mkdir, readFile, readdir } from "node:fs/promises";
import { i18nReportArtifactSchema } from "./contracts/release-artifacts.ts";
import { fixtureRejectionFailure } from "./lib/fixture-rejection.ts";
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
import path from "node:path";
import { EN_MESSAGES, KO_MESSAGES, MESSAGE_CATALOGS } from "../src/presentation/i18n/catalog.ts";
const fixtureMode = process.argv.includes("--fixture");
const failures: string[] = [];
const sourceExtensions = /\.(?:ts|tsx|mts|cts)$/;
const rawFailureRender =
/(?<!\$)\{\s*(?:failure|error|response|backend)(?:\?\.|\.)[\w?.]*message\s*\}/;
async function listSourceFiles(directory: string): Promise<string[]> {
const result: string[] = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
const target = path.join(directory, entry.name);
if (entry.isDirectory()) result.push(...(await listSourceFiles(target)));
else if (sourceExtensions.test(entry.name)) result.push(target);
}
return result;
}
function placeholders(template: string): string[] {
return [...template.matchAll(/\{([a-zA-Z][a-zA-Z0-9]*)\}/g)]
.map((match) => match[1])
.sort();
}
if (!fixtureMode) {
const canonicalKeys = Object.keys(KO_MESSAGES).sort();
for (const [locale, catalog] of Object.entries(MESSAGE_CATALOGS)) {
const readableCatalog = catalog as Readonly<Record<string, string>>;
const canonicalCatalog = KO_MESSAGES as Readonly<Record<string, string>>;
const keys = Object.keys(catalog).sort();
if (JSON.stringify(keys) !== JSON.stringify(canonicalKeys)) {
failures.push(`${locale} catalog keys do not match ko-KR`);
}
for (const key of canonicalKeys) {
if (
JSON.stringify(placeholders(readableCatalog[key] ?? "")) !==
JSON.stringify(placeholders(canonicalCatalog[key] ?? ""))
) {
failures.push(`${locale}:${key} interpolation parameters do not match`);
}
}
}
if (Object.keys(EN_MESSAGES).length !== canonicalKeys.length) {
failures.push("en-US catalog key count does not match ko-KR");
}
}
// 0929/08-02. Whether screen code takes its words from the catalog is an
// ESLint rule now (eslint.config.ts, screenTextSelectors): this script looked
// for Hangul anywhere in a file, so it rejected Korean comments and let English
// copy through. Raw HTML is the FE-OC-019 ESLint rule. What stays here is
// catalog parity and rendering a backend message, which a selector cannot tell
// from an ordinary `.message` read. Fixture mode runs the ESLint rule on the
// fixture trees too, so this one gate shows the whole i18n contract rejecting
// every forbidden file and passing the allowed one.
// `src/presentation/examples` (the platform overview) and the stories are
// workshop code and stay out of the ESLint rule's scope on purpose.
const forbiddenFixtureRoot = "tests/fixtures/i18n/forbidden";
const allowedFixtureRoot = "tests/fixtures/i18n/allowed";
const sourceRoot = fixtureMode ? forbiddenFixtureRoot : ".";
const commonDirectories = [
"src/presentation/boundaries",
"src/presentation/components",
"src/presentation/design-system",
"src/presentation/forms",
"src/presentation/layouts",
"src/presentation/pages",
"src/presentation/routes",
"src/presentation/templates",
];
async function featurePresentationDirectories(root: string): Promise<string[]> {
const features = path.join(root, "src/features");
const entries = await readdir(features, { withFileTypes: true }).catch(
() => [],
);
return entries
.filter((entry) => entry.isDirectory())
.map((entry) => path.join("src/features", entry.name, "presentation"));
}
async function existingSourceFiles(directory: string): Promise<string[]> {
return listSourceFiles(directory).catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return [];
throw error;
});
}
const sourceDirectories = [
...commonDirectories,
...(await featurePresentationDirectories(sourceRoot)),
].map((directory) => path.join(sourceRoot, directory));
const sources = (
await Promise.all(sourceDirectories.map(existingSourceFiles))
).flat();
async function rawFailureRenders(files: readonly string[]): Promise<string[]> {
const found: string[] = [];
for (const file of files) {
if (rawFailureRender.test(await readFile(file, "utf8"))) {
found.push(`raw backend/error message rendered in ${file}`);
}
}
return found;
}
/** ESLint errors in a fixture tree, one entry per error, ending in the file. */
async function lintErrors(root: string): Promise<string[]> {
const { ESLint } = await import("eslint");
const results = await new ESLint({ ignore: false }).lintFiles([root]);
return results.flatMap((result) =>
result.messages
.filter((message) => message.severity === 2)
.map(
(message) =>
`${message.ruleId ?? "eslint"} ${message.line}:${message.column} ${message.message} in ${path.relative(process.cwd(), result.filePath)}`,
),
);
}
failures.push(...(await rawFailureRenders(sources)));
if (fixtureMode) failures.push(...(await lintErrors(forbiddenFixtureRoot)));
const allowedFixtureFailures = fixtureMode
? [
...(await rawFailureRenders(await listSourceFiles(allowedFixtureRoot))),
...(await lintErrors(allowedFixtureRoot)),
]
: [];
const report = i18nReportArtifactSchema.parse({
schemaVersion: 1,
mode: fixtureMode ? "negative-fixture" : "source",
localeCount: Object.keys(MESSAGE_CATALOGS).length + 1,
messageKeyCount: Object.keys(KO_MESSAGES).length,
checkedFiles: sources.length,
failures,
passed: failures.length === 0,
});
await mkdir("artifacts/quality", { recursive: true });
await writeValidatedJsonArtifact({
path: fixtureMode
? "artifacts/quality/i18n-fixture.json"
: "artifacts/quality/i18n.json",
schema: i18nReportArtifactSchema,
value: report,
});
// Every fixture file must be rejected on its own; one rejected file must not
// hide a directory the discovery above stopped reaching.
const unrejectedFixtures = fixtureMode
? fixtureRejectionFailure("I18n", await listSourceFiles(sourceRoot), failures)
: undefined;
if (unrejectedFixtures) {
process.stderr.write(unrejectedFixtures);
process.exit(2);
}
// A comment, punctuation or catalog words must not be rejected (0929/08-02).
if (allowedFixtureFailures.length > 0) {
process.stderr.write(
`I18n allowed fixture was rejected:\n${allowedFixtureFailures.join("\n")}\n`,
);
process.exit(2);
}
if (failures.length > 0) {
process.stderr.write(`I18n contract failed:\n${failures.join("\n")}\n`);
process.exit(1);
}
process.stdout.write(
`I18n contract: ${report.messageKeyCount} keys across ${report.localeCount} locales PASS\n`,
);