diff --git a/tests/unit/product-extension-typecheck.test.ts b/tests/unit/product-extension-typecheck.test.ts index c12f3b0b..1d1319f9 100644 --- a/tests/unit/product-extension-typecheck.test.ts +++ b/tests/unit/product-extension-typecheck.test.ts @@ -1,6 +1,6 @@ import { spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; -import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { cp, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -23,72 +23,131 @@ import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture. * - a product runtime-config key with a `.default()`, which the template's * own tests must not have to spell out. * - * Only product-owned files and the feature's own directory are written. + * Only product-owned files, the product files kept next to them and the + * probe's own feature and context directories are written. * * The probe's names (`typecheck-probe-*`) are reserved for it: they are not - * the manual's example names, which a product may well use (1103 X2 #1). The - * capability type is appended to the product's own declaration, which a - * TypeScript interface merges, so a product that already declares - * capabilities keeps them. + * the manual's example names, which a product may well use (1103 X2 #1). + * + * 1105/09-01. The probe adds to the product's files and keeps everything they + * already declare and build. The capability type is appended to the + * product's own declaration, which a TypeScript interface merges. The + * product's `product-contracts.ts` and `product-composition.ts` move to + * `-product-*.ts` beside themselves; the probe's files re-export them + * and add only the probe's key, env row and capability on top. Writing those + * two files from scratch dropped the capabilities a product builds for its + * own features, so in such a product the app program failed with TS2741 in + * `src/bootstrap/runtime-adapters.ts`. */ +const PRODUCT_CAPABILITIES_FILE = "src/features/product-capabilities.ts"; +const PRODUCT_CONTRACTS_FILE = "src/contracts/product-contracts.ts"; +const PRODUCT_COMPOSITION_FILE = "src/bootstrap/product-composition.ts"; + +/** Every name one extension adds, derived from one reserved name. */ +function productExtension(name: string, camelName: string, constantName: string) { + return Object.freeze({ + featureId: `${name}-feature`, + contextId: `${name}-context`, + routePath: `${name}/*`, + messageKey: `${camelName}.title`, + capability: `${camelName}Settings`, + configKey: `${constantName}_PAGE_SIZE`, + keptContracts: `src/contracts/${name}-product-contracts.ts`, + keptComposition: `src/bootstrap/${name}-product-composition.ts`, + }); +} + +type ProductExtension = ReturnType; + +/** The probe itself. */ +const PROBE = productExtension("typecheck-probe", "typecheckProbe", "TYPECHECK_PROBE"); + +/** + * 1105/09-01. Stands in for a downstream's own capability and the feature that + * needs it. It is added the same way, so in a downstream it lands on top of + * the downstream's real product files too. + */ +const DOWNSTREAM = productExtension( + "typecheck-probe-downstream", + "typecheckProbeDownstream", + "TYPECHECK_PROBE_DOWNSTREAM", +); + /** Appended to the product's own `product-capabilities.ts`. */ -const PRODUCT_CAPABILITY_TYPES = ` +function capabilityType(extension: ProductExtension): string { + return ` export interface ProductFeaturePlatformCapabilities { - readonly typecheckProbeSettings: Readonly<{ pageSize(): number }>; + readonly ${extension.capability}: Readonly<{ pageSize(): number }>; } `; +} -const PRODUCT_CONTRACTS = `import { z } from "./zod.ts"; +/** Replaces `product-contracts.ts`; the product's own is kept beside it. */ +function productContracts(extension: ProductExtension): string { + const kept = `./${path.posix.basename(extension.keptContracts)}`; + return `import { + PRODUCT_ENV_REGISTRY as KEPT_PRODUCT_ENV_REGISTRY, + PRODUCT_RUNTIME_CONFIG_FIELDS as KEPT_PRODUCT_RUNTIME_CONFIG_FIELDS, +} from "${kept}"; +import { z } from "./zod.ts"; + +/** + * Product-owned. Filled by the 1103/09-02 typecheck fixture on top of the + * product's own file, kept as ${kept} (1105/09-01). + */ +export * from "${kept}"; -/** Product-owned. Filled by the 1103/09-02 typecheck fixture. */ export const PRODUCT_RUNTIME_CONFIG_FIELDS = Object.freeze({ - TYPECHECK_PROBE_PAGE_SIZE: z.int().min(1).max(100).default(20), + ...KEPT_PRODUCT_RUNTIME_CONFIG_FIELDS, + ${extension.configKey}: z.int().min(1).max(100).default(20), }); export const PRODUCT_ENV_REGISTRY = Object.freeze({ - TYPECHECK_PROBE_PAGE_SIZE: { + ...KEPT_PRODUCT_ENV_REGISTRY, + ${extension.configKey}: { phase: "runtime", classification: "public", required: false, defaultValue: "20", }, } as const); - -export const PRODUCT_REST_AUTH_PROFILES = Object.freeze({}); `; - -const PRODUCT_COMPOSITION = `import type { - ProductComposition, - ProductCompositionContext, - ProductSessionOwner, - ProductSessionOwnerContext, -} from "./product-composition-contract.ts"; - -/** Product-owned. Filled by the 1103/09-02 typecheck fixture. */ -export function composeProductSessionOwner( - context: ProductSessionOwnerContext, -): ProductSessionOwner { - return null; } +/** Replaces `product-composition.ts`; the product's own is kept beside it. */ +function productComposition(extension: ProductExtension): string { + const kept = `./${path.posix.basename(extension.keptComposition)}`; + return `import type { + ProductComposition, + ProductCompositionContext, +} from "./product-composition-contract.ts"; +import { composeProduct as composeKeptProduct } from "${kept}"; + +/** + * Product-owned. Filled by the 1103/09-02 typecheck fixture on top of the + * product's own file, kept as ${kept} (1105/09-01). + */ +export * from "${kept}"; + export function composeProduct(context: ProductCompositionContext) { - const pageSize = context.config.TYPECHECK_PROBE_PAGE_SIZE; + const product = composeKeptProduct(context); + const pageSize = context.config.${extension.configKey}; return { + ...product, capabilities: { - typecheckProbeSettings: Object.freeze({ pageSize: () => pageSize }), + ...product.capabilities, + ${extension.capability}: Object.freeze({ pageSize: () => pageSize }), }, - credentialProviders: {}, } satisfies ProductComposition; } `; +} -const FEATURE_ID = "typecheck-probe-feature"; -const CONTEXT_ID = "typecheck-probe-context"; +function featureModule(extension: ProductExtension): string { + return `import { defineFeatureModule } from "../feature-module.ts"; -const FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts"; - -export const FEATURE_MODULE_ID = "${FEATURE_ID}"; -export const FEATURE_CONTEXT_ID = "${CONTEXT_ID}"; +export const FEATURE_MODULE_ID = "${extension.featureId}"; +export const FEATURE_CONTEXT_ID = "${extension.contextId}"; export const FEATURE_MODULE = defineFeatureModule({ id: FEATURE_MODULE_ID, @@ -106,54 +165,59 @@ export const FEATURE_MODULE = defineFeatureModule({ }, routes: {}, // Both locales: with the sample features removed (test:sample-removal) - // this is the only catalog the message key types come from. + // the probe's catalogs are the only ones the message key types come from. messages: { - "ko-KR": { "typecheckProbe.title": "타입 검사 탐침" }, - "en-US": { "typecheckProbe.title": "Typecheck probe" }, + "ko-KR": { "${extension.messageKey}": "타입 검사 탐침" }, + "en-US": { "${extension.messageKey}": "Typecheck probe" }, }, loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME, } as const); `; +} -const FEATURE_RUNTIME = `import { defineFeatureAdapterContribution } from "../feature-adapter-contribution.ts"; +function featureRuntime(extension: ProductExtension): string { + return `import { defineFeatureAdapterContribution } from "../feature-adapter-contribution.ts"; import { defineFeatureRuntime } from "../feature-module.ts"; type TypecheckProbeInput = Readonly<{ pageSize(): number }>; declare module "../../application/ports/in/application-api.ts" { interface ApplicationFeatureInputs { - "${FEATURE_ID}": TypecheckProbeInput; + "${extension.featureId}": TypecheckProbeInput; } } export const FEATURE_RUNTIME = defineFeatureRuntime({ - featureId: "${FEATURE_ID}", + featureId: "${extension.featureId}", schemas: {}, adapters: [ defineFeatureAdapterContribution({ - featureId: "${FEATURE_ID}", - needs: ["typecheckProbeSettings"] as const, - createInput: ({ typecheckProbeSettings }) => + featureId: "${extension.featureId}", + needs: ["${extension.capability}"] as const, + createInput: ({ ${extension.capability} }) => Object.freeze({ - featureId: "${FEATURE_ID}", - input: Object.freeze({ pageSize: () => typecheckProbeSettings.pageSize() }), + featureId: "${extension.featureId}", + input: Object.freeze({ pageSize: () => ${extension.capability}.pageSize() }), }), }), ], contractContributions: [], } as const); `; +} const CONTEXT_ROUTES = `import type { RouteObject } from "react-router-dom"; export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze([]); `; -const CONTEXT_MODULE = `export const CONTEXT_MODULE_ID = "${CONTEXT_ID}"; +function contextModule(extension: ProductExtension): string { + return `export const CONTEXT_MODULE_ID = "${extension.contextId}"; export const CONTEXT_APP_ID = "template-app"; -export const CONTEXT_ROUTE_PATH = "typecheck-probe/*"; +export const CONTEXT_ROUTE_PATH = "${extension.routePath}"; export const CONTEXT_MAX_FEATURES = 1; `; +} const roots: string[] = []; @@ -161,53 +225,99 @@ afterAll(async () => { await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); }); -describe("1103/09-02 a product filled through its own files typechecks", () => { - it("passes the app, node and test programs", async () => { - const root = await mkdtemp(path.join(tmpdir(), "product-extension-typecheck-")); - roots.push(root); - // The repository's one copy-target list for a fixture copy. A removal - // drill runs this test in a copy that has already lost some of them - // (test:optional-recipe-removal deletes recipes/). - expect(existsSync(path.resolve("src/features", FEATURE_ID)), FEATURE_ID).toBe(false); - for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) { - if (!existsSync(path.resolve(entry))) continue; - await cp(path.resolve(entry), path.join(root, entry), { - recursive: true, - filter: (source) => !source.includes(`${path.sep}.generated`), - }); - } - await linkFixtureNodeModules(root); - const shipped = await readFile(path.resolve("src/features/product-capabilities.ts"), "utf8"); - const files: Readonly> = { - "src/features/product-capabilities.ts": `${shipped}${PRODUCT_CAPABILITY_TYPES}`, - "src/contracts/product-contracts.ts": PRODUCT_CONTRACTS, - "src/bootstrap/product-composition.ts": PRODUCT_COMPOSITION, - [`src/contexts/${CONTEXT_ID}/context-module.ts`]: CONTEXT_MODULE, - [`src/features/${FEATURE_ID}/feature-module.ts`]: FEATURE_MODULE, - [`src/features/${FEATURE_ID}/feature-runtime.ts`]: FEATURE_RUNTIME, - [`src/features/${FEATURE_ID}/context-routes.ts`]: CONTEXT_ROUTES, - }; - for (const [file, content] of Object.entries(files)) { - await mkdir(path.dirname(path.join(root, file)), { recursive: true }); - await writeFile(path.join(root, file), content); - } +async function copyRepository(): Promise { + const root = await mkdtemp(path.join(tmpdir(), "product-extension-typecheck-")); + roots.push(root); + // The repository's one copy-target list for a fixture copy. A removal + // drill runs this test in a copy that has already lost some of them + // (test:optional-recipe-removal deletes recipes/). + for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) { + if (!existsSync(path.resolve(entry))) continue; + await cp(path.resolve(entry), path.join(root, entry), { + recursive: true, + filter: (source) => !source.includes(`${path.sep}.generated`), + }); + } + await linkFixtureNodeModules(root); + return root; +} - const generated = spawnSync( - process.execPath, - [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], +async function writeFiles(root: string, files: Readonly>): Promise { + for (const [file, content] of Object.entries(files)) { + await mkdir(path.dirname(path.join(root, file)), { recursive: true }); + await writeFile(path.join(root, file), content); + } +} + +/** + * Adds one capability, its runtime-config key and a feature that needs it to + * the copy, keeping whatever the copy's product files already hold. + */ +async function addProductExtension(root: string, extension: ProductExtension): Promise { + // The extension's names are reserved for this file: a product that took one + // fails here, by name, instead of with a TS error in the copy. + for (const owned of [ + `src/features/${extension.featureId}`, + `src/contexts/${extension.contextId}`, + extension.keptContracts, + extension.keptComposition, + ]) { + expect(existsSync(path.join(root, owned)), owned).toBe(false); + } + await rename(path.join(root, PRODUCT_CONTRACTS_FILE), path.join(root, extension.keptContracts)); + await rename( + path.join(root, PRODUCT_COMPOSITION_FILE), + path.join(root, extension.keptComposition), + ); + const capabilities = await readFile(path.join(root, PRODUCT_CAPABILITIES_FILE), "utf8"); + await writeFiles(root, { + [PRODUCT_CAPABILITIES_FILE]: `${capabilities}${capabilityType(extension)}`, + [PRODUCT_CONTRACTS_FILE]: productContracts(extension), + [PRODUCT_COMPOSITION_FILE]: productComposition(extension), + [`src/contexts/${extension.contextId}/context-module.ts`]: contextModule(extension), + [`src/features/${extension.featureId}/feature-module.ts`]: featureModule(extension), + [`src/features/${extension.featureId}/feature-runtime.ts`]: featureRuntime(extension), + [`src/features/${extension.featureId}/context-routes.ts`]: CONTEXT_ROUTES, + }); +} + +/** Generates the copy's indexes and runs the three programs of `check:types`. */ +function expectTypecheckPasses(root: string): void { + const generated = spawnSync( + process.execPath, + [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], + { encoding: "utf8" }, + ); + expect(generated.stderr).toBe(""); + expect(generated.status).toBe(0); + + for (const project of ["tsconfig.app.json", "tsconfig.node.json", "tsconfig.test.json"]) { + const typecheck = spawnSync( + path.resolve("node_modules/.bin/tsc"), + ["--project", path.join(root, project)], { encoding: "utf8" }, ); - expect(generated.stderr).toBe(""); - expect(generated.status).toBe(0); + expect(typecheck.stdout + typecheck.stderr, project).toBe(""); + expect(typecheck.status, project).toBe(0); + } +} - for (const project of ["tsconfig.app.json", "tsconfig.node.json", "tsconfig.test.json"]) { - const typecheck = spawnSync( - path.resolve("node_modules/.bin/tsc"), - ["--project", path.join(root, project)], - { encoding: "utf8" }, - ); - expect(typecheck.stdout + typecheck.stderr, project).toBe(""); - expect(typecheck.status, project).toBe(0); - } +describe("1103/09-02 a product filled through its own files typechecks", () => { + it("passes the app, node and test programs", async () => { + const root = await copyRepository(); + await addProductExtension(root, PROBE); + expectTypecheckPasses(root); + }, 120_000); +}); + +describe("1105/09-01 the probe keeps what the product's own files build", () => { + // The copy first becomes a downstream whose own product-composition.ts + // builds a capability for its own feature, as memento and tech-log do + // (CHANGELOG.md, `composeProduct(context)`). The probe must not take it away. + it("passes when a product feature needs a product capability", async () => { + const root = await copyRepository(); + await addProductExtension(root, DOWNSTREAM); + await addProductExtension(root, PROBE); + expectTypecheckPasses(root); }, 120_000); });