import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import { describe, expect, it } from "vitest"; // src/.generated is gitignored (R-0): every entry point that loads the product // index must render it first, or a fresh checkout cannot run the gates. const GENERATE = "node scripts/generate-product-feature-index.ts && "; // Entry points the import walk below cannot see (tsc, vite, storybook). const NON_NODE_ENTRY_SCRIPTS = [ "dev", "build:app-only", "storybook", "build:storybook", "check:types:app", "check:types:node", "check:types:test", "check:types:fixture:route-runtime", "check:types:fixture:page-action", "check:types:fixture:icon-button", "check:types:fixture:i18n-key", "check:types:fixture:i18n-params", ] as const; const ROOT = process.cwd(); const GENERATED_DIR = path.join(ROOT, "src/.generated"); const RELATIVE_IMPORT = /(?:import|export)\s[^'"]*?from\s+["'](\.{1,2}\/[^"']+)["']|import\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)/gu; function reachesGeneratedIndex(file: string, seen = new Set()): boolean { if (seen.has(file) || !existsSync(file)) return false; seen.add(file); for (const match of readFileSync(file, "utf8").matchAll(RELATIVE_IMPORT)) { const resolved = path.resolve(path.dirname(file), match[1] ?? match[2] ?? ""); if (resolved.startsWith(GENERATED_DIR)) return true; if (reachesGeneratedIndex(resolved, seen)) return true; } return false; } function packageScripts(): Record { return (JSON.parse(readFileSync("package.json", "utf8")) as { scripts: Record }) .scripts; } describe("product index entry points", () => { it("renders the generated index before tsc, vite and storybook entry points", () => { const scripts = packageScripts(); for (const name of NON_NODE_ENTRY_SCRIPTS) { expect(scripts[name]?.startsWith(GENERATE), name).toBe(true); } }); it("renders the generated index before every node script that imports it", () => { const missing = Object.entries(packageScripts()) .filter(([, command]) => !command.startsWith(GENERATE)) .filter(([, command]) => [...command.matchAll(/node\s+(scripts\/[\w./-]+\.ts)/gu)] .map((match) => match[1] ?? "") .filter((entry) => entry !== "scripts/run-vitest.ts") .some((entry) => reachesGeneratedIndex(path.join(ROOT, entry))), ) .map(([name]) => name); expect(missing).toEqual([]); }); it("renders the generated index before every Vitest run", () => { const runner = readFileSync("scripts/run-vitest.ts", "utf8"); expect(runner.indexOf("generate-product-feature-index.ts")).toBeGreaterThan(-1); expect(runner.indexOf("generate-product-feature-index.ts")).toBeLessThan( runner.indexOf("vitestEntry, ...process.argv"), ); }); });