import { access, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { CreateFeatureError, planFeature, randomTopicSuffix, writeFeatureFiles, type FeatureRequest, type InstalledFacts, } from "../../scripts/create-feature.ts"; import { PLACEHOLDER_CONTRACT_PACKAGE_DIGEST } from "../../src/contracts/deployment-admission.ts"; /** * U7. What `pnpm create:feature` renders, checked without touching the * repository. test:feature-scaffold writes a feature into a copy and runs the * gates on it; this file covers the ids, the topic, the order and the refusals. */ const INSTALLED: InstalledFacts = Object.freeze({ appIds: ["template-app"], featureIds: ["orders-feature", "drafts-feature"], contexts: [ { id: "orders-context", routePath: "orders/*" }, { id: "billing-context", routePath: "billing/*" }, ], contextDirectories: ["orders-context", "billing-context"], routes: [ { routeId: "APP_HOME", path: "/", chunkId: "route-home", navigationOrder: 10 }, { routeId: "ORDERS_LIST", path: "/orders", chunkId: "route-orders-list", navigationOrder: 50 }, { routeId: "NOT_FOUND", path: "*", chunkId: "route-not-found", navigationOrder: null }, ], topics: ["qinv.0000000000000000000000000a"], messageKeys: ["route.APP_HOME.title", "home.list.title"], }); const TOPIC_SUFFIX = "abcdefghjkmnpqrstvwxyz0123"; function plan(request: FeatureRequest, installed: InstalledFacts = INSTALLED) { return planFeature(request, installed, () => TOPIC_SUFFIX); } function rendered(request: FeatureRequest): string { return [...plan(request).files.values()].join("\n"); } describe("create:feature rendering", () => { it("prefixes every global id with the feature and carries no sample token", () => { const text = rendered({ id: "invoice-feature" }); expect(text).not.toMatch(/reference/iu); const ids = [ ...text.matchAll( /\b(?:schemaId|inputSchemaId|operationId|mapperId|outputContractId|policyId|diagnosticsOperation|definitionId|chunkId|routeId|moduleId|loadingSurface|contributionId|owner)\s*:\s*"([^"]+)"/gu, ), ...text.matchAll(/\bzodValidator\(\s*"([^"]+)"/gu), ...text.matchAll(/defineQueryNamespaceIdentity\(\s*"([^"]+)"/gu), ...text.matchAll(/kind: "([a-z][^"]*\.[^"]*)"/gu), ...text.matchAll(/^\s+"((?:route\.)?[A-Za-z_.]+)": "/gmu), ].map((match) => match[1] ?? ""); expect(ids.length).toBeGreaterThan(30); for (const id of ids) { expect(id).toMatch( /^(?:INVOICE_|Invoice|invoice[.-]|route\.INVOICE_LIST\.|route-invoice-|feature-frontend-invoice-feature$)/u, ); } expect(text).not.toMatch(/"NoRequest"/u); }); it("names the route, context and topic it creates", () => { const created = plan({ id: "invoice-feature" }); expect(created).toMatchObject({ contextId: "invoice-context", newContext: true, routeId: "INVOICE_LIST", routePath: "/invoice", topic: `qinv.${TOPIC_SUFFIX}`, placeholder: true, }); expect([...created.files.keys()]).toEqual( expect.arrayContaining([ "src/contexts/invoice-context/context-module.ts", "src/features/invoice-feature/feature-module.ts", "tests/features/invoice-feature/invoice-feature-input.test.ts", "tests/features/invoice-feature/invoice-list-page.test.tsx", "artifacts/tests/a11y-manual/INVOICE_LIST.md", ]), ); expect([...created.files.keys()].some((file) => file.includes("/domain/"))).toBe(false); expect(created.files.get("src/contexts/invoice-context/context-module.ts")).toContain( 'CONTEXT_ROUTE_PATH = "invoice/*"', ); expect(created.files.get("artifacts/tests/a11y-manual/INVOICE_LIST.md")).toMatch( /^Status: pending-manual-review$/mu, ); }); it("generates a fresh lower-case 26-character topic and refuses an installed one", () => { const first = randomTopicSuffix(); expect(first).toMatch(/^[0-9a-hjkmnp-tv-z]{26}$/u); expect(randomTopicSuffix()).not.toBe(first); expect(() => planFeature({ id: "invoice-feature" }, INSTALLED, () => "0000000000000000000000000a"), ).toThrow(/qinv\.0000000000000000000000000a is already installed/u); }); it("places the route after the last navigation entry", () => { expect(rendered({ id: "invoice-feature" })).toContain("navigationOrder: 60,"); }); it("adds the route under an existing context's root", () => { const created = plan({ id: "invoice-feature", context: "billing-context" }); expect(created).toMatchObject({ newContext: false, routePath: "/billing/invoice" }); expect([...created.files.keys()].some((file) => file.startsWith("src/contexts/"))).toBe(false); }); it("pins the placeholder through its exported constant, or the given package", () => { expect(rendered({ id: "invoice-feature" })).toContain( "digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,", ); const digest = `sha256:${"ab".repeat(32)}`; const pinned = plan({ id: "invoice-feature", contractPackage: { packageId: "@org-contracts/invoice", version: "1.4.2", digest, sourceRevision: "0a1b2c3d", }, }); const contract = pinned.files.get( "src/features/invoice-feature/contracts/invoice-feature-contract.ts", ); expect(pinned.placeholder).toBe(false); expect(contract).toContain(`digest: "${digest}",`); expect(contract).not.toContain("PLACEHOLDER"); expect(digest).not.toBe(PLACEHOLDER_CONTRACT_PACKAGE_DIGEST); }); }); describe("create:feature refusals", () => { it.each(["Invoice", "invoice_feature", "-invoice", "invoice--x", "invoice-", "", "a".repeat(41)])( "refuses the id %j", (id) => { expect(() => plan({ id })).toThrow(/kebab-case/u); }, ); it.each([ [{ id: "orders-feature" }, /already a feature or context/u], [{ id: "orders-context" }, /already a feature or context/u], [{ id: "orders" }, /prefix its ids with "orders", which orders-feature already uses/u], [{ id: "billing-feature" }, /pass --context billing-context/u], [{ id: "invoice-feature", context: "orders" }, /already owns the route root orders\/\*/u], [{ id: "invoice-feature", context: "drafts-feature" }, /is a feature id/u], [{ id: "home-feature" }, /message keys already exist: home\.list\.title/u], [ { id: "invoice-feature", contractPackage: { packageId: "@org-contracts/invoice", version: "1.4.2", digest: "sha256:abc", sourceRevision: "0a1b2c3d", }, }, /not a pinned identity: invoice-feature: package digest/u, ], ] as const)("refuses %j", (request, reason) => { expect(() => plan(request)).toThrow(reason); }); it("refuses a route that collides with an installed one", () => { expect(() => plan( { id: "invoice-feature" }, { ...INSTALLED, routes: [ ...INSTALLED.routes, { routeId: "LEGACY", path: "/invoice", chunkId: "route-legacy", navigationOrder: null }, ], }, ), ).toThrow(/collides with installed route LEGACY/u); }); }); describe("create:feature writing", () => { const roots: string[] = []; afterEach(async () => { await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); }); async function emptyRoot(): Promise { const root = await mkdtemp(path.join(tmpdir(), "create-feature-")); roots.push(root); return root; } it("refuses to overwrite and writes nothing when one target exists", async () => { const root = await emptyRoot(); const files = plan({ id: "invoice-feature" }).files; await mkdir(path.join(root, "artifacts/tests/a11y-manual"), { recursive: true }); await writeFile(path.join(root, "artifacts/tests/a11y-manual/INVOICE_LIST.md"), "kept\n"); await expect(writeFeatureFiles(root, files)).rejects.toThrow( /refusing to overwrite: artifacts\/tests\/a11y-manual\/INVOICE_LIST\.md/u, ); expect(await readdir(root)).toEqual(["artifacts"]); }); it("refuses an existing feature directory", async () => { const root = await emptyRoot(); await mkdir(path.join(root, "src/features/invoice-feature"), { recursive: true }); await expect( writeFeatureFiles(root, plan({ id: "invoice-feature" }).files, [ "src/features/invoice-feature", ]), ).rejects.toThrow(CreateFeatureError); }); it("removes what it wrote when a later write fails", async () => { const root = await emptyRoot(); const files = new Map([ ["src/features/broken/first.ts", "export {};\n"], // A file cannot be a directory, so this write fails after the first. ["src/features/broken/first.ts/second.ts", "export {};\n"], ]); await expect(writeFeatureFiles(root, files)).rejects.toThrow(); await expect(access(path.join(root, "src"))).rejects.toThrow(); }); });