diff --git a/src/cli/laws-probe-adopter.test.ts b/src/cli/laws-probe-adopter.test.ts new file mode 100644 index 0000000..c87f705 --- /dev/null +++ b/src/cli/laws-probe-adopter.test.ts @@ -0,0 +1,44 @@ +import { symlinkSync } from "node:fs"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { REAL_TOOL_TIMEOUT } from "../gate/test-support-timeouts.ts"; +import { cleanTemp, put, tempDir } from "../laws/probe/testkit.ts"; +import { failing, KIT, probeFrom, probeProcess } from "./test-support-probe.ts"; + +afterAll(cleanTemp); + +/** + * A real astro-site adopter: its tsconfig names its own sources and says nothing of `.web-tops/`, and its ESLint + * config is the kit's astro preset, which parses a `.astro` file with the project's `tsconfig.json`. The probe's twins + * are not in that project, so the probe gives ESLint a tsconfig that is. + */ +function adopter(): string { + const dir = tempDir(); + symlinkSync(join(KIT, "node_modules"), join(dir, "node_modules")); + put(dir, { + "tsconfig.json": JSON.stringify({ extends: join(KIT, "tsconfig.json"), include: ["src/**/*"] }), + "package.json": '{ "type": "module", "dependencies": { "astro": "5.0.0" } }\n', + "src/page.astro": "---\nconst title = 'a';\n---\n

{title}

\n", + "eslint.config.js": [ + `import { eslintPreset } from "${join(KIT, "src/presets/eslint.js")}";`, + 'export default await eslintPreset({ variant: "astro", tsconfigRootDir: import.meta.dirname, class: "astro-site" });', + "", + ].join("\n"), + }); + return dir; +} + +describe("the Astro twins are proven in an adopter whose tsconfig does not include the probe's directory", () => { + it( + "W-49 passes over its .astro twins, none skipped and none not evaluated", + () => { + const run = probeFrom( + probeProcess(adopter(), "--class", "astro-site", "--law", "W-49", "--json"), + ); + expect(failing(run.report)).toEqual([]); + expect(run.code).toBe(0); + expect(run.report.skipped).toEqual([]); + }, + REAL_TOOL_TIMEOUT, + ); +}); diff --git a/src/laws/probe/run.test.ts b/src/laws/probe/run.test.ts index a8eb46a..d04b1d0 100644 --- a/src/laws/probe/run.test.ts +++ b/src/laws/probe/run.test.ts @@ -1,4 +1,4 @@ -import { realpathSync, writeFileSync } from "node:fs"; +import { readFileSync, realpathSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { afterAll, describe, expect, it } from "vitest"; import type { Exec, ExecResult } from "../../gate/types.ts"; @@ -154,17 +154,21 @@ describe("G3b the runner lints the twins once and compiles them once, then judge expect(calls).toHaveLength(2); }); - it("passes the ESLint config given with --config, and none when there is none", async () => { - const cwd = project(); - const withConfig: Call[] = []; - const named = request(cwd, fake({ eslintOutput: "[]" }, withConfig), { + it("passes a wrapper of the ESLint config given, which imports it", async () => { + const calls: Call[] = []; + const named = request(project(), fake({ eslintOutput: "[]" }, calls), { eslintConfig: "/x/e.js", }); await runProbe(named); - const args = withConfig[0]?.args ?? []; - expect(args[args.indexOf("--config") + 1]).toBe("/x/e.js"); + const args = String(calls[0]?.args); + const wrapper = args.split(",")[args.split(",").indexOf("--config") + 1]; + expect(String(wrapper).endsWith(".web-tops/out/laws-probe.eslint.config.mjs")).toBe(true); + expect(readFileSync(String(wrapper), "utf8")).toContain('await import("file:///x/e.js")'); + }); + + it("passes no ESLint config when none is given and the project has none", async () => { const without: Call[] = []; - await runProbe(request(cwd, fake({ eslintOutput: "[]" }, without))); + await runProbe(request(project(), fake({ eslintOutput: "[]" }, without))); expect(without[0]?.args).not.toContain("--config"); }); diff --git a/src/laws/probe/run.ts b/src/laws/probe/run.ts index 82cb123..014c91b 100644 --- a/src/laws/probe/run.ts +++ b/src/laws/probe/run.ts @@ -14,6 +14,7 @@ import { splitTwins, stylelintIgnore, } from "./twins.ts"; +import { defaultConfig, writeWrapper } from "./wrapper.ts"; import type { Expectation, Observed, ProbeLaw, ProbeReport, SkippedTwin, Twin } from "./types.ts"; export interface ProbeRequest { @@ -122,9 +123,17 @@ function lintTargets(request: ProbeRequest, twins: readonly Twin[]): string[] { return [relative(request.cwd, request.scratch), ...astro]; } +/** The config ESLint is given: the project's own, with the twins' tsconfig for the type-aware rules (R109). */ +function configArgs(request: ProbeRequest): string[] { + const config = request.eslintConfig ?? defaultConfig(request.cwd); + return config === undefined + ? [] + : ["--config", writeWrapper(config, request.scratch, request.cwd)]; +} + async function eslintPass(request: ProbeRequest, twins: readonly Twin[]): Promise { const output = join(request.scratch, "eslint.json"); - const config = request.eslintConfig === undefined ? [] : ["--config", request.eslintConfig]; + const config = configArgs(request); const args = ["--no-ignore", "--format", "json", "--output-file", output, ...config]; const result = await runTool(request, "eslint", [...args, ...lintTargets(request, twins)]); const failed = stopped("eslint", result, [0, 1]); diff --git a/src/laws/probe/wrapper.test.ts b/src/laws/probe/wrapper.test.ts new file mode 100644 index 0000000..4429209 --- /dev/null +++ b/src/laws/probe/wrapper.test.ts @@ -0,0 +1,72 @@ +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { afterAll, describe, expect, it } from "vitest"; +import { cleanTemp, put, tempDir } from "./testkit.ts"; +import { defaultConfig, wrapperName, wrapperSource, writeWrapper } from "./wrapper.ts"; + +afterAll(cleanTemp); + +/** R109: the twins' type-aware rules read the scratch tsconfig, whatever project the adopter's config names. */ + +describe("the wrapper config", () => { + it("imports the project's config and adds one block, for the twins, that points the parser at the scratch tsconfig", () => { + const text = wrapperSource("/p/eslint.config.js", "/p/.web-tops/out/laws-probe", "/p"); + expect(text).toContain( + `await import(${JSON.stringify(pathToFileURL("/p/eslint.config.js").href)})`, + ); + expect(text).toContain("export default [...(Array.isArray(base) ? base : [base]), twins];"); + expect(text).toContain('files: [".web-tops/out/laws-probe/**/*.{ts,tsx,mts,cts,astro}"]'); + expect(text).toContain( + 'parserOptions: {"projectService":false,"project":["/p/.web-tops/out/laws-probe/tsconfig.json"],"tsconfigRootDir":"/p/.web-tops/out/laws-probe"}', + ); + }); + + it("is written beside the scratch directory, not in it, so the probe does not lint it", () => { + const cwd = tempDir(); + const scratch = join(cwd, ".web-tops", "out", "laws-probe"); + mkdirSync(scratch, { recursive: true }); + const path = writeWrapper(join(cwd, "eslint.config.js"), scratch, cwd); + expect(path).toBe(join(cwd, ".web-tops", "out", wrapperName())); + expect(readFileSync(path, "utf8")).toContain("await import("); + expect(existsSync(join(scratch, wrapperName()))).toBe(false); + }); +}); + +describe("the wrapper config, exactly", () => { + it("is these lines, with a newline at the end", () => { + expect(wrapperSource("/p/eslint.config.js", "/p/s", "/p")).toBe( + [ + 'const loaded = await import("file:///p/eslint.config.js");', + "const base = loaded.default ?? loaded;", + 'const twins = { files: ["s/**/*.{ts,tsx,mts,cts,astro}"], languageOptions: { parserOptions: {"projectService":false,"project":["/p/s/tsconfig.json"],"tsconfigRootDir":"/p/s"} } };', + "export default [...(Array.isArray(base) ? base : [base]), twins];", + "", + ].join("\n"), + ); + }); +}); + +describe("the config ESLint finds for a project", () => { + it.each(["js", "mjs", "cjs", "ts", "mts", "cts"])("finds eslint.config.%s", (extension) => { + const cwd = tempDir(); + put(cwd, { [`eslint.config.${extension}`]: "export default [];\n" }); + expect(defaultConfig(cwd)).toBe(join(cwd, `eslint.config.${extension}`)); + }); + + it("is the first of its names in the directory, js before mjs", () => { + const cwd = tempDir(); + put(cwd, { + "eslint.config.mjs": "export default [];\n", + "eslint.config.js": "export default [];\n", + }); + expect(defaultConfig(cwd)).toBe(join(cwd, "eslint.config.js")); + }); + + it("is the nearest one above when the directory has none, and none when no directory has one", () => { + const cwd = tempDir(); + put(cwd, { "eslint.config.cts": "export default [];\n", "a/b/x.txt": "x\n" }); + expect(defaultConfig(join(cwd, "a", "b"))).toBe(join(cwd, "eslint.config.cts")); + expect(defaultConfig("/")).toBeUndefined(); + }); +}); diff --git a/src/laws/probe/wrapper.ts b/src/laws/probe/wrapper.ts new file mode 100644 index 0000000..cad2691 --- /dev/null +++ b/src/laws/probe/wrapper.ts @@ -0,0 +1,47 @@ +import { existsSync, writeFileSync } from "node:fs"; +import { dirname, join, relative } from "node:path"; +import { pathToFileURL } from "node:url"; + +/** The name of the wrapper config, beside the scratch directory: it is not a file the probe lints. */ +export const wrapperName = (): string => "laws-probe.eslint.config.mjs"; + +/** + * An ESLint config that is the project's own, with one block more for the twins: type-aware rules read the scratch + * `tsconfig.json`, which extends the project's and includes every twin, whatever `project` the project's config names. + * A config that names the project's own `tsconfig.json` would not find the twins, which are not in that project. + */ +export function wrapperSource(config: string, scratch: string, cwd: string): string { + const files = `${relative(cwd, scratch)}/**/*.{ts,tsx,mts,cts,astro}`; + const parserOptions = { + projectService: false, + project: [join(scratch, "tsconfig.json")], + tsconfigRootDir: scratch, + }; + return [ + `const loaded = await import(${JSON.stringify(pathToFileURL(config).href)});`, + "const base = loaded.default ?? loaded;", + `const twins = { files: [${JSON.stringify(files)}], languageOptions: { parserOptions: ${JSON.stringify(parserOptions)} } };`, + "export default [...(Array.isArray(base) ? base : [base]), twins];", + "", + ].join("\n"); +} + +/** The names ESLint looks for a flat config under, in its own order. */ +const configNames = (): readonly string[] => + ["js", "mjs", "cjs", "ts", "mts", "cts"].map((extension) => `eslint.config.${extension}`); + +/** The flat config ESLint finds for a project: the first of its names in the directory, or in the nearest one above. */ +export function defaultConfig(cwd: string): string | undefined { + const found = configNames() + .map((name) => join(cwd, name)) + .find((path) => existsSync(path)); + const parent = dirname(cwd); + return found ?? (parent === cwd ? undefined : defaultConfig(parent)); +} + +/** Writes the wrapper config beside the scratch directory and returns its path. */ +export function writeWrapper(config: string, scratch: string, cwd: string): string { + const path = join(dirname(scratch), wrapperName()); + writeFileSync(path, wrapperSource(config, scratch, cwd)); + return path; +}