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
This commit is contained in:
@@ -934,30 +934,6 @@ export default [
|
||||
"react-hooks/rules-of-hooks": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
files: [
|
||||
`tests/fixtures/architecture/forbidden/**/*.${sourceExtensions}`,
|
||||
],
|
||||
rules: {
|
||||
"no-restricted-imports": restrictedImports(
|
||||
[
|
||||
"**/adapters/**",
|
||||
"**/application/ports/out/**",
|
||||
"@tanstack/**",
|
||||
"react",
|
||||
"react-dom",
|
||||
"**/application/**",
|
||||
],
|
||||
"forbidden architecture fixture: this import must be rejected.",
|
||||
),
|
||||
"no-restricted-globals": [
|
||||
"error",
|
||||
"fetch",
|
||||
"localStorage",
|
||||
"sessionStorage",
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: [
|
||||
`tests/fixtures/browser-file-storage-boundaries/forbidden/**/*.${sourceExtensions}`,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { parseAsync } from "@babel/core";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdir, readFile, readdir } from "node:fs/promises";
|
||||
import { dirname, extname, isAbsolute, relative, resolve, sep } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
import { ESLint } from "eslint";
|
||||
|
||||
import { architectureDependencyReportArtifactSchema } from "./contracts/release-artifacts.ts";
|
||||
import { checkArchitectureLintFixtures } from "./lib/architecture-lint-fixtures.ts";
|
||||
import { formatArchitectureViolation } from "./lib/architecture-violation-message.ts";
|
||||
import { writeValidatedJsonArtifact } from "./lib/validated-json-artifact.ts";
|
||||
|
||||
@@ -79,7 +81,6 @@ const architectureConfig = parseArchitectureConfig(
|
||||
const architectureRules = architectureConfig.forbidden;
|
||||
const sourceExtensionPattern = /\.(?:ts|tsx|mts|cts)$/u;
|
||||
const declarationExtensionPattern = /\.d\.(?:ts|mts|cts)$/u;
|
||||
const lintFixtureExtensionPattern = sourceExtensionPattern;
|
||||
const forbiddenJavaScriptExtensionPattern = /\.(?:js|jsx|mjs|cjs)$/u;
|
||||
const forbiddenLocalJavaScriptSpecifierPattern =
|
||||
/\.(?:js|jsx|mjs|cjs)(?:[?#]|$)/u;
|
||||
@@ -89,13 +90,6 @@ const relativeSpecifierPattern = /^\.{1,2}(?:\/|$)/u;
|
||||
|
||||
await mkdir(dirname(qualityArtifact), { recursive: true });
|
||||
|
||||
const configuredPnpmCli = process.env.npm_execpath;
|
||||
|
||||
if (!configuredPnpmCli) {
|
||||
throw new Error("check:architecture must run through the pnpm script");
|
||||
}
|
||||
const pnpmCli = configuredPnpmCli;
|
||||
|
||||
if (
|
||||
(architectureConfig.allowed?.length ?? 0) > 0 ||
|
||||
(architectureConfig.required?.length ?? 0) > 0
|
||||
@@ -106,12 +100,6 @@ if (
|
||||
}
|
||||
validateArchitectureRules(architectureRules);
|
||||
|
||||
function runPnpm(arguments_: string[]) {
|
||||
return spawnSync(process.execPath, [pnpmCli, ...arguments_], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
// 12-05 (D-11): this graph is the only architecture checker. dependency-cruiser
|
||||
// 18 cannot parse TypeScript 7, so it cruised zero modules and still passed.
|
||||
// .dependency-cruiser.json keeps its name and is read here as the rule file.
|
||||
@@ -211,68 +199,22 @@ process.stdout.write(
|
||||
`TypeScript-only source policy: PASS (${typeScriptOnlyPolicy.checkedRoots.join(", ")}; no fixture exceptions)\n`,
|
||||
);
|
||||
|
||||
const allowed = runPnpm([
|
||||
"exec",
|
||||
"eslint",
|
||||
"tests/fixtures/architecture/allowed",
|
||||
"--no-ignore",
|
||||
"--max-warnings=0",
|
||||
]);
|
||||
|
||||
const forbidden = runPnpm([
|
||||
"exec",
|
||||
"eslint",
|
||||
"tests/fixtures/architecture/forbidden",
|
||||
"--no-ignore",
|
||||
"--max-warnings=0",
|
||||
]);
|
||||
|
||||
async function fixtureFiles(directory: string): Promise<string[]> {
|
||||
const entries = await readdir(directory, { withFileTypes: true });
|
||||
const files = await Promise.all(
|
||||
entries.map((entry) => {
|
||||
const target = `${directory}/${entry.name}`;
|
||||
return entry.isDirectory()
|
||||
? fixtureFiles(target)
|
||||
: lintFixtureExtensionPattern.test(entry.name)
|
||||
? [target]
|
||||
: [];
|
||||
}),
|
||||
);
|
||||
return files.flat();
|
||||
}
|
||||
|
||||
const forbiddenResults = await Promise.all(
|
||||
(await fixtureFiles("tests/fixtures/architecture/forbidden")).map((file) => ({
|
||||
file,
|
||||
result: runPnpm([
|
||||
"exec",
|
||||
"eslint",
|
||||
file,
|
||||
"--no-ignore",
|
||||
"--max-warnings=0",
|
||||
]),
|
||||
})),
|
||||
);
|
||||
const acceptedForbidden = forbiddenResults.filter(
|
||||
({ result }) => result.status === 0,
|
||||
);
|
||||
|
||||
if (
|
||||
allowed.status !== 0 ||
|
||||
forbidden.status === 0 ||
|
||||
acceptedForbidden.length > 0
|
||||
) {
|
||||
process.stderr.write(allowed.stderr || allowed.stdout);
|
||||
process.stderr.write(forbidden.stderr || forbidden.stdout);
|
||||
for (const { file } of acceptedForbidden) {
|
||||
process.stderr.write(`Forbidden fixture was accepted: ${file}\n`);
|
||||
// 1103/12-04. Each fixture is linted under the production configuration of
|
||||
// the path it stands for, and a forbidden one must be reported by the rule it
|
||||
// names (scripts/lib/architecture-lint-fixtures.ts).
|
||||
const lintFixtures = await checkArchitectureLintFixtures({
|
||||
root: projectRoot,
|
||||
linter: new ESLint({ cwd: projectRoot }),
|
||||
});
|
||||
if (lintFixtures.failures.length > 0) {
|
||||
for (const failure of lintFixtures.failures) {
|
||||
process.stderr.write(`Architecture lint fixture: ${failure}\n`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
`Architecture fixtures: allowed PASS, ${forbiddenResults.length} forbidden rejected\n`,
|
||||
`Architecture fixtures: ${lintFixtures.allowed} allowed PASS, ${lintFixtures.forbidden} forbidden rejected by the production rule for their layer\n`,
|
||||
);
|
||||
|
||||
async function analyzeSourceGraph(
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
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),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { cp, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { ESLint } from "eslint";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ARCHITECTURE_LINT_FIXTURE_ROOT,
|
||||
checkArchitectureLintFixtures,
|
||||
} from "../../scripts/lib/architecture-lint-fixtures.ts";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
// 1103/12-04. The fixtures used to be linted under an ESLint entry of their
|
||||
// own, so deleting a production layer rule still left them "rejected".
|
||||
describe("architecture lint fixtures", () => {
|
||||
it("are rejected by the production rules for their layer, and only the forbidden ones", async () => {
|
||||
const result = await checkArchitectureLintFixtures({
|
||||
root: process.cwd(),
|
||||
linter: new ESLint({ cwd: process.cwd() }),
|
||||
});
|
||||
expect(result).toEqual({ allowed: 3, forbidden: 9, failures: [] });
|
||||
}, 30_000);
|
||||
|
||||
it("fail when the production presentation rules lose their layer bans", async () => {
|
||||
const result = await checkArchitectureLintFixtures({
|
||||
root: process.cwd(),
|
||||
linter: new ESLint({
|
||||
cwd: process.cwd(),
|
||||
overrideConfig: [{
|
||||
files: ["src/presentation/**/*.{ts,tsx}"],
|
||||
rules: { "no-restricted-globals": "off", "no-restricted-imports": "off" },
|
||||
}],
|
||||
}),
|
||||
});
|
||||
expect(result.failures).toEqual(expect.arrayContaining([
|
||||
expect.stringContaining("forbidden/presentation-direct-fetch.tsx (as src/presentation/"),
|
||||
expect.stringContaining("forbidden/presentation-imports-adapter.ts (as src/presentation/"),
|
||||
expect.stringContaining("forbidden/template-imports-application.tsx (as src/presentation/templates/"),
|
||||
]));
|
||||
expect(result.failures.join("\n")).not.toMatch(/application-imports|domain-imports/u);
|
||||
}, 30_000);
|
||||
|
||||
it("fail for a fixture nobody says what must reject", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "architecture-lint-fixtures-"));
|
||||
roots.push(root);
|
||||
await cp(ARCHITECTURE_LINT_FIXTURE_ROOT, path.join(root, ARCHITECTURE_LINT_FIXTURE_ROOT), {
|
||||
recursive: true,
|
||||
});
|
||||
await writeFile(
|
||||
path.join(root, ARCHITECTURE_LINT_FIXTURE_ROOT, "forbidden/unlisted.ts"),
|
||||
"export const unlisted = true;\n",
|
||||
);
|
||||
const result = await checkArchitectureLintFixtures({
|
||||
root,
|
||||
linter: { lintText: async () => [{ messages: [{ ruleId: "no-restricted-imports", message: "x" }] }] },
|
||||
});
|
||||
expect(result.failures).toContain(
|
||||
"forbidden/unlisted.ts: not listed in ARCHITECTURE_LINT_FIXTURES, so nothing says what must reject it",
|
||||
);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user