diff --git a/scripts/generate-product-feature-index.ts b/scripts/generate-product-feature-index.ts index 7f96301d..3b7aaf2f 100644 --- a/scripts/generate-product-feature-index.ts +++ b/scripts/generate-product-feature-index.ts @@ -2,6 +2,8 @@ import { mkdir, readdir, readFile, writeFile } from "node:fs/promises"; import { dirname, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { selectCompiledProductFeatures } from "../src/contracts/product-features.ts"; + export type FeatureImportEntry = Readonly<{ id: string; importPath: string; @@ -14,8 +16,19 @@ export type FeatureIndexEntry = FeatureImportEntry & Readonly<{ contextMaxFeatures: number; }>; -export function renderFeatureIndex(entries: readonly FeatureImportEntry[]): string { +/** + * `declaredIds` is every feature the app declares, selected or not, so a build + * that left one out still reports it as `NOT_INSTALLED` without importing it. + */ +export function renderFeatureIndex( + entries: readonly FeatureImportEntry[], + declaredIds: readonly string[] = entries.map((entry) => entry.id), +): string { const sorted = [...entries].sort((left, right) => left.id.localeCompare(right.id)); + const declared = [...declaredIds] + .sort((left, right) => left.localeCompare(right)) + .map((id) => JSON.stringify(id)) + .join(", "); const imports = sorted .map( (entry, index) => @@ -24,7 +37,7 @@ export function renderFeatureIndex(entries: readonly FeatureImportEntry[]): stri .join("\n"); const modules = sorted.map((_, index) => ` featureModule${index},`).join("\n"); const featureImports = imports.length > 0 ? `${imports}\n` : ""; - return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nimport type { FeatureModule } from "../features/feature-module.ts";\n${featureImports}\nexport const PRODUCT_FEATURE_MODULES = Object.freeze([\n${modules}\n] as const);\n\ntype GeneratedProductFeatureModule = (typeof PRODUCT_FEATURE_MODULES)[number];\nexport type ProductFeatureModule =\n [GeneratedProductFeatureModule] extends [never]\n ? FeatureModule\n : GeneratedProductFeatureModule;\n`; + return `// Generated by scripts/generate-product-feature-index.ts. Do not edit by hand.\nimport type { FeatureModule } from "../features/feature-module.ts";\n${featureImports}\nexport const DECLARED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze([${declared}]);\n\nexport const PRODUCT_FEATURE_MODULES = Object.freeze([\n${modules}\n] as const);\n\ntype GeneratedProductFeatureModule = (typeof PRODUCT_FEATURE_MODULES)[number];\nexport type ProductFeatureModule =\n [GeneratedProductFeatureModule] extends [never]\n ? FeatureModule\n : GeneratedProductFeatureModule;\n`; } export function renderContextIndex(entries: readonly FeatureIndexEntry[]): string { @@ -164,10 +177,16 @@ export function resolveSelectedApp( return ids[0] as string; } -/** The production selection: one app -> its direct contexts -> their features. */ +/** + * The production selection: one app -> its direct contexts -> their features, + * narrowed by `VITE_PRODUCT_FEATURES` (09-02, D-9). The narrowing happens here + * so the bundle, the Node build scripts and the context router all import the + * same set, and a misspelt id fails the first build step. + */ export function selectAppIndexes( source: TopologyDeclarationSource, appId: string, + productFeatures?: string, ): SelectedAppIndexes { const app = source.app(appId); if (!app) throw new Error(`Unknown deployable app: ${appId}`); @@ -205,11 +224,15 @@ export function selectAppIndexes( if (new Set(ids).size !== ids.length) { throw new Error(`Duplicate generated feature ids: ${ids.join(", ")}`); } + const selected = selectCompiledProductFeatures( + entries.map((entry) => Object.freeze({ featureId: entry.id, entry })), + productFeatures, + ).map(({ entry }) => entry); return Object.freeze({ app, - entries: Object.freeze(entries), - featureIndex: renderFeatureIndex(entries), - contextIndex: renderContextIndex(entries), + entries: Object.freeze(selected), + featureIndex: renderFeatureIndex(selected, ids), + contextIndex: renderContextIndex(selected), appIndex: renderAppIndex(app), }); } @@ -321,9 +344,14 @@ export async function createFileSystemDeclarationSource( export async function generateAppIndexes( root: string, requestedApp: string | undefined, + productFeatures?: string, ): Promise { const source = await createFileSystemDeclarationSource(root); - return selectAppIndexes(source, resolveSelectedApp(source, requestedApp)); + return selectAppIndexes( + source, + resolveSelectedApp(source, requestedApp), + productFeatures, + ); } async function main(): Promise { @@ -344,7 +372,11 @@ async function main(): Promise { process.argv.find((argument) => argument.startsWith("--app="))?.slice("--app=".length) || process.env["PRODUCT_APP_ID"] || undefined; - const selected = await generateAppIndexes(root, requestedApp); + const selected = await generateAppIndexes( + root, + requestedApp, + process.env["VITE_PRODUCT_FEATURES"], + ); const rendered = { feature: selected.featureIndex, context: selected.contextIndex, diff --git a/src/contracts/env.ts b/src/contracts/env.ts index c5b20beb..916be599 100644 --- a/src/contracts/env.ts +++ b/src/contracts/env.ts @@ -57,8 +57,9 @@ export const ENV_REGISTRY = Object.freeze({ CAPABILITY_OVERRIDES: runtime("public", false, null), // §3.5: likewise for features — subtractive, keyed by installed feature id. FEATURE_OVERRIDES: runtime("public", false, null), - // §3.5: build-time narrowing of the product manifest. A feature left out - // here is not imported by any registry and never reaches the bundle. + // §3.5: build-time narrowing of the product manifest, applied by + // scripts/generate-product-feature-index.ts (09-02). A feature left out here + // is not imported by any registry and never reaches the bundle. VITE_PRODUCT_FEATURES: build("compile-time", false, null), }); diff --git a/src/contracts/product-features.ts b/src/contracts/product-features.ts index a6e5cd26..bb0d069b 100644 --- a/src/contracts/product-features.ts +++ b/src/contracts/product-features.ts @@ -5,12 +5,12 @@ * Two different questions, deliberately answered by two different inputs: * * - **Installed** is a build-time decision. `VITE_PRODUCT_FEATURES` selects - * from the features this source tree declares; a feature left out contributes - * no route, no operation, no schema, no codec and no adapter, so nothing can - * reach it. It does *not* shrink the bundle: a static import cannot be undone - * by a value, and building the import graph from a configuration string is - * exactly what §3.5 forbids. Physical removal is FE-GATE-020's job — delete - * the feature directory and rebuild, which that gate proves still works. + * from the features this source tree declares. The index generator + * (`scripts/generate-product-feature-index.ts`) applies it before anything is + * compiled (09-02, D-9), so a feature left out is not imported by the bundle, + * the Node build scripts or the context router, and a misspelt id fails the + * first build step. Deleting the feature directory is still the way to take + * its source out of the repository; FE-GATE-020 proves that works. * - **Active** is a runtime decision. `FEATURE_OVERRIDES` in the runtime config * may take an installed feature out of service without a rebuild. * diff --git a/src/features/installed-product-manifest.ts b/src/features/installed-product-manifest.ts index 22f79029..58e4c371 100644 --- a/src/features/installed-product-manifest.ts +++ b/src/features/installed-product-manifest.ts @@ -1,55 +1,26 @@ import { + DECLARED_PRODUCT_FEATURE_IDS, PRODUCT_FEATURE_MODULES, type ProductFeatureModule, } from "../.generated/product-feature-index.ts"; -import { - selectCompiledProductFeatures, - type SelectableProductFeature, -} from "../contracts/product-features.ts"; /** - * Product installation has one generated static source of truth. Feature-owned - * descriptors are discovered at build time; runtime configuration can only - * subtract from that compiled set. + * Product installation has one generated static source of truth. The + * generator discovers feature-owned descriptors and applies the build-time + * `VITE_PRODUCT_FEATURES` selection (09-02, D-9), so a feature left out is not + * imported by the bundle, the Node build scripts or the context router alike. + * Runtime configuration can only subtract from that installed set. */ -export const COMPILED_PRODUCT_FEATURE_MODULES: readonly ProductFeatureModule[] = + +/** Every feature the source tree declares, installed or not. */ +export const COMPILED_PRODUCT_FEATURE_IDS: readonly string[] = + DECLARED_PRODUCT_FEATURE_IDS; + +export const INSTALLED_PRODUCT_FEATURE_MODULES: readonly ProductFeatureModule[] = PRODUCT_FEATURE_MODULES; -export const COMPILED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze( - COMPILED_PRODUCT_FEATURE_MODULES.map((feature) => feature.id), -); - -function declaredFeatureSelection(): string | undefined { - const environment = ( - import.meta as unknown as { - env?: Readonly>; - } - ).env; - return environment?.["VITE_PRODUCT_FEATURES"]; -} - -type CompiledFeatureModule = ProductFeatureModule; -type CompiledFeatureContract = CompiledFeatureModule["contracts"]; -type SelectableFeatureModule = SelectableProductFeature & - Readonly<{ module: CompiledFeatureModule }>; - -const SELECTABLE_PRODUCT_FEATURE_MODULES: readonly SelectableFeatureModule[] = - Object.freeze( - COMPILED_PRODUCT_FEATURE_MODULES.map((module) => - Object.freeze({ featureId: module.id, module }), - ), - ); - -const INSTALLED_SELECTION = selectCompiledProductFeatures( - SELECTABLE_PRODUCT_FEATURE_MODULES, - declaredFeatureSelection(), -); - -export const INSTALLED_PRODUCT_FEATURE_MODULES: readonly CompiledFeatureModule[] = - Object.freeze(INSTALLED_SELECTION.map((entry) => entry.module)); - /** Backward-compatible projection consumed by the existing contract composer. */ -export const INSTALLED_PRODUCT_FEATURES: readonly CompiledFeatureContract[] = +export const INSTALLED_PRODUCT_FEATURES: readonly ProductFeatureModule["contracts"][] = Object.freeze( INSTALLED_PRODUCT_FEATURE_MODULES.map((module) => module.contracts), ); diff --git a/tests/component/context-route-gateway.test.tsx b/tests/component/context-route-gateway.test.tsx index 7d3a27a5..ffaaf233 100644 --- a/tests/component/context-route-gateway.test.tsx +++ b/tests/component/context-route-gateway.test.tsx @@ -14,6 +14,7 @@ import { createTestApplication } from "../helpers/create-test-application.ts"; * and the third one's routes module fails to download. */ vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], })); vi.mock("../../src/apps/template-app.ts", async () => { diff --git a/tests/component/route-status-surfaces.test.tsx b/tests/component/route-status-surfaces.test.tsx index 754c7515..2fda7e8b 100644 --- a/tests/component/route-status-surfaces.test.tsx +++ b/tests/component/route-status-surfaces.test.tsx @@ -18,6 +18,7 @@ import { createTestApplication } from "../helpers/create-test-application.ts"; // Feature-route surfaces run against a test-only feature, not the removable // sample (FE-GATE-020 runs the suite after deleting the sample). vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], })); vi.mock("../../src/.generated/product-context-index.ts", async () => ({ diff --git a/tests/component/router.test.tsx b/tests/component/router.test.tsx index cd6cbb71..294e527f 100644 --- a/tests/component/router.test.tsx +++ b/tests/component/router.test.tsx @@ -16,6 +16,7 @@ import { createProductFeaturesStub } from "../helpers/runtime-capabilities-stub. // Feature-route surfaces run against a test-only feature, not the removable // sample (FE-GATE-020 runs this file after deleting the sample). vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], })); vi.mock("../../src/.generated/product-context-index.ts", async () => ({ diff --git a/tests/helpers/fixture-feature.tsx b/tests/helpers/fixture-feature.tsx index 3f56a130..3dccdf1c 100644 --- a/tests/helpers/fixture-feature.tsx +++ b/tests/helpers/fixture-feature.tsx @@ -11,6 +11,7 @@ import { defineFeatureModule } from "../../src/features/feature-module.ts"; * indexes, so they do not depend on the removable sample feature (FE-GATE-020): * * vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + * DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], * PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], * })); * vi.mock("../../src/.generated/product-context-index.ts", async () => ({ diff --git a/tests/scripts/generate-product-feature-index.test.ts b/tests/scripts/generate-product-feature-index.test.ts index 60164d9b..181cb8a7 100644 --- a/tests/scripts/generate-product-feature-index.test.ts +++ b/tests/scripts/generate-product-feature-index.test.ts @@ -4,6 +4,8 @@ import { generateAppIndexes, renderContextIndex, renderFeatureIndex, + selectAppIndexes, + type TopologyDeclarationSource, } from "../../scripts/generate-product-feature-index.ts"; describe("feature index generator", () => { @@ -149,3 +151,66 @@ describe("app-scoped selection from ownership declarations", () => { expect(selected.appIndex).toContain('id: "a"'); }); }); + +describe("build-time product selection (09-02)", () => { + const source: TopologyDeclarationSource = Object.freeze({ + appIds: () => ["a"], + app: (appId: string) => + appId === "a" ? Object.freeze({ id: "a", maxContexts: 20 }) : undefined, + contextsOf: () => [ + Object.freeze({ id: "c", appId: "a", routePath: "c/*", maxFeatures: 200 }), + ], + featuresOf: () => [ + Object.freeze({ id: "f1", contextId: "c", directory: "f1" }), + Object.freeze({ id: "f2", contextId: "c", directory: "f2" }), + ], + }); + const declared = + 'DECLARED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze(["f1", "f2"])'; + + it("keeps every declared feature when nothing is selected", () => { + for (const selection of [undefined, "", " "]) { + const selected = selectAppIndexes(source, "a", selection); + expect(selected.entries.map((entry) => entry.id)).toEqual(["f1", "f2"]); + expect(selected.featureIndex).toBe(selectAppIndexes(source, "a").featureIndex); + expect(selected.featureIndex).toContain(declared); + } + }); + + it("imports only the selected features and still declares the rest", () => { + const selected = selectAppIndexes(source, "a", "f2"); + expect(selected.entries.map((entry) => entry.id)).toEqual(["f2"]); + expect(selected.featureIndex).not.toContain("features/f1/"); + expect(selected.contextIndex).not.toContain("features/f1/"); + expect(selected.contextIndex).toContain("features/f2/context-routes.ts"); + expect(selected.featureIndex).toContain(declared); + }); + + it("imports nothing for an explicit none", () => { + const selected = selectAppIndexes(source, "a", "none"); + expect(selected.entries).toEqual([]); + expect(selected.featureIndex).not.toMatch(/features\/f[12]\//u); + expect(selected.contextIndex).toBe(renderContextIndex([])); + expect(selected.featureIndex).toContain(declared); + }); + + it("fails generation on an id the app does not declare", () => { + expect(() => selectAppIndexes(source, "a", "f1,f3")).toThrow( + /VITE_PRODUCT_FEATURES names features this build does not contain: f3/u, + ); + }); + + it("fails the generator command, the first build step, on a misspelt id", async () => { + const { spawnSync } = await import("node:child_process"); + const run = spawnSync( + process.execPath, + ["scripts/generate-product-feature-index.ts", "--check"], + { + encoding: "utf8", + env: { ...process.env, VITE_PRODUCT_FEATURES: "reference-featrue" }, + }, + ); + expect(run.status).not.toBe(0); + expect(run.stderr).toMatch(/does not contain: reference-featrue/u); + }); +}); diff --git a/tests/unit/product-feature-selection-build.test.ts b/tests/unit/product-feature-selection-build.test.ts new file mode 100644 index 00000000..9eb4341f --- /dev/null +++ b/tests/unit/product-feature-selection-build.test.ts @@ -0,0 +1,99 @@ +import { spawnSync } from "node:child_process"; +import { cp, mkdir, mkdtemp, readFile, rm, symlink } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { filesBelow } from "../../scripts/lib/removal-fixture.ts"; +import { ROUTE_FEATURE_OWNER } from "../../src/features/installed-feature-contracts.ts"; +import { COMPILED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts"; + +/** + * 09-02 (D-9). `VITE_PRODUCT_FEATURES=none` has to leave every feature out of + * every consumer, not only the browser bundle: the generated context index + * (router), the installed contract contributions (Node contract-set + * generation) and the built assets. This runs the production generator and a + * Vite build over a copy of the build inputs. Written against whatever + * features the tree declares, so it holds after the sample's removal too. + */ +const BUILD_INPUTS = [ + "src", + "public", + "index.html", + "vite.config.ts", + "tsconfig.base.json", + "tsconfig.app.json", + "scripts/lib/vite-module-inventory.ts", +] as const; +// Feature ids stay: the generated index still declares them so the platform +// overview reports NOT_INSTALLED. Their modules and route ids go. +const FEATURE_ROUTE_IDS = Object.keys(ROUTE_FEATURE_OWNER); +const FEATURE_MODULE = /^src\/(?:features\/[^/]+|contexts\/[^/]+)\//u; + +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +describe("VITE_PRODUCT_FEATURES=none build (09-02)", () => { + it("leaves every feature out of the context index, the contract set and dist", async () => { + const root = await mkdtemp(path.join(tmpdir(), "product-selection-build-")); + roots.push(root); + for (const input of BUILD_INPUTS) { + await mkdir(path.dirname(path.join(root, input)), { recursive: true }); + await cp(path.resolve(input), path.join(root, input), { recursive: true }); + } + await symlink(path.resolve("node_modules"), path.join(root, "node_modules"), "dir"); + const env = { ...process.env, VITE_PRODUCT_FEATURES: "none" }; + + const generated = spawnSync( + process.execPath, + [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], + { encoding: "utf8", env }, + ); + expect(generated.stderr).toBe(""); + expect(generated.status).toBe(0); + const contextIndex = await readFile( + path.join(root, "src/.generated/product-context-index.ts"), + "utf8", + ); + expect(contextIndex).not.toContain("../features/"); + + const contributions = (await import( + pathToFileURL(path.join(root, "src/features/installed-contract-contributions.ts")).href + )) as typeof import("../../src/features/installed-contract-contributions.ts"); + expect(contributions.INSTALLED_CONTRACT_CONTRIBUTIONS).toEqual([]); + const manifest = (await import( + pathToFileURL(path.join(root, "src/features/installed-product-manifest.ts")).href + )) as typeof import("../../src/features/installed-product-manifest.ts"); + expect(manifest.INSTALLED_PRODUCT_FEATURE_IDS).toEqual([]); + // Still declared, so the platform overview reports them as NOT_INSTALLED. + expect(manifest.COMPILED_PRODUCT_FEATURE_IDS).toEqual(COMPILED_PRODUCT_FEATURE_IDS); + + const built = spawnSync( + path.resolve("node_modules/.bin/vite"), + ["build", "--logLevel", "error"], + { cwd: root, encoding: "utf8", env }, + ); + expect(built.stderr).toBe(""); + expect(built.status).toBe(0); + const residue: string[] = []; + for (const file of await filesBelow(path.join(root, "dist"))) { + if (!/\.(?:js|css|html)$/u.test(file)) continue; + const content = await readFile(file, "utf8"); + for (const routeId of FEATURE_ROUTE_IDS) { + if (content.includes(routeId)) residue.push(`${path.relative(root, file)}: ${routeId}`); + } + } + expect(residue).toEqual([]); + const inventory = JSON.parse( + await readFile(path.join(root, "dist/.vite/module-inventory.json"), "utf8"), + ) as { chunks: { modules: string[] }[] }; + const modules = inventory.chunks.flatMap((chunk) => chunk.modules); + expect(modules).toContain("src/features/installed-product-manifest.ts"); + expect(modules.filter((module) => FEATURE_MODULE.test(module))).toEqual([]); + }, 120_000); +});