// @effect-diagnostics nodeBuiltinImport:off - Runs the real Knip CLI against a disposable on-disk project. import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; import * as NodeProcess from "node:process"; import { expect, it } from "vite-plus/test"; it("agrees with an uncached run after a new file takes over an import or an imported type changes", () => { // Keeping the disposable project here gives it the same Effect installation as the scripts. const cwd = NodeFS.mkdtempSync(NodePath.join(import.meta.dirname, ".knip-test-")); const write = (file: string, content: string) => { NodeFS.mkdirSync(NodePath.dirname(NodePath.join(cwd, file)), { recursive: true }); NodeFS.writeFileSync(NodePath.join(cwd, file), content); }; const run = () => { const result = NodeChildProcess.spawnSync( NodeProcess.execPath, [NodePath.join(import.meta.dirname, "knip-check.ts"), "--cwd", cwd], { encoding: "utf8" }, ); return { status: result.status, output: result.stdout + result.stderr }; }; const uncached = () => { NodeFS.rmSync(NodePath.join(cwd, "node_modules"), { recursive: true, force: true }); return run(); }; try { write("package.json", JSON.stringify({ private: true, workspaces: ["apps/*"] })); write( "knip.json", JSON.stringify({ // As in knip.jsonc. rules: { types: "off", nsTypes: "off" }, workspaces: { "apps/web": { entry: ["main.ts"], project: ["**/*.ts"] } }, }), ); write( "apps/web/package.json", JSON.stringify({ name: "web", type: "module", dependencies: { effect: "*" } }), ); write( "apps/web/tsconfig.json", JSON.stringify({ compilerOptions: { module: "ESNext", moduleResolution: "Bundler" } }), ); write( "apps/web/main.ts", ` import "./entry"; const kept: import("./shape/index").Shape | undefined = undefined; console.log(kept); `, ); write("apps/web/entry.ts", `export const Value = null as unknown as import("./shape").Shape;`); write( "apps/web/shape/index.ts", `import * as S from "effect/Schema"; export type Shape = typeof S.String;`, ); const first = run(); expect(first.status, first.output).toBe(0); // A second run answers from both caches. expect(run()).toEqual(first); // "./shape" now resolves here; entry.ts and shape/index.ts are untouched. write("apps/web/shape.ts", `export type Shape = { id: number };`); const takenOver = run(); expect(takenOver.status, takenOver.output).toBe(1); expect(takenOver.output).toContain("Value"); expect(takenOver.output).not.toContain("shape.ts"); expect(takenOver).toEqual(uncached()); // Only a file that entry.ts imports changes. run(); write( "apps/web/shape.ts", `import * as S from "effect/Schema"; export type Shape = typeof S.Number;`, ); const schemaAgain = run(); expect(schemaAgain.status, schemaAgain.output).toBe(0); expect(schemaAgain).toEqual(uncached()); } finally { NodeFS.rmSync(cwd, { recursive: true, force: true }); } });