Files
clean-architecture-frontend…/scripts/check-i18n.ts
T
DongHyeonka 855d22ac1b fix(i18n): 화면 문구 literal 검사를 ESLint 선택자로 옮긴다 (0929/08-02)
문제: `check:i18n`은 화면 파일 전체에 `/[가-힣]/`를 돌린다. 한국어 주석
한 줄에 실패하고, 영어 JSX 문구와 영어 접근성 이름은 통과한다. 샘플
화면에도 영어 literal이 이미 있었다(목록 h1 "Reference feature",
`limit {n}`, 목록 aria-label, 상세 "DetailPage"·"Resource ID"·"Created",
폼·상태 eyebrow). ko-KR 사용자에게 영어 문구와 스크린리더 이름이 섞인다.

고른 방법: (B) 문구 literal 검사를 ESLint `no-restricted-syntax` 선택자로
옮긴다(`eslint.config.ts`의 `screenTextSelectors`).
- 대상: 글자(`\p{L}`)가 든 `JSXText`, 표시·접근성 속성(`aria-label`,
  `aria-description`, `aria-roledescription`, `aria-valuetext`,
  `aria-placeholder`, `title`, `placeholder`, `alt`, `label`)의 문자열
  literal, 그리고 `{"..."}` 형태의 같은 literal. 주석은 AST에 없어 빠진다.
  구두점·숫자만 있는 문구는 통과한다.
- 범위(4.3절 "화면 코드"): 지난 `check:i18n`과 같은 폴더다. 공통 UI
  폴더와 `src/features/*/presentation`. 컴포넌트 갤러리
  `src/presentation/examples`는 지금처럼 뺀다. stories(`*.stories.tsx`)는
  workshop 코드라 뺀다. 테스트는 이 폴더 밖이라 대상이 아니다.
- 이 항목은 일반 `no-restricted-syntax` 목록을 대체하므로 FE-OC-019
  선택자(raw HTML, script 생성)를 함께 싣는다.
- `check:i18n`에는 catalog parity와 raw backend 메시지 검사만 남긴다.
  raw HTML은 원래 전역 FE-OC-019 ESLint 규칙이 거절한다.
- `check:i18n:fixture`는 ESLint Node API로 같은 규칙을 fixture 트리에도
  돌린다. forbidden 파일은 하나하나 거절돼야 하고(아니면 종료 코드 2),
  새 `tests/fixtures/i18n/allowed` 트리(한국어 주석, 구두점, catalog
  문구)는 통과해야 한다(거절되면 종료 코드 2). 게이트 기대값(종료 1,
  "I18n contract failed:")은 그대로다.
- fixture 추가: allowed `korean-comment.tsx`, forbidden
  `english-jsx-text.tsx`, `english-accessible-name.tsx`.
- 샘플의 영어 literal 11곳을 catalog로 옮겼다. 새 키 10개
  (`reference.list.title`·`filterLimit`·`filterTags`·`resources`,
  `reference.detail.eyebrow`·`titlePending`·`resourceId`·`createdAt`,
  `reference.form.eyebrow`, `reference.status.eyebrow`). en-US 값은
  예전 영어 문구 그대로라 en-US 화면은 바뀌지 않는다. ko-KR 화면은 한국어가
  된다.

버린 대안:
- (A) 현 상태: 두 제품이 각각 막히거나 스크립트를 고쳤다.
- (C) "행동·상태 문구"만 정규식으로 고르는 제품 정책: 한국어 문장 목록에
  기대 영어를 못 잡고, 템플릿 기본값으로 쓰기에 제품 특화다.
ESLint 설정은 제품이 자기 규칙으로 덮어쓸 수 있는 자리다(한 locale 제품,
고유명사 허용).

위험·한계:
- 식 안에서 만든 문구는 보지 못한다. template literal, 삼항식, 객체
  prop(`heading.title` 같은 것)이 그렇다. 샘플의 이런 문구는 손으로
  옮겼고, `reference-page.test.tsx`가 ko-KR main 영역을 catalog·데이터
  밖 라틴 문자로 검사해 그 빈 곳을 샘플에서만 막는다.
- 고유명사·브랜드 이름도 걸린다. 제품이 선택자를 덮어쓰거나 그 줄에
  `eslint-disable-next-line`을 쓴다.
- ko-KR route 제목(`route.REFERENCE_RESOURCE_*`)은 catalog 안의 영어라
  그대로 뒀다(라우트 제목 정리는 0929/08-06 몫).
- `tests/e2e/reference-form.spec.ts`의 ko-KR 목록 h1 기대값을 "참조
  기능"으로 바꿨다. e2e는 이 worktree에서 돌리지 않았다(webServer가
  pnpm build를 부른다).
- 시각 골든(`tests/visual`)은 /examples/ui·states·platform만 찍는다.
  샘플 화면과 nav 문구는 바뀌지 않아 골든 영향이 없다고 본다(미실행).

검증:
- RED(수정 전):
  - E1 한글 주석 변이: `node scripts/check-i18n.ts` -> "hardcoded common
    user-facing locale literal in .../reference-resource-status-page.tsx",
    exit 1
  - E1b 영어 JSX 문구 변이: `check-i18n.ts` PASS exit 0, `eslint` exit 0
  - `check-i18n.ts --fixture` -> "I18n fixture was not rejected:
    english-accessible-name.tsx, english-jsx-text.tsx", exit 2
  - 새 ko-KR main 테스트: "limit 5 · tags ..." 가 남아 실패
- GREEN(수정 후):
  - E1 변이: `check-i18n.ts` PASS, `eslint` exit 0
  - E1b 변이: `eslint` -> 42:13 no-restricted-syntax, exit 1
  - `check-i18n.ts` PASS(224 keys), `--fixture` -> forbidden 7개 모두
    거절, "I18n contract failed:", exit 1. allowed에 영어 문구를 넣으면
    "I18n allowed fixture was rejected", exit 2
  - ko-KR main 테스트 통과
- `npx eslint src scripts tests recipes .storybook ... --max-warnings=0`
  통과, app·test·node 타입 검사 통과
- vitest: tests/unit + tests/component 209 files 2725 tests,
  tests/features 등 25 files 141 tests 통과
- `check-registries.ts` PASS, `check-ci-contract.ts` PASS,
  `verify-documentation-readiness.ts` PASS_SCOPED

Refs: docs/reviews/2026-09-29-maturity-review/08-presentation.md 08-02, 4.3
2026-11-03 00:54:18 +09:00

181 lines
6.7 KiB
TypeScript

import { mkdir, readFile, readdir } from "node:fs/promises";
import { i18nReportArtifactSchema } from "./contracts/release-artifacts.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` is the component gallery and stays out of 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 fixtureFiles = fixtureMode ? await listSourceFiles(sourceRoot) : [];
const unrejectedFixtures = fixtureFiles.filter(
(file) => !failures.some((failure) => failure.endsWith(file)),
);
if (fixtureMode && (fixtureFiles.length === 0 || unrejectedFixtures.length > 0)) {
process.stderr.write(
`I18n fixture was not rejected:\n${unrejectedFixtures.join("\n") || "(no fixture files found)"}\n`,
);
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`,
);