Files
clean-architecture-frontend…/scripts/lib/architecture-lint-fixtures.ts
DongHyeonka d1db7e7887 fix(architecture): 금지 fixture를 그 계층의 운영 ESLint 설정으로 검사한다
문제
tests/fixtures/architecture/forbidden/**에는 fixture 전용 ESLint 블록이
붙어 있었다. 모든 계층의 금지 import와 fetch·localStorage·sessionStorage
금지를 합친 것이다. check-architecture.ts는 fixture마다 ESLint 종료 코드가
0이 아니면 거부됐다고 셌다. 그래서 운영 src/presentation/** 블록에서 계층
import 금지와 fetch 금지를 지워도(변이 M2) check:architecture는 "9 forbidden
rejected"로 통과했다. 전역 fetch·localStorage 금지는 이 ESLint 블록 말고 지키는
검사가 없다.

고른 방법
- 새 scripts/lib/architecture-lint-fixtures.ts가 fixture마다 그것이 대표하는
  운영 경로(lintAs, 예: src/presentation/__architecture_fixture__/…)와 거부해야
  하는 규칙(rejectedBy)을 적는다. ESLint API lintText(code, { filePath })로
  그 경로의 운영 설정을 그대로 적용한다. 금지 fixture는 그 규칙이 보고해야
  통과하고, 허용 fixture는 계층 규칙(no-restricted-imports·globals)이 아무것도
  보고하지 않아야 통과한다. 목록에 없는 fixture 파일도 실패로 센다.
- domain fixture는 domain 코드가 실제로 사는 src/features/*/domain 블록으로
  검사한다(최상위 src/domain 폴더는 없다).
- fixture 전용 ESLint 블록을 지운다. check-architecture.ts에서 쓰이지 않게 된
  pnpm 하위 프로세스 실행과 npm_execpath 요구를 지운다.
- 버린 대안: 금지 fixture 삭제. import 방향은 그래프가 지키지만 전역 금지의
  검출이 0이 된다. 종료 코드만 보고 운영 경로로 옮기기. 다른 규칙(화면 문구
  등)이 걸려도 거부로 센다.

위험·한계
- 계층 규칙 이름이 바뀌면 fixture 표의 rejectedBy도 같이 고쳐야 한다(고치지
  않으면 실패로 드러난다).
- 출력 문구가 "3 allowed PASS, 9 forbidden rejected by the production rule for
  their layer"로 바뀐다. 이 문구를 읽는 스크립트는 없다.

검증
- RED: 수정 전 변이 M2(운영 presentation 블록의 계층 import 금지와 fetch 금지
  삭제)에서 check:architecture exit 0, "9 forbidden rejected".
- 수정 뒤 같은 변이에서 check:architecture exit 1, presentation fixture 5개가
  "was accepted"로 실패. 되돌린 뒤 exit 0.
- 새 tests/unit/architecture-lint-fixtures.test.ts 3건(운영 설정 통과,
  overrideConfig로 규칙을 끄면 실패, 목록 밖 fixture 실패) 통과.
  architecture-report 3건 통과. check:types 통과, eslint 통과.

Refs: docs/reviews/2026-11-03-maturity-review/12-guardrails-ci.md 12-04
2026-11-04 21:10:19 +09:00

178 lines
6.8 KiB
TypeScript

import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
/**
* 1103/12-04. The architecture lint fixtures are linted under the production
* configuration of the layer they stand for.
*
* They used to be linted where they live, under tests/, by an ESLint entry of
* their own that banned every layer's imports and globals at once, and a
* fixture counted as rejected whenever ESLint exited non-zero. Deleting the
* production rule for a layer therefore still left "9 forbidden rejected":
* presentation code could call `fetch` and the fixtures said it could not.
*
* Each fixture is now linted as if it were the file at `lintAs`, so exactly
* the production entries for that path apply, and a forbidden fixture passes
* only when the rule named in `rejectedBy` reports it.
*/
export type ArchitectureLintRule = "no-restricted-imports" | "no-restricted-globals";
export type ArchitectureLintFixture = Readonly<{
/** Relative to tests/fixtures/architecture. */
file: string;
/** The production path whose ESLint configuration the fixture is linted under. */
lintAs: string;
/** For a forbidden fixture: the production rule that must reject it. */
rejectedBy?: ArchitectureLintRule;
}>;
export const ARCHITECTURE_LINT_FIXTURE_ROOT = "tests/fixtures/architecture";
const LAYER_RULES: ReadonlySet<string> = new Set<ArchitectureLintRule>([
"no-restricted-imports",
"no-restricted-globals",
]);
const at = (layer: string, file: string) =>
`${layer}/__architecture_fixture__/${path.posix.basename(file)}`;
export const ARCHITECTURE_LINT_FIXTURES: readonly ArchitectureLintFixture[] = Object.freeze([
...[
"allowed/bootstrap-composes-adapter.ts",
].map((file) => ({ file, lintAs: at("src/bootstrap", file) })),
...[
"allowed/presentation-facade.ts",
"allowed/presentation-facade.tsx",
].map((file) => ({ file, lintAs: at("src/presentation", file) })),
...[
"forbidden/application-imports-adapter.ts",
"forbidden/application-imports-tanstack.ts",
].map((file) => ({
file,
lintAs: at("src/application", file),
rejectedBy: "no-restricted-imports" as const,
})),
// Domain code lives inside features; src/features/*/domain is the entry
// that applies to it.
{
file: "forbidden/domain-imports-react.ts",
lintAs: "src/features/__architecture_fixture__/domain/domain-imports-react.ts",
rejectedBy: "no-restricted-imports",
},
{
file: "forbidden/presentation-direct-fetch.tsx",
lintAs: at("src/presentation", "presentation-direct-fetch.tsx"),
rejectedBy: "no-restricted-globals",
},
...[
"forbidden/presentation-imports-adapter.ts",
"forbidden/presentation-imports-adapter.tsx",
"forbidden/presentation-imports-output-port.tsx",
"forbidden/presentation-imports-tanstack.tsx",
].map((file) => ({
file,
lintAs: at("src/presentation", file),
rejectedBy: "no-restricted-imports" as const,
})),
{
file: "forbidden/template-imports-application.tsx",
lintAs: at("src/presentation/templates", "template-imports-application.tsx"),
rejectedBy: "no-restricted-imports",
},
]);
type LintMessage = Readonly<{
ruleId: string | null;
message: string;
fatal?: boolean;
line?: number;
}>;
export type ArchitectureLinter = Readonly<{
lintText(
code: string,
options: Readonly<{ filePath: string; warnIgnored: boolean }>,
): Promise<readonly Readonly<{ messages: readonly LintMessage[] }>[]>;
}>;
export type ArchitectureLintFixtureResult = Readonly<{
allowed: number;
forbidden: number;
failures: readonly string[];
}>;
const SOURCE_FILE = /\.(?:ts|tsx)$/u;
async function filesBelow(root: string, directory: string): Promise<string[]> {
const entries = await readdir(path.join(root, directory), { withFileTypes: true });
const files = await Promise.all(entries.map((entry) => {
const relative = path.posix.join(directory, entry.name);
if (entry.isDirectory()) return filesBelow(root, relative);
return SOURCE_FILE.test(entry.name) ? [relative] : [];
}));
return files.flat();
}
export async function checkArchitectureLintFixtures(input: Readonly<{
root: string;
linter: ArchitectureLinter;
fixtures?: readonly ArchitectureLintFixture[];
}>): Promise<ArchitectureLintFixtureResult> {
const fixtures = input.fixtures ?? ARCHITECTURE_LINT_FIXTURES;
const failures: string[] = [];
const onDisk = new Set([
...await filesBelow(input.root, path.posix.join(ARCHITECTURE_LINT_FIXTURE_ROOT, "allowed")),
...await filesBelow(input.root, path.posix.join(ARCHITECTURE_LINT_FIXTURE_ROOT, "forbidden")),
].map((file) => path.posix.relative(ARCHITECTURE_LINT_FIXTURE_ROOT, file)));
const listed = new Set(fixtures.map(({ file }) => file));
for (const file of [...onDisk].filter((candidate) => !listed.has(candidate)).sort()) {
failures.push(`${file}: not listed in ARCHITECTURE_LINT_FIXTURES, so nothing says what must reject it`);
}
for (const fixture of fixtures) {
const forbidden = fixture.file.startsWith("forbidden/");
if (forbidden !== (fixture.rejectedBy !== undefined)) {
failures.push(`${fixture.file}: a forbidden fixture names its rule and an allowed one names none`);
continue;
}
if (!onDisk.has(fixture.file)) {
failures.push(`${fixture.file}: listed fixture does not exist`);
continue;
}
const code = await readFile(
path.join(input.root, ARCHITECTURE_LINT_FIXTURE_ROOT, fixture.file),
"utf8",
);
const [result] = await input.linter.lintText(code, {
filePath: path.join(input.root, fixture.lintAs),
warnIgnored: true,
});
const messages = result?.messages ?? [];
const unlinted = messages.filter((message) => message.fatal || message.ruleId === null);
if (unlinted.length > 0) {
failures.push(
`${fixture.file} (as ${fixture.lintAs}) was not linted: ${unlinted.map(({ message }) => message).join("; ")}`,
);
continue;
}
const layerMessages = messages.filter(({ ruleId }) => ruleId !== null && LAYER_RULES.has(ruleId));
if (fixture.rejectedBy !== undefined) {
if (!layerMessages.some(({ ruleId }) => ruleId === fixture.rejectedBy)) {
failures.push(
`${fixture.file} (as ${fixture.lintAs}) was accepted: the production ${fixture.rejectedBy} rule for that path no longer rejects it`,
);
}
} else if (layerMessages.length > 0) {
failures.push(
`${fixture.file} (as ${fixture.lintAs}) was rejected: ${layerMessages
.map(({ ruleId, line, message }) => `${ruleId} at line ${line ?? "?"}: ${message}`)
.join("; ")}`,
);
}
}
return Object.freeze({
allowed: fixtures.filter(({ rejectedBy }) => rejectedBy === undefined).length,
forbidden: fixtures.filter(({ rejectedBy }) => rejectedBy !== undefined).length,
failures: Object.freeze(failures),
});
}