diff --git a/eslint.config.ts b/eslint.config.ts index 2e55d3c6..b5912fd1 100644 --- a/eslint.config.ts +++ b/eslint.config.ts @@ -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}`, diff --git a/scripts/check-architecture.ts b/scripts/check-architecture.ts index 2413162c..42405580 100644 --- a/scripts/check-architecture.ts +++ b/scripts/check-architecture.ts @@ -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 { - 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( diff --git a/scripts/lib/architecture-lint-fixtures.ts b/scripts/lib/architecture-lint-fixtures.ts new file mode 100644 index 00000000..f2570043 --- /dev/null +++ b/scripts/lib/architecture-lint-fixtures.ts @@ -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 = new Set([ + "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[]>; +}>; + +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 { + 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 { + 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), + }); +} diff --git a/tests/unit/architecture-lint-fixtures.test.ts b/tests/unit/architecture-lint-fixtures.test.ts new file mode 100644 index 00000000..0c37b46d --- /dev/null +++ b/tests/unit/architecture-lint-fixtures.test.ts @@ -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", + ); + }); +});