diff --git a/.dependency-cruiser.json b/.dependency-cruiser.json index 7ab151ca..99561bb1 100644 --- a/.dependency-cruiser.json +++ b/.dependency-cruiser.json @@ -237,6 +237,18 @@ "path": "^src/features/installed-" } }, + { + "name": "boot-does-not-load-every-feature-runtime", + "comment": "15-01. src/features/loaded-feature-runtimes.ts awaits every installed feature's runtime half at module evaluation. Imported anywhere on the boot path, the first render would wait for all feature code, and the initial-chunk budget would not see it because the runtimes are dynamic imports. Any top-level await in the browser graph also turns off rolldown chunk optimizations for the whole build. At runtime the composition root loads one feature at a time when its routes are entered; the platform overview route calls loadInstalledFeatureRuntimeRegistries() instead. Node scripts and tests are outside src and may import it. Owner: frontend-platform.", + "severity": "error", + "from": { + "path": "^src/", + "pathNot": "^src/features/loaded-feature-runtimes\\.ts$" + }, + "to": { + "path": "^src/features/loaded-feature-runtimes\\.ts$" + } + }, { "name": "adapters-do-not-know-other-concrete-adapters", "comment": "docs/architecture/layers.md §4: a concrete adapter never depends on another concrete adapter. The adapter kernel is shared on purpose and any adapter may import it: src/adapters/platform/** (clock, abort primitive, capacity guard), src/adapters/browser-file-storage/result.ts (browser-data result helpers) and src/adapters/cross-context-invalidation/index.ts (the cross-context invalidation transport and its types). Owner: frontend-platform. No new file-level exception is added here; a new shared primitive goes into src/adapters/platform/.", diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index 11eaa591..47619f22 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -141,7 +141,7 @@ }, { "registryId": "FE-REG-API", - "path": "src/features/installed-feature-contracts.ts", + "path": "src/features/loaded-feature-runtimes.ts", "exportName": "API_OPERATIONS", "owner": "feature-frontend-api-client-response-envelope-contract", "keyField": "operationId", @@ -209,7 +209,7 @@ }, { "registryId": "FE-REG-SCHEMA", - "path": "src/features/installed-feature-contracts.ts", + "path": "src/features/loaded-feature-runtimes.ts", "exportName": "SCHEMA_REGISTRY", "owner": "feature-frontend-contract-schema-registry", "keyField": "schemaId", diff --git a/config/scale/feature-shape-ceilings.json b/config/scale/feature-shape-ceilings.json index 1731d967..8c2ed540 100644 --- a/config/scale/feature-shape-ceilings.json +++ b/config/scale/feature-shape-ceilings.json @@ -21,9 +21,9 @@ }, { "axis": "Initial JavaScript", - "verified": "Grows by about 2.9 KB gzip and one file per feature: every installed feature's contracts and module load at boot", - "condition": "Same", - "notVerified": "The initial budget (204,800 B, config/performance/budgets.json) is exceeded after a few more reference-shaped features, far below the context ceiling" + "verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes. Measured with scripts/scale/measure-feature-shape-growth.ts measureInitialJavascriptGzipBytes: 202,361 B with no copy, +741 B for the first copy, +648 B for the second, 205,629 B with five (before 15-01: +3,922 B per copy). tests/unit/feature-shape-growth.test.ts keeps one copy at or under 1 KiB", + "condition": "Same; the feature-declarations and feature-platform chunk groups in vite.config.ts", + "notVerified": "The initial budget (204,800 B, config/performance/budgets.json) still fits only about three more reference-shaped features: the platform itself is 98.8% of it. The committed baseline (feature-shape-growth.json) predates 15-01" }, { "axis": "Lazy JavaScript", diff --git a/docs/architecture/frontend-application-foundation.md b/docs/architecture/frontend-application-foundation.md index d820018e..60fc15c1 100644 --- a/docs/architecture/frontend-application-foundation.md +++ b/docs/architecture/frontend-application-foundation.md @@ -98,9 +98,18 @@ A feature owns its contract, runtime and adapter contributions. Central installed catalogs are aggregation points only: - `installed-product-manifest.ts`: which product features are compiled/selected -- `installed-feature-contracts.ts`: contract aggregation -- `installed-feature-runtimes.tsx`: runtime contribution aggregation -- `installed-feature-adapters.ts`: application-input contribution aggregation +- `installed-feature-contracts.ts`: boot-time contract aggregation (routes, + route runtime contracts, invalidation) from the feature declarations +- `installed-feature-adapters.ts`: application-input loaders, one per active + feature, run when the router enters the feature's routes (15-01) +- `installed-contract-contributions.ts`: declared contract packages and the + registry the HTTP executor resolves against, filled as features load +- `installed-feature-runtime-registries.ts`: loads every runtime half and + composes the V2 API registries and contract contributions; the platform + overview route calls it before it renders, the boot never does +- `loaded-feature-runtimes.ts`: the same registries as module constants (top- + level await) for Node scripts, tests and registry governance; nothing under + `src` may import it (`boot-does-not-load-every-feature-runtime`) Feature-specific composition belongs under the feature itself. Central catalogs must not grow feature-specific branching logic. diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md index 89515500..492db3b8 100644 --- a/docs/architecture/routing-pages-and-patterns.md +++ b/docs/architecture/routing-pages-and-patterns.md @@ -38,8 +38,9 @@ RP-04 이후 route runtime과 RP-06 page/form platform에는 다음 장점이 production composition에서 실행한다. platform route 계약, `src/features/installed-feature-contracts.ts`, -`src/features/installed-feature-runtimes.tsx`의 완전성은 TypeScript와 registry -negative fixture가 함께 검사한다. params/search codec, loading/error surface, +`src/presentation/routes/route-runtime.tsx`의 완전성은 TypeScript와 registry +negative fixture가 함께 검사한다. feature route의 codec은 그 route의 context +route handle(`codecs`)에 실려 route와 함께 적재된다(15-01). params/search codec, loading/error surface, access, title, navigation, chunk ID는 `src/presentation/routes/app-router.tsx`에서 모두 소비된다. built Vite manifest의 dynamic entry는 release manifest route chunk map과 검증되며, diff --git a/docs/architecture/starter-experience.md b/docs/architecture/starter-experience.md index d47dc836..787fa916 100644 --- a/docs/architecture/starter-experience.md +++ b/docs/architecture/starter-experience.md @@ -94,6 +94,7 @@ parent, as exported string or integer literals the generator reads: | `src/apps//app-module.ts` | `APP_MODULE_ID`, `APP_MAX_CONTEXTS` | | `src/contexts//context-module.ts` | `CONTEXT_MODULE_ID`, `CONTEXT_APP_ID`, `CONTEXT_ROUTE_PATH`, `CONTEXT_MAX_FEATURES` | | `src/features//feature-module.ts` | `FEATURE_MODULE_ID`, `FEATURE_CONTEXT_ID`, `FEATURE_MODULE` | +| `src/features//feature-runtime.ts` | `FEATURE_RUNTIME` (imported only by `feature-module.ts`, dynamically) | | `src/features//context-routes.ts` | `FEATURE_CONTEXT_ROUTES` | The generator writes `src/.generated/` (git-ignored): the feature index the @@ -112,25 +113,35 @@ selected app. Every build and check script runs it first; run it yourself with ### Adding a feature 1. Create `src/features//feature-module.ts`. Build `FEATURE_MODULE` - with `defineFeatureModule` (`src/features/feature-module.ts`): the feature's - contract (routes, route runtime contracts, API operations, invalidation, - schemas, runtime schemas, mappers), its adapter contributions - (`defineFeatureAdapterContribution`, with `needs` naming the platform - capabilities it receives), its runtime descriptor (route codecs), its message - catalogs and its contract contributions. + with `defineFeatureModule` (`src/features/feature-module.ts`). This is the + feature's declaration, and it is in the initial chunk, so it holds data + only: the declaration contract (routes, route runtime contracts, + invalidation, topic versions and the external `contractPackages` the + release manifest is checked against at boot), its message catalogs, and + `loadRuntime`, which imports `feature-runtime.ts` dynamically. `src/features/reference-feature/feature-module.ts` is the complete example. -2. Create `src/features//context-routes.ts` exporting - `FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here; the - owning context loads this file only when its route root is visited +2. Create `src/features//feature-runtime.ts` with + `defineFeatureRuntime`: the API contract (operations, schema metadata, + runtime schemas, mappers), the adapter contributions + (`defineFeatureAdapterContribution`, with `needs` naming the platform + capabilities it receives) and the contract contributions. The router loads + it (`application.features.load`) when one of the feature's routes is + entered. Do not import it statically from anywhere: each feature would add + its whole executable code to the initial chunk again, about 3.9 KB gzip + (`tests/unit/feature-shape-growth.test.ts` bounds one feature at 1 KiB). +3. Create `src/features//context-routes.ts` exporting + `FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here, and each + route handle carries the route's params/search `codecs`; the owning context + loads this file only when its route root is visited (`src/features/reference-feature/context-routes.ts`). -3. Name the owning context in `FEATURE_CONTEXT_ID`. Use an existing context or +4. Name the owning context in `FEATURE_CONTEXT_ID`. Use an existing context or add `src/contexts//context-module.ts` owned by the app. -4. If the feature has application input, augment `ApplicationFeatureInputs` +5. If the feature has application input, augment `ApplicationFeatureInputs` from the feature (`src/features/local-draft-feature/application/local-draft-api.ts`). -5. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`, +6. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`, `corepack pnpm check:registries` and the tests. `tests/unit/two-feature-install-typecheck.test.ts` keeps the installed catalogs compiling with more than one feature. -6. Run `corepack pnpm test:sample-removal -- --feature=` to prove +7. Run `corepack pnpm test:sample-removal -- --feature=` to prove the product still builds and passes its gates without the feature. Files outside the feature directory: diff --git a/scripts/scale/composition-workloads.ts b/scripts/scale/composition-workloads.ts index 5193205d..1f2cb9b3 100644 --- a/scripts/scale/composition-workloads.ts +++ b/scripts/scale/composition-workloads.ts @@ -72,10 +72,14 @@ export const COMPOSITION_WORKLOADS: readonly CompositionWorkload[] = Object.free id, contracts: Object.freeze({ featureId: id }), routes: Object.freeze({}), - adapters: Object.freeze([]), - runtimes: Object.freeze([]), messages: Object.freeze({}), - contractContributions: Object.freeze([]), + loadRuntime: async () => + Object.freeze({ + featureId: id, + apiContract: Object.freeze({}), + adapters: Object.freeze([]), + contractContributions: Object.freeze([]), + }), }), ); const contextCount = Math.ceil(n / CONTEXT_FEATURES); diff --git a/scripts/scale/measure-feature-shape-growth.ts b/scripts/scale/measure-feature-shape-growth.ts index 380c3688..98dc3ede 100644 --- a/scripts/scale/measure-feature-shape-growth.ts +++ b/scripts/scale/measure-feature-shape-growth.ts @@ -147,6 +147,24 @@ async function javascriptGzipBytes(root: string, files: readonly string[]) { return bytes; } +/** + * 15-01. Initial JavaScript gzip bytes of the app with `features` reference + * copies added: the generator and `vite build` only, no typecheck. The unit + * suite (merge stage) bounds what one more feature adds to the initial chunk + * with it, so the growth is caught on the PR instead of at the next release. + */ +export async function measureInitialJavascriptGzipBytes(features: number): Promise { + const root = await createFixture(features); + try { + run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root); + run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root); + const manifest = JSON.parse(await readFile(path.join(root, "dist/.vite/manifest.json"), "utf8")); + return await javascriptGzipBytes(root, classifyViteJavascript(manifest).initialFiles); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + async function measureOnce(root: string, features: number) { const loadBefore = load(); run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root); @@ -155,6 +173,11 @@ async function measureOnce(root: string, features: number) { const contracts = (await import( `${pathToFileURL(path.join(root, "src/features/installed-feature-contracts.ts")).href}?features=${features}` )) as typeof import("../../src/features/installed-feature-contracts.ts"); + // 15-01. Operations, schemas and contract contributions compose from the + // runtime halves, which only this module loads. + await import( + `${pathToFileURL(path.join(root, "src/features/loaded-feature-runtimes.ts")).href}?features=${features}` + ); const routes = Object.keys(contracts.ROUTE_REGISTRY).length; const tsc = run( path.resolve("node_modules/.bin/tsc"), diff --git a/src/application/create-application.ts b/src/application/create-application.ts index 5625e5de..9c912b15 100644 --- a/src/application/create-application.ts +++ b/src/application/create-application.ts @@ -12,6 +12,14 @@ import { decideChunkRecovery } from "./use-cases/decide-chunk-recovery.ts"; export type { ApplicationApi, ApplicationOutputPorts }; +/** + * 15-01. Creates the inputs of one feature once its runtime half has loaded. + * It may only return that feature's input. + */ +export type ApplicationFeatureLoader = () => Promise< + Readonly> +>; + /** * Builds the driving API consumed by inbound adapters. Concrete output ports * remain inside these closures and are never returned to React. @@ -19,6 +27,7 @@ export type { ApplicationApi, ApplicationOutputPorts }; export function createApplication( outputPorts: ApplicationOutputPorts, featureInputs: Readonly> = {}, + featureLoaders: Readonly> = {}, ): ApplicationApi { const session = Object.freeze({ getSnapshot: () => outputPorts.session.getState(), @@ -197,7 +206,11 @@ export function createApplication( } }, }); - const installedFeatureInputs = Object.freeze({ ...featureInputs }); + // 15-01. Grows as feature runtimes load; only `load` writes to it. + const installedFeatureInputs: Partial = { + ...featureInputs, + }; + const pendingLoads = new Map>(); const features = Object.freeze({ has(featureId: string): featureId is ApplicationFeatureId { return Object.hasOwn(installedFeatureInputs, featureId); @@ -206,12 +219,45 @@ export function createApplication( featureId: FeatureId, ): ApplicationFeatureInputs[FeatureId] { if (!Object.hasOwn(installedFeatureInputs, featureId)) { - throw new Error(`Application feature is not installed: ${featureId}`); + throw new Error( + Object.hasOwn(featureLoaders, featureId) + ? `Application feature is not loaded yet: ${featureId} (features.load runs before its routes render)` + : `Application feature is not installed: ${featureId}`, + ); } return installedFeatureInputs[ featureId ] as ApplicationFeatureInputs[FeatureId]; }, + load(featureId: string): Promise { + if ( + Object.hasOwn(installedFeatureInputs, featureId) || + !Object.hasOwn(featureLoaders, featureId) + ) { + return Promise.resolve(); + } + const pending = pendingLoads.get(featureId); + if (pending) return pending; + const loader = featureLoaders[featureId] as ApplicationFeatureLoader; + const load = loader().then( + (inputs) => { + const foreign = Object.keys(inputs).find((id) => id !== featureId); + if (foreign !== undefined) { + throw new TypeError( + `Feature ${featureId} installed an input for ${foreign}`, + ); + } + Object.assign(installedFeatureInputs, inputs); + }, + (error: unknown) => { + // A chunk that failed to download may succeed after recovery. + pendingLoads.delete(featureId); + throw error; + }, + ); + pendingLoads.set(featureId, load); + return load; + }, }); return Object.freeze({ diff --git a/src/application/ports/in/application-api.ts b/src/application/ports/in/application-api.ts index fbf7564c..8c1db28a 100644 --- a/src/application/ports/in/application-api.ts +++ b/src/application/ports/in/application-api.ts @@ -89,9 +89,20 @@ export type ApplicationApi = Readonly<{ >; }>; features: Readonly<{ + /** True once the feature's input is installed (see `load`). */ has(featureId: string): featureId is ApplicationFeatureId; + /** Throws for a feature whose input is not installed (yet). */ get( featureId: FeatureId, ): ApplicationFeatureInputs[FeatureId]; + /** + * 15-01. A feature's input is created from its runtime half, which is not + * in the initial chunk. The router calls this before it renders the + * feature's routes, so `get` works inside them. Resolves at once when the + * input is already installed or the composition has nothing to load for + * the feature (not installed, or switched off by `FEATURE_OVERRIDES`). + * Concurrent calls share one load; a failed load can be retried. + */ + load(featureId: string): Promise; }>; }>; diff --git a/src/bootstrap/composition-root.ts b/src/bootstrap/composition-root.ts index 63184367..10e4ab05 100644 --- a/src/bootstrap/composition-root.ts +++ b/src/bootstrap/composition-root.ts @@ -1,4 +1,7 @@ -import { createApplication } from "../application/create-application.ts"; +import { + createApplication, + type ApplicationFeatureLoader, +} from "../application/create-application.ts"; import type { ApplicationApi, ApplicationFeatureInputs, @@ -16,6 +19,8 @@ type AdapterBundle = Readonly<{ outputPorts: ApplicationOutputPorts; infrastructure: Infrastructure; featureInputs?: Readonly>; + /** 15-01. Inputs of features whose runtime half loads with their routes. */ + featureLoaders?: Readonly>; }>; type CompositionFactories = Readonly<{ @@ -40,6 +45,7 @@ export async function createCompositionRoot( const application = createApplication( adapters.outputPorts, adapters.featureInputs, + adapters.featureLoaders, ); return Object.freeze({ diff --git a/src/bootstrap/runtime-adapters.ts b/src/bootstrap/runtime-adapters.ts index 7603e0c6..d3aa1216 100644 --- a/src/bootstrap/runtime-adapters.ts +++ b/src/bootstrap/runtime-adapters.ts @@ -42,7 +42,7 @@ import { INSTALLED_REST_AUTH_PROFILES, } from "../contracts/rest-profiles.ts"; import type { ClockPort } from "../application/ports/clock-port.ts"; -import { createInstalledFeatureInputs } from "../features/installed-feature-adapters.ts"; +import { createInstalledFeatureLoaders } from "../features/installed-feature-adapters.ts"; import { INVALIDATION_REGISTRY, INVALIDATION_TOPIC_VERSIONS, @@ -64,7 +64,7 @@ import { } from "./load-release-manifest.ts"; import type { RuntimeConfigLoadResult } from "./load-runtime-config.ts"; import { createServerStateGenerationStore } from "./server-state-generation-store.ts"; -import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../features/installed-contract-contributions.ts"; +import { createInstalledContractRegistry } from "../features/installed-contract-contributions.ts"; import { indexInvalidationRegistry, indexInvalidationTopicVersions, @@ -541,12 +541,15 @@ export async function createRuntimeAdapters( }, observe: createHttpObservationProjector({ diagnostics, telemetry }), }); + // 15-01. Filled one feature at a time as feature runtimes load; an + // operation of a feature that has not loaded resolves to nothing and is + // refused below, exactly like an operation no feature contributes. + const contractRegistry = createInstalledContractRegistry(); const contractOperations: InstalledHttpOperationExecutor = Object.freeze({ async execute(operation, input, executionContext) { - const installed = - COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.get( - operation.contract.operationId, - ); + const installed = contractRegistry.resolveHttp( + operation.contract.operationId, + ); if (!installed) { return Object.freeze({ kind: "CONTRACT_VIOLATION" as const, @@ -603,9 +606,11 @@ export async function createRuntimeAdapters( http: contractOperations, telemetry: featureTelemetry, }); - const featureInputs = createInstalledFeatureInputs(featureCapabilities, [ - ...activeFeatureIds, - ]); + const featureLoaders = createInstalledFeatureLoaders( + featureCapabilities, + [...activeFeatureIds], + contractRegistry.install, + ); return Object.freeze({ outputPorts: Object.freeze({ @@ -642,6 +647,6 @@ export async function createRuntimeAdapters( serverStateGeneration.dispose(); }, }), - featureInputs, + featureLoaders, }); } diff --git a/src/features/feature-module.ts b/src/features/feature-module.ts index 4f944742..d72f4d27 100644 --- a/src/features/feature-module.ts +++ b/src/features/feature-module.ts @@ -2,25 +2,36 @@ export type FeatureContractIdentity = Readonly<{ featureId: string }>; type EmptyRecord = Readonly>; +/** + * 15-01. A feature has two halves. The declaration (`FeatureModule`) is what + * the shell needs before any of the feature's routes is entered: its route + * table, its messages, its cache invalidation identities and the external + * contract packages the release manifest is checked against at boot. It is + * imported statically and lands in the initial chunk, so it stays data. + * + * Everything executable (API contracts with their runtime schemas and mappers, + * the application input factory, the HTTP contract contributions) is the + * runtime half (`FeatureRuntime`). `loadRuntime` imports it dynamically when + * one of the feature's routes is entered. Before 15-01 both halves loaded at + * boot and each feature added about 3.9 KB gzip to the initial chunk. + */ + /** * Zero-feature products are a supported topology. The fallback contract keeps * every composer's property access valid without pretending that any feature - * route, operation, schema, mapper, or invalidation edge exists. + * route, invalidation edge or contract package exists. */ export type EmptyFeatureContract = FeatureContractIdentity & Readonly<{ routes: EmptyRecord; routeRuntimeContracts: EmptyRecord; - apiOperations: EmptyRecord; invalidation: Readonly<{ topics: readonly []; namespaces: readonly []; edges: readonly []; }>; topicVersions: readonly []; - schemas: EmptyRecord; - runtimeSchemas: EmptyRecord; - mappers: EmptyRecord; + contractPackages: readonly []; }>; export type FeatureMessageCatalogs = Readonly< @@ -31,12 +42,32 @@ type EmptyFeatureMessageCatalogs = Readonly< Record>> >; -type EmptyFeatureRuntimeDescriptor = Readonly<{ - featureId: string; - routeCodecs: EmptyRecord; - routeRuntime: EmptyRecord; +/** The V2 API contract: operations, schema metadata, runtime codecs, mappers. */ +export type EmptyFeatureApiContract = Readonly<{ + apiOperations: EmptyRecord; + schemas: EmptyRecord; + runtimeSchemas: EmptyRecord; + mappers: EmptyRecord; }>; +/** + * The executable half. `featureId` must equal the declaring module's id; the + * loader checks it, and checks that every adapter and contract contribution in + * it belongs to that feature. + */ +export type FeatureRuntime< + ApiContract = EmptyFeatureApiContract, + Adapter = never, + ContractContribution = never, +> = Readonly<{ + featureId: string; + apiContract: ApiContract; + adapters: readonly Adapter[]; + contractContributions: readonly ContractContribution[]; +}>; + +export type AnyFeatureRuntime = FeatureRuntime; + /** * The default parameters deliberately describe the empty-product fallback. * Concrete generated modules retain their literal types; only an empty @@ -45,28 +76,32 @@ type EmptyFeatureRuntimeDescriptor = Readonly<{ export type FeatureModule< Contract extends FeatureContractIdentity = EmptyFeatureContract, Routes extends Readonly> = EmptyRecord, - Adapter = never, - Runtime = EmptyFeatureRuntimeDescriptor, Messages extends FeatureMessageCatalogs = EmptyFeatureMessageCatalogs, - ContractContribution = never, + Runtime extends AnyFeatureRuntime = FeatureRuntime, > = Readonly<{ id: string; contracts: Contract; routes: Routes; - adapters: readonly Adapter[]; - runtimes: readonly Runtime[]; messages: Messages; - contractContributions: readonly ContractContribution[]; + /** + * Must dynamically import the feature's `feature-runtime.ts`: a static + * import here would put the runtime half back into the initial chunk + * (tests/unit/feature-shape-growth.test.ts measures it). + */ + loadRuntime(): Promise; }>; /** Structural supertype used when accepting any concrete feature descriptor. */ export type AnyFeatureModule = FeatureModule< FeatureContractIdentity, Readonly>, - unknown, - unknown, FeatureMessageCatalogs, - unknown + AnyFeatureRuntime +>; + +/** The runtime half a module's `loadRuntime` resolves to. */ +export type FeatureModuleRuntime = Awaited< + ReturnType >; export function defineFeatureModule( @@ -77,10 +112,32 @@ export function defineFeatureModule( `Feature module id ${module.id} does not match contract featureId ${module.contracts.featureId}`, ); } + return Object.freeze({ ...module }) as unknown as Readonly; +} + +export function defineFeatureRuntime( + runtime: Runtime, +): Readonly { return Object.freeze({ - ...module, - adapters: Object.freeze([...module.adapters]), - runtimes: Object.freeze([...module.runtimes]), - contractContributions: Object.freeze([...module.contractContributions]), - }) as unknown as Readonly; + ...runtime, + adapters: Object.freeze([...runtime.adapters]), + contractContributions: Object.freeze([...runtime.contractContributions]), + }) as unknown as Readonly; +} + +/** + * Loads a module's runtime half and refuses one that belongs to another + * feature. Composers call this instead of `module.loadRuntime()` directly. + */ +export async function loadFeatureRuntime( + module: Module, +): Promise> { + const runtime = (await module.loadRuntime()) as FeatureModuleRuntime; + const owner = (runtime as AnyFeatureRuntime).featureId; + if (owner !== module.id) { + throw new TypeError( + `Feature module ${module.id} loaded the runtime of ${String(owner)}`, + ); + } + return runtime; } diff --git a/src/features/installed-contract-contributions.ts b/src/features/installed-contract-contributions.ts index 029a5451..209aeb86 100644 --- a/src/features/installed-contract-contributions.ts +++ b/src/features/installed-contract-contributions.ts @@ -2,19 +2,117 @@ import { composeContractContributions, type InstalledContractContribution, type InstalledContractPackageIdentity, + type InstalledHttpContract, } from "../contracts/external-contract-runtime.ts"; -import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts"; +import { INSTALLED_PRODUCT_FEATURES } from "./installed-product-manifest.ts"; -export const INSTALLED_CONTRACT_CONTRIBUTIONS: readonly InstalledContractContribution[] = - Object.freeze( - INSTALLED_PRODUCT_FEATURE_MODULES.flatMap( - (module) => module.contractContributions, +/** + * 15-01. Contract contributions are executable (validators, effect + * classifiers) and load with each feature's runtime half. The release + * manifest is still checked at boot, before any feature loads, so the external + * packages a feature pins are declared up front in its declaration + * (`contracts.contractPackages`). A loaded contribution that pins a package no + * feature declared is refused (`createInstalledContractRegistry`), and + * `loaded-feature-runtimes.ts` checks the two sets are equal. + */ +function composeDeclaredPackages( + declarations: readonly (readonly InstalledContractPackageIdentity[])[], +): readonly InstalledContractPackageIdentity[] { + const byId = new Map(); + for (const identity of declarations.flat()) { + const existing = byId.get(identity.packageId); + if (existing && !samePackage(existing, identity)) { + throw new TypeError( + `contract package ${identity.packageId} is declared with conflicting identities`, + ); + } + byId.set(identity.packageId, Object.freeze({ ...identity })); + } + return Object.freeze([...byId.values()]); +} + +function samePackage( + left: InstalledContractPackageIdentity, + right: InstalledContractPackageIdentity, +): boolean { + return ( + left.packageId === right.packageId && + left.version === right.version && + left.digest === right.digest && + left.runtimeProtocolVersion === right.runtimeProtocolVersion && + left.sourceRevision === right.sourceRevision + ); +} + +export const EXPECTED_CONTRACT_SET_PACKAGES: readonly InstalledContractPackageIdentity[] = + composeDeclaredPackages( + INSTALLED_PRODUCT_FEATURES.map( + (contract) => + contract.contractPackages as readonly InstalledContractPackageIdentity[], ), ); -export const COMPOSED_CONTRACT_CONTRIBUTIONS = composeContractContributions( - INSTALLED_CONTRACT_CONTRIBUTIONS, -); +/** Throws unless every package the composed contributions pin was declared. */ +export function assertDeclaredContractPackages( + featureId: string, + pinned: readonly InstalledContractPackageIdentity[], + declared: readonly InstalledContractPackageIdentity[] = EXPECTED_CONTRACT_SET_PACKAGES, +): void { + for (const identity of pinned) { + if (!declared.some((entry) => samePackage(entry, identity))) { + throw new TypeError( + `${featureId} contributes contract package ${identity.packageId}, which no installed feature declares in contracts.contractPackages`, + ); + } + } +} -export const EXPECTED_CONTRACT_SET_PACKAGES: readonly InstalledContractPackageIdentity[] = - COMPOSED_CONTRACT_CONTRIBUTIONS.externalPackages; +export type InstalledContractRegistry = Readonly<{ + /** + * Adds one feature's contributions. The whole installed set is composed + * again, so a duplicate operation or contribution id across features is + * refused exactly as it was when every contribution composed at boot. + */ + install( + featureId: string, + contributions: readonly InstalledContractContribution[], + ): void; + resolveHttp( + operationId: string, + ): InstalledHttpContract | undefined; +}>; + +/** + * The composition root owns the only instance; the HTTP executor gets + * `resolveHttp`, the feature loader `install`. Nothing else can add a row + * (LIVE-03 kept the composed registry read-only for the same reason). + */ +export function createInstalledContractRegistry( + declaredPackages: readonly InstalledContractPackageIdentity[] = EXPECTED_CONTRACT_SET_PACKAGES, +): InstalledContractRegistry { + let installed: readonly InstalledContractContribution[] = Object.freeze([]); + let composed = composeContractContributions(installed); + return Object.freeze({ + install(featureId, contributions) { + for (const contribution of contributions) { + if (contribution.featureId !== featureId) { + throw new TypeError( + `feature ${featureId} loaded a contract contribution of ${contribution.featureId}`, + ); + } + } + const next = Object.freeze([...installed, ...contributions]); + const nextComposed = composeContractContributions(next); + assertDeclaredContractPackages( + featureId, + nextComposed.externalPackages, + declaredPackages, + ); + installed = next; + composed = nextComposed; + }, + resolveHttp(operationId) { + return composed.httpByOperationId.get(operationId); + }, + }); +} diff --git a/src/features/installed-feature-adapters.ts b/src/features/installed-feature-adapters.ts index 7d78588e..72fe9905 100644 --- a/src/features/installed-feature-adapters.ts +++ b/src/features/installed-feature-adapters.ts @@ -1,47 +1,86 @@ +import type { InstalledContractContribution } from "../contracts/external-contract-runtime.ts"; import { composeFeatureAdapterInputs, type ContributionsCapabilityContext, type InstalledFeatureInputs, } from "./feature-adapter-contribution.ts"; -import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts"; +import { + loadFeatureRuntime, + type FeatureModuleRuntime, +} from "./feature-module.ts"; +import { + INSTALLED_PRODUCT_FEATURE_MODULES, + type ProductFeatureModule, +} from "./installed-product-manifest.ts"; + +type InstalledFeatureRuntime = FeatureModuleRuntime; // 09-01. Indexed access distributes over the installed-module union, so this is // every installed contribution. `flatMap` alone infers its element type from // the first union member and rejected the second installed feature. type InstalledFeatureAdapterContribution = - (typeof INSTALLED_PRODUCT_FEATURE_MODULES)[number]["adapters"][number]; - -const INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS: readonly InstalledFeatureAdapterContribution[] = - Object.freeze( - INSTALLED_PRODUCT_FEATURE_MODULES.flatMap( - (module): readonly InstalledFeatureAdapterContribution[] => module.adapters, - ), - ); + InstalledFeatureRuntime["adapters"][number]; type InstalledFeatureCapabilityContext = ContributionsCapabilityContext< - typeof INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS + readonly InstalledFeatureAdapterContribution[] >; +/** One feature's input, created when its runtime half has loaded. */ +export type InstalledFeatureLoader = () => Promise; + /** - * Adapter installation is a projection of feature-owned descriptors. Adding a - * feature changes its descriptor and the generated index, not this composer + * 15-01. Adapter installation is a projection of feature-owned descriptors, as + * before, but each feature's descriptors now arrive with its runtime half. The + * composition root hands these loaders to the application; the router calls + * `application.features.load` before it renders the feature's routes. Adding a + * feature still changes only its descriptor and the generated index * (tests/unit/two-feature-install-typecheck.test.ts installs a second one). * - * Q-6.9-5. The runtime composer passes `activeFeatureIds` (installed minus - * `FEATURE_OVERRIDES`). A feature switched off there gets no input, so - * `application.features.get()` cannot hand out its API; the router was the - * only place that honoured the switch before. The default (every installed - * feature) is for callers that have no runtime configuration. + * Q-6.9-5. Only `activeFeatureIds` (installed minus `FEATURE_OVERRIDES`) get a + * loader. A feature switched off there has no input, so + * `application.features.get()` cannot hand out its API. The default (every + * installed feature) is for callers that have no runtime configuration. + * + * `installContracts` receives the runtime's contract contributions before its + * input is created, so the HTTP executor can resolve the feature's operations + * by the time the feature can call them. */ -export function createInstalledFeatureInputs( +export function createInstalledFeatureLoaders( context: InstalledFeatureCapabilityContext, activeFeatureIds: readonly string[] = INSTALLED_PRODUCT_FEATURE_MODULES.map( (module) => module.id, ), -): InstalledFeatureInputs { - return composeFeatureAdapterInputs( - INSTALLED_FEATURE_ADAPTER_CONTRIBUTIONS, - activeFeatureIds, - context, + installContracts: ( + featureId: string, + contributions: readonly InstalledContractContribution[], + ) => void = () => undefined, +): Readonly> { + const active = new Set(activeFeatureIds); + return Object.freeze( + Object.fromEntries( + INSTALLED_PRODUCT_FEATURE_MODULES.filter((module) => + active.has(module.id), + ).map((module) => [ + module.id, + async (): Promise => { + const runtime: InstalledFeatureRuntime = + await loadFeatureRuntime(module); + const adapters: readonly InstalledFeatureAdapterContribution[] = + runtime.adapters; + for (const adapter of adapters) { + if (adapter.featureId !== module.id) { + throw new TypeError( + `feature ${module.id} loaded an adapter contribution of ${adapter.featureId}`, + ); + } + } + installContracts( + module.id, + runtime.contractContributions as readonly InstalledContractContribution[], + ); + return composeFeatureAdapterInputs(adapters, [module.id], context); + }, + ]), + ), ); } diff --git a/src/features/installed-feature-contracts.ts b/src/features/installed-feature-contracts.ts index dd736089..e11f2106 100644 --- a/src/features/installed-feature-contracts.ts +++ b/src/features/installed-feature-contracts.ts @@ -1,19 +1,14 @@ -import { - composeApiOperations, - validateApiRuntimeBindings, -} from "../contracts/api-operations.ts"; -import { composeBoundaryMapperRegistry } from "../contracts/boundary-mapper.ts"; import { PLATFORM_ROUTE_RUNTIME_CONTRACT } from "../contracts/route-runtime-contract.ts"; -import { validateRestProfileBindings } from "../contracts/rest-profiles.ts"; import { PLATFORM_ROUTE_REGISTRY } from "../contracts/routes.ts"; -import { - composeRuntimeSchemaCodecs, - composeSchemaRegistry, - PLATFORM_SCHEMA_REGISTRY, -} from "../contracts/schema-registry.ts"; import { composeUniqueRecord } from "../platform/cardinality/compose-unique-record.ts"; import { INSTALLED_PRODUCT_FEATURES } from "./installed-product-manifest.ts"; +/** + * 15-01. Boot-time registries composed from the features' declarations: the + * route table, route runtime contracts, cache invalidation and navigation. + * The V2 API registries need the executable half of every feature and live in + * `loaded-feature-runtimes.ts`, which the app boot never imports. + */ export const INSTALLED_FEATURE_CONTRACTS = INSTALLED_PRODUCT_FEATURES; // 09-01. The registries keep composeUniqueRecord's own type, the intersection @@ -38,13 +33,6 @@ export const ROUTE_RUNTIME_CONTRACT = composeUniqueRecord( () => "route runtime contract", ); -export const API_OPERATIONS = composeApiOperations( - INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.apiOperations), -); -export const REST_PROFILE_BINDINGS_VALID = validateRestProfileBindings( - API_OPERATIONS, - Object.freeze({ PRIMARY_API: Object.freeze(["omit"] as const) }), -); // 09-01. Element types are spelled out for the same reason as in // installed-feature-adapters.ts: flatMap over the installed-contract union // otherwise returns the member arrays unflattened. @@ -78,22 +66,6 @@ export const INVALIDATION_TOPIC_VERSIONS = Object.freeze( (contract): readonly InstalledTopicVersion[] => contract.topicVersions, ), ); -export const SCHEMA_REGISTRY = composeSchemaRegistry([ - PLATFORM_SCHEMA_REGISTRY, - ...INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.schemas), -]); -export const RUNTIME_SCHEMA_CODECS = composeRuntimeSchemaCodecs( - INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.runtimeSchemas), -); -export const MAPPER_REGISTRY = composeBoundaryMapperRegistry( - INSTALLED_FEATURE_CONTRACTS.map((contract) => contract.mappers), -); -export const API_RUNTIME_BINDINGS_VALID = validateApiRuntimeBindings( - API_OPERATIONS, - SCHEMA_REGISTRY, - RUNTIME_SCHEMA_CODECS, - MAPPER_REGISTRY, -); export const ROUTE_FEATURE_OWNER: Readonly> = Object.freeze( diff --git a/src/features/installed-feature-runtime-registries.ts b/src/features/installed-feature-runtime-registries.ts new file mode 100644 index 00000000..1b86be28 --- /dev/null +++ b/src/features/installed-feature-runtime-registries.ts @@ -0,0 +1,110 @@ +import { + composeApiOperations, + validateApiRuntimeBindings, +} from "../contracts/api-operations.ts"; +import { composeBoundaryMapperRegistry } from "../contracts/boundary-mapper.ts"; +import { + composeContractContributions, + type InstalledContractContribution, +} from "../contracts/external-contract-runtime.ts"; +import { validateRestProfileBindings } from "../contracts/rest-profiles.ts"; +import { + composeRuntimeSchemaCodecs, + composeSchemaRegistry, + PLATFORM_SCHEMA_REGISTRY, +} from "../contracts/schema-registry.ts"; +import { loadFeatureRuntime } from "./feature-module.ts"; +import { + assertDeclaredContractPackages, + EXPECTED_CONTRACT_SET_PACKAGES, +} from "./installed-contract-contributions.ts"; +import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts"; + +/** + * 15-01. Loads every installed feature's runtime half and composes the + * registries that need all of them: the V2 API registries and the contract + * contributions. Duplicates across features throw here, as they did at boot + * before 15-01. + * + * The app boot never calls this: at runtime the composition root loads one + * feature at a time when its routes are entered (`installed-feature-adapters.ts`). + * The platform overview route calls it before it renders, and Node scripts and + * tests read the same result through `loaded-feature-runtimes.ts`. + */ +export async function loadInstalledFeatureRuntimeRegistries() { + const runtimes = Object.freeze( + await Promise.all(INSTALLED_PRODUCT_FEATURE_MODULES.map(loadFeatureRuntime)), + ); + type LoadedApiContract = (typeof runtimes)[number]["apiContract"]; + const apiContracts: readonly LoadedApiContract[] = runtimes.map( + (runtime) => runtime.apiContract, + ); + + const apiOperations = composeApiOperations( + apiContracts.map((contract) => contract.apiOperations), + ); + const restProfileBindingsValid = validateRestProfileBindings( + apiOperations, + Object.freeze({ PRIMARY_API: Object.freeze(["omit"] as const) }), + ); + const schemaRegistry = composeSchemaRegistry([ + PLATFORM_SCHEMA_REGISTRY, + ...apiContracts.map((contract) => contract.schemas), + ]); + const runtimeSchemaCodecs = composeRuntimeSchemaCodecs( + apiContracts.map((contract) => contract.runtimeSchemas), + ); + const mapperRegistry = composeBoundaryMapperRegistry( + apiContracts.map((contract) => contract.mappers), + ); + const apiRuntimeBindingsValid = validateApiRuntimeBindings( + apiOperations, + schemaRegistry, + runtimeSchemaCodecs, + mapperRegistry, + ); + + const contractContributions: readonly InstalledContractContribution[] = + Object.freeze( + runtimes.flatMap( + (runtime): readonly InstalledContractContribution[] => + runtime.contractContributions, + ), + ); + const composedContractContributions = composeContractContributions( + contractContributions, + ); + // The declared packages (checked against the release manifest at boot) and + // the packages the loaded contributions actually pin must be the same set. + assertDeclaredContractPackages( + "installed features", + composedContractContributions.externalPackages, + ); + for (const declared of EXPECTED_CONTRACT_SET_PACKAGES) { + if ( + !composedContractContributions.externalPackages.some( + (pinned) => pinned.packageId === declared.packageId, + ) + ) { + throw new TypeError( + `contract package ${declared.packageId} is declared, but no loaded contribution pins it`, + ); + } + } + + return Object.freeze({ + runtimes, + apiOperations, + restProfileBindingsValid, + schemaRegistry, + runtimeSchemaCodecs, + mapperRegistry, + apiRuntimeBindingsValid, + contractContributions, + composedContractContributions, + }); +} + +export type InstalledFeatureRuntimeRegistries = Awaited< + ReturnType +>; diff --git a/src/features/installed-feature-runtimes.tsx b/src/features/installed-feature-runtimes.tsx deleted file mode 100644 index f7f456a6..00000000 --- a/src/features/installed-feature-runtimes.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { composeUniqueRecord } from "../platform/cardinality/compose-unique-record.ts"; -import { PLATFORM_ROUTE_CODECS } from "../presentation/routes/platform-route-codecs.ts"; -import { PLATFORM_ROUTE_RUNTIME } from "../presentation/routes/route-runtime.tsx"; -import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.ts"; - -// 09-01. See installed-feature-adapters.ts: the element type is spelled out so -// a second installed feature widens it instead of failing inference. -type InstalledFeatureRuntimeContribution = - (typeof INSTALLED_PRODUCT_FEATURE_MODULES)[number]["runtimes"][number]; - -const INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS: readonly InstalledFeatureRuntimeContribution[] = - Object.freeze( - INSTALLED_PRODUCT_FEATURE_MODULES.flatMap( - (module): readonly InstalledFeatureRuntimeContribution[] => module.runtimes, - ), - ); - -export const ROUTE_CODECS = composeUniqueRecord( - [ - PLATFORM_ROUTE_CODECS, - ...INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS.map( - (contribution) => contribution.routeCodecs, - ), - ], - () => "route codec", -); - -export const ROUTE_RUNTIME = composeUniqueRecord( - [ - PLATFORM_ROUTE_RUNTIME, - ...INSTALLED_FEATURE_RUNTIME_CONTRIBUTIONS.map( - (contribution) => contribution.routeRuntime, - ), - ], - () => "route runtime", -); diff --git a/src/features/installed-product-manifest.ts b/src/features/installed-product-manifest.ts index 58e4c371..6a140235 100644 --- a/src/features/installed-product-manifest.ts +++ b/src/features/installed-product-manifest.ts @@ -31,3 +31,5 @@ export const INSTALLED_PRODUCT_FEATURE_IDS: readonly string[] = Object.freeze( export const INSTALLED_PRODUCT_FEATURE_ID_SET: ReadonlySet = new Set(INSTALLED_PRODUCT_FEATURE_IDS); + +export type { ProductFeatureModule }; diff --git a/src/features/loaded-feature-runtimes.ts b/src/features/loaded-feature-runtimes.ts new file mode 100644 index 00000000..d97ba99f --- /dev/null +++ b/src/features/loaded-feature-runtimes.ts @@ -0,0 +1,27 @@ +import { loadInstalledFeatureRuntimeRegistries } from "./installed-feature-runtime-registries.ts"; + +/** + * 15-01. The registries composed from every installed feature's runtime half, + * as module constants (top-level await), for Node scripts, tests and the + * registry governance (`config/contracts/registry-governance.json` reads + * `API_OPERATIONS` and `SCHEMA_REGISTRY` here). + * + * Nothing under `src` may import this module (architecture rule + * `boot-does-not-load-every-feature-runtime`). On the boot path it would make + * the first render wait for every feature's code, which the initial-chunk + * budget cannot see because the runtimes are dynamic imports; and any + * top-level await in the browser graph turns off rolldown's chunk + * optimizations for the whole build. + */ +const registries = await loadInstalledFeatureRuntimeRegistries(); + +export const LOADED_FEATURE_RUNTIMES = registries.runtimes; +export const API_OPERATIONS = registries.apiOperations; +export const REST_PROFILE_BINDINGS_VALID = registries.restProfileBindingsValid; +export const SCHEMA_REGISTRY = registries.schemaRegistry; +export const RUNTIME_SCHEMA_CODECS = registries.runtimeSchemaCodecs; +export const MAPPER_REGISTRY = registries.mapperRegistry; +export const API_RUNTIME_BINDINGS_VALID = registries.apiRuntimeBindingsValid; +export const INSTALLED_CONTRACT_CONTRIBUTIONS = registries.contractContributions; +export const COMPOSED_CONTRACT_CONTRIBUTIONS = + registries.composedContractContributions; diff --git a/src/features/reference-feature/README.md b/src/features/reference-feature/README.md index 8c07b364..c6afd373 100644 --- a/src/features/reference-feature/README.md +++ b/src/features/reference-feature/README.md @@ -13,7 +13,8 @@ reference implementation이다. adapter, 독립 form schema/command mapper와 list/detail/form/status page generic application은 비어 있는 `ApplicationFeatureInputs`와 typed -`features.has/get` registry만 소유한다. 이 feature의 application API가 module +`features.has/get/load` registry만 소유한다. input은 reference route에 처음 +들어갈 때 router가 `features.load`로 실행부를 적재한 뒤에 생긴다. 이 feature의 application API가 module augmentation으로 `"reference-feature": ReferenceFeatureInput`을 기여하므로 등록되지 않은 ID와 잘못된 input shape는 typecheck에서 거절된다. feature hook은 별도 cast나 runtime shape 확인 없이 정확한 input type을 받는다. 다만 동적 호출로 @@ -44,15 +45,20 @@ route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route t feature가 실제 contribution을 소유한다. -- contract: `reference-feature-contract.ts` -- route codec: `REFERENCE_FEATURE_RUNTIME_DESCRIPTOR` (`feature-module.ts`가 설치) -- page component: `REFERENCE_FEATURE_ROUTE_RUNTIME` (`context-routes.ts`가 lazy로 적재) -- bootstrap input: `REFERENCE_FEATURE_ADAPTER_CONTRIBUTION` +- 선언(초기 청크, `feature-module.ts`): route 표와 invalidation은 + `reference-feature-contract.ts`, 문구는 `reference-message-catalog.ts` +- 실행부(`feature-runtime.ts`, reference route에 들어갈 때 적재): API 계약 + `reference-api-contract.ts`, bootstrap input + `REFERENCE_FEATURE_ADAPTER_CONTRIBUTION`, HTTP contract contribution +- route codec과 page component: `REFERENCE_FEATURE_ROUTE_CODECS`, + `REFERENCE_FEATURE_ROUTE_RUNTIME` (`context-routes.ts`가 route handle에 실어 + lazy로 적재) -중앙 파일인 `installed-feature-contracts.ts`, -`installed-feature-runtimes.tsx`, `installed-feature-adapters.ts`는 선택된 -contribution을 합치는 역할만 한다. 새 기능의 내부 조립 규칙을 중앙 catalog에 -추가하지 않는다. +`feature-module.ts`는 `feature-runtime.ts`를 동적 import로만 가리킨다. 정적 +import로 바꾸면 실행부 전체가 다시 초기 청크에 들어간다(15-01). 중앙 파일인 +`installed-feature-contracts.ts`, `installed-feature-adapters.ts`, +`installed-contract-contributions.ts`는 선택된 contribution을 합치는 역할만 +한다. 새 기능의 내부 조립 규칙을 중앙 catalog에 추가하지 않는다. ## 검증과 제거 diff --git a/src/features/reference-feature/context-routes.ts b/src/features/reference-feature/context-routes.ts index d00f812b..a36d5220 100644 --- a/src/features/reference-feature/context-routes.ts +++ b/src/features/reference-feature/context-routes.ts @@ -1,7 +1,10 @@ import type { RouteObject } from "react-router-dom"; import { REFERENCE_FEATURE_CONTRACT } from "./contracts/reference-feature-contract.ts"; -import { REFERENCE_FEATURE_ROUTE_RUNTIME } from "./presentation/reference-feature-runtime.ts"; +import { + REFERENCE_FEATURE_ROUTE_CODECS, + REFERENCE_FEATURE_ROUTE_RUNTIME, +} from "./presentation/reference-feature-runtime.ts"; export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze( Object.values(REFERENCE_FEATURE_CONTRACT.routes).map((definition) => { @@ -14,6 +17,8 @@ export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze( handle: Object.freeze({ routeId: definition.routeId, runtime, + // 15-01. The route's params/search codecs load with its routes. + codecs: REFERENCE_FEATURE_ROUTE_CODECS, }), }); }), diff --git a/src/features/reference-feature/contracts/reference-api-contract.ts b/src/features/reference-feature/contracts/reference-api-contract.ts new file mode 100644 index 00000000..b22f6bc9 --- /dev/null +++ b/src/features/reference-feature/contracts/reference-api-contract.ts @@ -0,0 +1,155 @@ +import { defineRestOperation } from "../../../contracts/api-operations.ts"; +import { REFERENCE_RUNTIME_SCHEMA_CODECS } from "./reference-schemas.ts"; +import { REFERENCE_BOUNDARY_MAPPERS } from "./reference-mapper.ts"; + +/** + * 15-01. The V2 API contract of the reference feature: operations, schema + * metadata, runtime schema codecs and boundary mappers. Runtime half only + * (`feature-runtime.ts`); the app boot never imports it. + */ +export const REFERENCE_API_CONTRACT = Object.freeze({ + runtimeSchemas: REFERENCE_RUNTIME_SCHEMA_CODECS, + mappers: REFERENCE_BOUNDARY_MAPPERS, + schemas: Object.freeze({ + ReferenceResourceParams: Object.freeze({ + schemaId: "ReferenceResourceParams", + boundary: "route-params", + owner: "feature-frontend-reference-feature-vertical-slice", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + ReferenceResourceListQuery: Object.freeze({ + schemaId: "ReferenceResourceListQuery", + boundary: "route-search-api-request", + owner: "feature-frontend-reference-feature-vertical-slice", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + CreateReferenceResourceCommand: Object.freeze({ + schemaId: "CreateReferenceResourceCommand", + boundary: "api-request", + owner: "feature-frontend-reference-feature-vertical-slice", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + NoRequest: Object.freeze({ + schemaId: "NoRequest", + boundary: "api-request", + owner: "feature-frontend-reference-feature-vertical-slice", + runtime: "zod", + schemaVersion: 1, + direction: "REQUEST", + unknownFieldPolicy: "REJECT_UNKNOWN", + }), + ReferenceResourceListPayload: Object.freeze({ + schemaId: "ReferenceResourceListPayload", + boundary: "api-response", + owner: "feature-frontend-reference-feature-vertical-slice", + runtime: "zod", + schemaVersion: 1, + direction: "RESPONSE", + unknownFieldPolicy: "STRIP_UNKNOWN", + }), + ReferenceResourcePayload: Object.freeze({ + schemaId: "ReferenceResourcePayload", + boundary: "api-response", + owner: "feature-frontend-reference-feature-vertical-slice", + runtime: "zod", + schemaVersion: 1, + direction: "RESPONSE", + unknownFieldPolicy: "STRIP_UNKNOWN", + }), + }), + apiOperations: Object.freeze({ + LIST_REFERENCE_RESOURCES: defineRestOperation({ + method: "GET", + path: "/api/reference-resources", + operationId: "LIST_REFERENCE_RESOURCES", + auth: "external-session", + timeoutMs: null, + idempotency: "safe", + retry: "runtime", + requestSource: "search", + requestSchema: "ReferenceResourceListQuery", + responseSchema: "ReferenceResourceListPayload", + owner: "feature-frontend-reference-feature-vertical-slice", + contractVersion: 2, + protocol: "REST", + semantics: "QUERY", + replayPolicy: "SAFE", + idempotencyKeyPolicy: "NONE", + mapperId: "ReferenceResourceListMapper", + successStatuses: [200], + responseMediaTypes: ["application/json"], + maxResponseBytes: 262_144, + providerId: "PRIMARY_API", + authProfileId: "REFERENCE_EXTERNAL_BEARER", + csrfProfileId: "NO_CSRF_BEARER", + pathSchema: "NoRequest", + pathParameterNames: [], + maxEncodedSearchBytes: 4_096, + }), + CREATE_REFERENCE_RESOURCE: defineRestOperation({ + method: "POST", + path: "/api/reference-resources", + operationId: "CREATE_REFERENCE_RESOURCE", + auth: "external-session", + timeoutMs: null, + idempotency: "keyed", + retry: "runtime", + requestSource: "body", + requestSchema: "CreateReferenceResourceCommand", + responseSchema: "ReferenceResourcePayload", + owner: "feature-frontend-reference-feature-vertical-slice", + contractVersion: 2, + protocol: "REST", + semantics: "COMMAND", + replayPolicy: "KEYED_COMMAND", + idempotencyKeyPolicy: "REQUIRED", + mapperId: "ReferenceResourceMapper", + successStatuses: [200, 201], + responseMediaTypes: ["application/json"], + maxResponseBytes: 32_768, + providerId: "PRIMARY_API", + authProfileId: "REFERENCE_EXTERNAL_BEARER", + csrfProfileId: "NO_CSRF_BEARER", + pathSchema: "NoRequest", + pathParameterNames: [], + maxEncodedSearchBytes: 0, + }), + GET_REFERENCE_RESOURCE: defineRestOperation({ + method: "GET", + path: "/api/reference-resources/{resourceId}", + operationId: "GET_REFERENCE_RESOURCE", + auth: "external-session", + timeoutMs: null, + idempotency: "safe", + retry: "runtime", + requestSource: "none", + requestSchema: "NoRequest", + responseSchema: "ReferenceResourcePayload", + owner: "feature-frontend-reference-feature-vertical-slice", + contractVersion: 2, + protocol: "REST", + semantics: "QUERY", + replayPolicy: "SAFE", + idempotencyKeyPolicy: "NONE", + mapperId: "ReferenceResourceMapper", + successStatuses: [200], + responseMediaTypes: ["application/json"], + maxResponseBytes: 32_768, + providerId: "PRIMARY_API", + authProfileId: "REFERENCE_EXTERNAL_BEARER", + csrfProfileId: "NO_CSRF_BEARER", + pathSchema: "ReferenceResourceParams", + pathParameterNames: ["resourceId"], + maxEncodedSearchBytes: 0, + }), + }), +} as const); diff --git a/src/features/reference-feature/contracts/reference-feature-contract.ts b/src/features/reference-feature/contracts/reference-feature-contract.ts index fb06ea59..cfff3eb9 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract.ts @@ -1,8 +1,5 @@ import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts"; import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts"; -import { defineRestOperation } from "../../../contracts/api-operations.ts"; -import { REFERENCE_RUNTIME_SCHEMA_CODECS } from "./reference-schemas.ts"; -import { REFERENCE_BOUNDARY_MAPPERS } from "./reference-mapper.ts"; export const REFERENCE_FEATURE_ID = "reference-feature"; export const REFERENCE_RESOURCE_QUERY_NAMESPACE = defineQueryNamespaceIdentity( @@ -12,66 +9,14 @@ export const REFERENCE_RESOURCE_QUERY_NAMESPACE = defineQueryNamespaceIdentity( export const REFERENCE_RESOURCE_INVALIDATION_TOPIC = defineQueryInvalidationTopic("qinv.01k10f7m3w9p6r2c8v5n4x"); +/** + * 15-01. The declaration half: what the shell reads before a reference route + * is entered. It is in the initial chunk, so it holds data only. The API + * contract with its runtime schemas and mappers is + * `reference-api-contract.ts`, loaded with `feature-runtime.ts`. + */ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ featureId: REFERENCE_FEATURE_ID, - runtimeSchemas: REFERENCE_RUNTIME_SCHEMA_CODECS, - mappers: REFERENCE_BOUNDARY_MAPPERS, - schemas: Object.freeze({ - ReferenceResourceParams: Object.freeze({ - schemaId: "ReferenceResourceParams", - boundary: "route-params", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "REQUEST", - unknownFieldPolicy: "REJECT_UNKNOWN", - }), - ReferenceResourceListQuery: Object.freeze({ - schemaId: "ReferenceResourceListQuery", - boundary: "route-search-api-request", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "REQUEST", - unknownFieldPolicy: "REJECT_UNKNOWN", - }), - CreateReferenceResourceCommand: Object.freeze({ - schemaId: "CreateReferenceResourceCommand", - boundary: "api-request", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "REQUEST", - unknownFieldPolicy: "REJECT_UNKNOWN", - }), - NoRequest: Object.freeze({ - schemaId: "NoRequest", - boundary: "api-request", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "REQUEST", - unknownFieldPolicy: "REJECT_UNKNOWN", - }), - ReferenceResourceListPayload: Object.freeze({ - schemaId: "ReferenceResourceListPayload", - boundary: "api-response", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "RESPONSE", - unknownFieldPolicy: "STRIP_UNKNOWN", - }), - ReferenceResourcePayload: Object.freeze({ - schemaId: "ReferenceResourcePayload", - boundary: "api-response", - owner: "feature-frontend-reference-feature-vertical-slice", - runtime: "zod", - schemaVersion: 1, - direction: "RESPONSE", - unknownFieldPolicy: "STRIP_UNKNOWN", - }), - }), routes: Object.freeze({ REFERENCE_RESOURCE_LIST: Object.freeze({ routeId: "REFERENCE_RESOURCE_LIST", @@ -153,92 +98,6 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ searchCodec: "none", }), }), - apiOperations: Object.freeze({ - LIST_REFERENCE_RESOURCES: defineRestOperation({ - method: "GET", - path: "/api/reference-resources", - operationId: "LIST_REFERENCE_RESOURCES", - auth: "external-session", - timeoutMs: null, - idempotency: "safe", - retry: "runtime", - requestSource: "search", - requestSchema: "ReferenceResourceListQuery", - responseSchema: "ReferenceResourceListPayload", - owner: "feature-frontend-reference-feature-vertical-slice", - contractVersion: 2, - protocol: "REST", - semantics: "QUERY", - replayPolicy: "SAFE", - idempotencyKeyPolicy: "NONE", - mapperId: "ReferenceResourceListMapper", - successStatuses: [200], - responseMediaTypes: ["application/json"], - maxResponseBytes: 262_144, - providerId: "PRIMARY_API", - authProfileId: "REFERENCE_EXTERNAL_BEARER", - csrfProfileId: "NO_CSRF_BEARER", - pathSchema: "NoRequest", - pathParameterNames: [], - maxEncodedSearchBytes: 4_096, - }), - CREATE_REFERENCE_RESOURCE: defineRestOperation({ - method: "POST", - path: "/api/reference-resources", - operationId: "CREATE_REFERENCE_RESOURCE", - auth: "external-session", - timeoutMs: null, - idempotency: "keyed", - retry: "runtime", - requestSource: "body", - requestSchema: "CreateReferenceResourceCommand", - responseSchema: "ReferenceResourcePayload", - owner: "feature-frontend-reference-feature-vertical-slice", - contractVersion: 2, - protocol: "REST", - semantics: "COMMAND", - replayPolicy: "KEYED_COMMAND", - idempotencyKeyPolicy: "REQUIRED", - mapperId: "ReferenceResourceMapper", - successStatuses: [200, 201], - responseMediaTypes: ["application/json"], - maxResponseBytes: 32_768, - providerId: "PRIMARY_API", - authProfileId: "REFERENCE_EXTERNAL_BEARER", - csrfProfileId: "NO_CSRF_BEARER", - pathSchema: "NoRequest", - pathParameterNames: [], - maxEncodedSearchBytes: 0, - }), - GET_REFERENCE_RESOURCE: defineRestOperation({ - method: "GET", - path: "/api/reference-resources/{resourceId}", - operationId: "GET_REFERENCE_RESOURCE", - auth: "external-session", - timeoutMs: null, - idempotency: "safe", - retry: "runtime", - requestSource: "none", - requestSchema: "NoRequest", - responseSchema: "ReferenceResourcePayload", - owner: "feature-frontend-reference-feature-vertical-slice", - contractVersion: 2, - protocol: "REST", - semantics: "QUERY", - replayPolicy: "SAFE", - idempotencyKeyPolicy: "NONE", - mapperId: "ReferenceResourceMapper", - successStatuses: [200], - responseMediaTypes: ["application/json"], - maxResponseBytes: 32_768, - providerId: "PRIMARY_API", - authProfileId: "REFERENCE_EXTERNAL_BEARER", - csrfProfileId: "NO_CSRF_BEARER", - pathSchema: "ReferenceResourceParams", - pathParameterNames: ["resourceId"], - maxEncodedSearchBytes: 0, - }), - }), invalidation: Object.freeze({ topics: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]), namespaces: Object.freeze([REFERENCE_RESOURCE_QUERY_NAMESPACE]), @@ -255,4 +114,6 @@ export const REFERENCE_FEATURE_CONTRACT = Object.freeze({ topicVersion: 1, }), ]), + // TEMPLATE_FIXTURE contributions are not part of the contract set. + contractPackages: Object.freeze([]), } as const); diff --git a/src/features/reference-feature/feature-module.ts b/src/features/reference-feature/feature-module.ts index daebe2da..78e8e9e4 100644 --- a/src/features/reference-feature/feature-module.ts +++ b/src/features/reference-feature/feature-module.ts @@ -1,26 +1,26 @@ import { defineFeatureModule } from "../feature-module.ts"; -import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-reference-feature-input.ts"; import { REFERENCE_FEATURE_CONTRACT, REFERENCE_FEATURE_ID, } from "./contracts/reference-feature-contract.ts"; -import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./contracts/reference-feature-contract-contribution.ts"; import { REFERENCE_MESSAGE_CATALOGS } from "./contracts/reference-message-catalog.ts"; -import { REFERENCE_FEATURE_RUNTIME_DESCRIPTOR } from "./presentation/reference-feature-runtime-descriptor.ts"; export const FEATURE_MODULE_ID = "reference-feature" satisfies typeof REFERENCE_FEATURE_ID; /** Owning bounded context (route root and budget live in its declaration). */ export const FEATURE_CONTEXT_ID = "reference-context"; +/** + * 15-01. Declaration only: this file and what it imports statically are in the + * initial chunk. The executable half is `feature-runtime.ts`, imported here + * dynamically and loaded when a reference route is entered. + */ export const REFERENCE_FEATURE_MODULE = defineFeatureModule({ id: FEATURE_MODULE_ID, contracts: REFERENCE_FEATURE_CONTRACT, routes: REFERENCE_FEATURE_CONTRACT.routes, - adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION], - runtimes: [REFERENCE_FEATURE_RUNTIME_DESCRIPTOR], messages: REFERENCE_MESSAGE_CATALOGS, - contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION], + loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME, } as const); export const FEATURE_MODULE = REFERENCE_FEATURE_MODULE; diff --git a/src/features/reference-feature/feature-runtime.ts b/src/features/reference-feature/feature-runtime.ts new file mode 100644 index 00000000..f36b0a04 --- /dev/null +++ b/src/features/reference-feature/feature-runtime.ts @@ -0,0 +1,18 @@ +import { defineFeatureRuntime } from "../feature-module.ts"; +import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-reference-feature-input.ts"; +import { REFERENCE_API_CONTRACT } from "./contracts/reference-api-contract.ts"; +import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./contracts/reference-feature-contract-contribution.ts"; +import { REFERENCE_FEATURE_ID } from "./contracts/reference-feature-contract.ts"; + +/** + * 15-01. The executable half of the reference feature. `feature-module.ts` + * imports this file dynamically; the router loads it when a reference route + * is entered (`application.features.load`), so none of it is in the initial + * chunk. + */ +export const FEATURE_RUNTIME = defineFeatureRuntime({ + featureId: REFERENCE_FEATURE_ID, + apiContract: REFERENCE_API_CONTRACT, + adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION], + contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION], +} as const); diff --git a/src/features/reference-feature/presentation/reference-feature-runtime-descriptor.ts b/src/features/reference-feature/presentation/reference-feature-runtime-descriptor.ts deleted file mode 100644 index ea240867..00000000 --- a/src/features/reference-feature/presentation/reference-feature-runtime-descriptor.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts"; -import { - referenceResourceListQuerySchema, - referenceResourceParamsSchema, -} from "../contracts/reference-schemas.ts"; - -export const REFERENCE_FEATURE_ROUTE_CODECS = { - ReferenceResourceListQuery: referenceResourceListQuerySchema, - ReferenceResourceParams: referenceResourceParamsSchema, -} as const; - -/** - * Boot-safe feature runtime metadata. Page components are deliberately absent: - * executable route chunks are owned and loaded by the bounded context route - * module, so Node-side composition and app boot do not pull the page graph in. - */ -export const REFERENCE_FEATURE_RUNTIME_DESCRIPTOR = Object.freeze({ - featureId: REFERENCE_FEATURE_ID, - routeCodecs: REFERENCE_FEATURE_ROUTE_CODECS, - routeRuntime: Object.freeze({}), -}); diff --git a/src/features/reference-feature/presentation/reference-feature-runtime.ts b/src/features/reference-feature/presentation/reference-feature-runtime.ts index 86ed6e35..8d33baeb 100644 --- a/src/features/reference-feature/presentation/reference-feature-runtime.ts +++ b/src/features/reference-feature/presentation/reference-feature-runtime.ts @@ -1,9 +1,21 @@ import { lazy } from "react"; import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts"; -import { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-feature-runtime-descriptor.ts"; +import { + referenceResourceListQuerySchema, + referenceResourceParamsSchema, +} from "../contracts/reference-schemas.ts"; -export { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-feature-runtime-descriptor.ts"; +/** + * 15-01. Route codecs travel with the context routes (`context-routes.ts` puts + * them on each route handle), not with the boot-time feature module: zod + * schemas are executable and the shell needs none of them before a reference + * route is entered. + */ +export const REFERENCE_FEATURE_ROUTE_CODECS = { + ReferenceResourceListQuery: referenceResourceListQuerySchema, + ReferenceResourceParams: referenceResourceParamsSchema, +} as const; export const REFERENCE_FEATURE_ROUTE_RUNTIME = { REFERENCE_RESOURCE_LIST: Object.freeze({ diff --git a/src/presentation/examples/platform-overview-page.tsx b/src/presentation/examples/platform-overview-page.tsx index ce57c13f..e959073c 100644 --- a/src/presentation/examples/platform-overview-page.tsx +++ b/src/presentation/examples/platform-overview-page.tsx @@ -1,12 +1,13 @@ -import { useEffect, useState } from "react"; +import { type ComponentType, useEffect, useState } from "react"; -import { HTTP_EXECUTION_CEILINGS } from "../../contracts/external-contract-runtime.ts"; -import { SERVER_STATE_PROFILES } from "../../contracts/server-state.ts"; import { - COMPOSED_CONTRACT_CONTRIBUTIONS, - EXPECTED_CONTRACT_SET_PACKAGES, -} from "../../features/installed-contract-contributions.ts"; + HTTP_EXECUTION_CEILINGS, + type ComposedContractContributions, +} from "../../contracts/external-contract-runtime.ts"; +import { SERVER_STATE_PROFILES } from "../../contracts/server-state.ts"; +import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../features/installed-contract-contributions.ts"; import { ROUTE_REGISTRY } from "../../features/installed-feature-contracts.ts"; +import { loadInstalledFeatureRuntimeRegistries } from "../../features/installed-feature-runtime-registries.ts"; import type { RuntimeCapabilityId, RuntimeCapabilityStatus, @@ -250,9 +251,11 @@ const FEATURE_BADGE = Object.freeze({ }), }); -function buildOperationRows(): readonly OperationRow[] { +function buildOperationRows( + contracts: ComposedContractContributions, +): readonly OperationRow[] { return Object.freeze( - [...COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.values()].map( + [...contracts.httpByOperationId.values()].map( (installed) => { const { contract, frontend } = installed; return Object.freeze({ @@ -278,7 +281,14 @@ function buildOperationRows(): readonly OperationRow[] { ); } -export default function PlatformOverviewPage() { +/** + * 15-01. The page lists every installed HTTP operation, which lives in the + * features' runtime halves. Its route loads them all before it renders + * (`loadPlatformOverviewPage`); the boot never does. + */ +export function PlatformOverviewPage({ + contracts, +}: Readonly<{ contracts: ComposedContractContributions }>) { const runtime = useApplicationRuntime(); const [release, setRelease] = useState< Awaited> | "failed" | null @@ -300,14 +310,14 @@ export default function PlatformOverviewPage() { }, [runtime]); const routes = Object.values(ROUTE_REGISTRY); - const operations = buildOperationRows(); + const operations = buildOperationRows(contracts); const capabilities = runtime.getCapabilitySnapshot(); const features = runtime.getFeatureSnapshot(); const activeCapabilityCount = capabilities.filter( (status) => status.active > 0, ).length; const fixtureContributions = - COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.filter( + contracts.contributions.filter( (contribution) => contribution.source.kind === "TEMPLATE_FIXTURE", ).length; @@ -544,3 +554,16 @@ export default function PlatformOverviewPage() { ); } + +/** The route module: the page bound to the registries it reads. */ +export async function loadPlatformOverviewPage(): Promise< + Readonly<{ default: ComponentType }> +> { + const registries = await loadInstalledFeatureRuntimeRegistries(); + const contracts = registries.composedContractContributions; + return Object.freeze({ + default: function InstalledPlatformOverviewPage() { + return ; + }, + }); +} diff --git a/src/presentation/providers/application-provider.tsx b/src/presentation/providers/application-provider.tsx index 9a74ca00..17388d7c 100644 --- a/src/presentation/providers/application-provider.tsx +++ b/src/presentation/providers/application-provider.tsx @@ -54,6 +54,11 @@ export function useApplicationRecovery(): ApplicationApi["recovery"] { return useApplicationContext().recovery; } +/** 15-01. The router loads a feature's runtime half before its routes. */ +export function useApplicationFeatures(): ApplicationApi["features"] { + return useApplicationContext().features; +} + export function useApplicationFeature< FeatureId extends ApplicationFeatureId, >(featureId: FeatureId): ApplicationFeatureInputs[FeatureId] { diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index 9b3236f7..26e51ba5 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -48,6 +48,7 @@ import { useLocale } from "../i18n/index.ts"; import { AppShell } from "../layouts/app-shell.tsx"; import { useApplicationDiagnostics, + useApplicationFeatures, useApplicationRecovery, useApplicationRuntime, } from "../providers/application-provider.tsx"; @@ -63,9 +64,10 @@ import { import { buildRouteUrl, parseRouteInput, + type FeatureRouteCodecs, type RouteId, } from "./route-codecs.ts"; -import { ROUTE_RUNTIME } from "../../features/installed-feature-runtimes.tsx"; +import { PLATFORM_ROUTE_RUNTIME } from "./route-runtime.tsx"; import type { ParsedRouteInput } from "./route-contract.ts"; import { RouteInputProvider } from "./route-input.tsx"; @@ -201,8 +203,10 @@ function RouteLifecycle({ function CanonicalRouteRedirect({ input, + codecs, }: { input: ParsedRouteInput; + codecs: FeatureRouteCodecs; }) { const location = useLocation(); const navigate = useNavigate(); @@ -210,10 +214,11 @@ function CanonicalRouteRedirect({ useEffect(() => { if (input.routeId === "NOT_FOUND") return; const source = `${location.pathname}${location.search}`; - const canonical = buildRouteUrl(input.routeId, { - params: input.params, - search: input.search, - }); + const canonical = buildRouteUrl( + input.routeId, + { params: input.params, search: input.search }, + codecs, + ); // D-16: a route that ignores its query leaves the query in the URL. const target = ROUTE_RUNTIME_CONTRACT[input.routeId].searchCodec === "none" @@ -224,7 +229,7 @@ function CanonicalRouteRedirect({ } else if (guard.current.allow(source, target)) { void navigate(target, { replace: true }); } - }, [input, location.pathname, location.search, navigate]); + }, [codecs, input, location.pathname, location.search, navigate]); return null; } @@ -298,6 +303,8 @@ type RegisteredRouteProps = { routeId: RouteId; buildId: string; runtimeOverride?: ExecutableRouteRuntime; + /** 15-01. A feature route's codecs, from its context route handle. */ + codecsOverride?: FeatureRouteCodecs; paramsOverride?: Readonly>; }; @@ -317,10 +324,13 @@ function RegisteredRoute(props: RegisteredRouteProps) { ); } +const NO_FEATURE_CODECS: FeatureRouteCodecs = Object.freeze({}); + function RouteSurface({ routeId, buildId, runtimeOverride, + codecsOverride = NO_FEATURE_CODECS, paramsOverride, }: RegisteredRouteProps) { const definition = getRoute(routeId); @@ -341,17 +351,17 @@ function RouteSurface({ // Feature executable runtimes are loaded by their bounded context. Platform // routes still use the boot-safe global runtime table. const platformRuntimes: Readonly> = - ROUTE_RUNTIME; + PLATFORM_ROUTE_RUNTIME; const runtime = runtimeOverride ?? platformRuntimes[routeId]; if (!runtime) return ; - const parsed = parseRouteInput(routeId, params, search); + const parsed = parseRouteInput(routeId, params, search, codecsOverride); if (!parsed.success) return ; const boundaryName = definition.errorSurface === "feature-boundary" ? "feature" : "route"; const content = ( - + }> {/* React Router reuses this instance across sibling routes; the key keeps one route's failed chunk from latching onto the next. */} @@ -403,6 +413,7 @@ function RouteSurface({ type ContextRouteHandle = Readonly<{ routeId: RouteId; runtime: ExecutableRouteRuntime; + codecs?: FeatureRouteCodecs; }>; function isContextRouteHandle(value: unknown): value is ContextRouteHandle { @@ -414,17 +425,39 @@ function isContextRouteHandle(value: unknown): value is ContextRouteHandle { !!runtime && typeof runtime === "object" && typeof (runtime as Readonly>)["moduleId"] === "string" && - "Component" in runtime + "Component" in runtime && + (handle["codecs"] === undefined || + (!!handle["codecs"] && typeof handle["codecs"] === "object")) ); } -/** The registered route a URL names, to key chunk recovery on its chunk. */ -function routeChunkId(pathname: string): string | undefined { +/** + * 15-01. The features that own a context's routes. Their runtime halves load + * together with the routes, so `application.features.get` works in every page + * the context renders. + */ +function routeOwners(routes: readonly RouteObject[]): readonly string[] { + const owners = new Set(); + for (const route of routes) { + if (!isContextRouteHandle(route.handle)) continue; + const owner = ROUTE_FEATURE_OWNER[route.handle.routeId]; + if (owner !== undefined) owners.add(owner); + } + return [...owners]; +} + +/** The registered route a URL names. */ +function registeredRouteIdAt(pathname: string): string | undefined { const routes = Object.values(ROUTE_REGISTRY).map((definition) => ({ id: definition.routeId, path: definition.path, })); - const routeId = matchRoutes(routes, pathname)?.at(-1)?.route.id; + return matchRoutes(routes, pathname)?.at(-1)?.route.id; +} + +/** The chunk that route recovers, to key chunk recovery on it. */ +function routeChunkId(pathname: string): string | undefined { + const routeId = registeredRouteIdAt(pathname); return routeId === undefined ? undefined : getRoute(routeId).chunkId; } @@ -439,27 +472,52 @@ function ContextRouteGateway({ const location = useLocation(); const recovery = useApplicationRecovery(); const diagnostics = useApplicationDiagnostics(); + const features = useApplicationFeatures(); + const platformRuntime = useApplicationRuntime(); const [routes, setRoutes] = useState(null); const [failure, setFailure] = useState | null>( null, ); + // The URL this context was entered with (the gateway is keyed per context). + const [enteredPathname] = useState(() => location.pathname); useEffect(() => { let active = true; setRoutes(null); setFailure(null); - void routeModule.loadRoutes().then( - (loaded) => { - if (active) setRoutes(loaded); - }, - (error: unknown) => { - if (active) setFailure({ error }); - }, - ); + // A feature the runtime document switched off is not loaded: its routes + // answer with the disabled-feature surface. + const loadActive = (featureIds: readonly string[]) => + Promise.all( + featureIds + .filter((featureId) => platformRuntime.isFeatureActive(featureId)) + .map((featureId) => features.load(featureId)), + ); + // The feature that owns the entered URL starts loading together with the + // routes, so its runtime half adds no round trip of its own. + const enteredRouteId = registeredRouteIdAt(enteredPathname); + const enteredOwner = + enteredRouteId === undefined ? undefined : ROUTE_FEATURE_OWNER[enteredRouteId]; + void Promise.all([ + routeModule.loadRoutes(), + loadActive(enteredOwner === undefined ? [] : [enteredOwner]), + ]) + .then(async ([loaded]) => { + await loadActive(routeOwners(loaded)); + return loaded; + }) + .then( + (loaded) => { + if (active) setRoutes(loaded); + }, + (error: unknown) => { + if (active) setFailure({ error }); + }, + ); return () => { active = false; }; - }, [routeModule]); + }, [enteredPathname, features, platformRuntime, routeModule]); const resetKey = `${location.pathname}${location.search}`; const withinContext = (content: ReactNode) => ( @@ -509,6 +567,7 @@ function ContextRouteGateway({ routeId={handle.routeId} buildId={buildId} runtimeOverride={handle.runtime} + {...(handle.codecs === undefined ? {} : { codecsOverride: handle.codecs })} paramsOverride={selectedMatch.params} /> ); diff --git a/src/presentation/routes/route-codecs.ts b/src/presentation/routes/route-codecs.ts index 7ea4dd93..ec09a42e 100644 --- a/src/presentation/routes/route-codecs.ts +++ b/src/presentation/routes/route-codecs.ts @@ -1,5 +1,5 @@ import { getRoute, ROUTE_RUNTIME_CONTRACT } from "../../features/installed-feature-contracts.ts"; -import { ROUTE_CODECS } from "../../features/installed-feature-runtimes.tsx"; +import { PLATFORM_ROUTE_CODECS } from "./platform-route-codecs.ts"; import type { ParsedRouteInput, RouteId, @@ -8,8 +8,31 @@ import type { export type { ParsedRouteInput, RouteId, RouteInputResult }; -function codecById(codecId: string) { - const codec = ROUTE_CODECS[codecId as keyof typeof ROUTE_CODECS]; +type RouteCodec = Readonly<{ + safeParse(value: unknown): + | Readonly<{ success: true; data: Readonly> }> + | Readonly<{ success: false }>; + parse(value: unknown): Readonly>; +}>; + +/** + * 15-01. A feature route's codecs come from its context route handle + * (`context-routes.ts`), loaded with the route; only the platform codecs are in + * the initial chunk. A feature codec may not shadow a platform one. + */ +export type FeatureRouteCodecs = Readonly>; + +function codecById(codecId: string, featureCodecs: FeatureRouteCodecs) { + const platform = Object.hasOwn(PLATFORM_ROUTE_CODECS, codecId); + const feature = Object.hasOwn(featureCodecs, codecId); + if (platform && feature) { + throw new TypeError(`Feature route codec shadows a platform codec: ${codecId}`); + } + const codec: RouteCodec | undefined = platform + ? PLATFORM_ROUTE_CODECS[codecId as keyof typeof PLATFORM_ROUTE_CODECS] + : feature + ? featureCodecs[codecId] + : undefined; if (!codec) throw new TypeError(`Unregistered route codec: ${codecId}`); return codec; } @@ -18,13 +41,14 @@ export function parseRouteInput( routeId: RouteId, rawParams: Readonly>, rawSearch: URLSearchParams, + featureCodecs: FeatureRouteCodecs = {}, ): RouteInputResult { const runtime = ROUTE_RUNTIME_CONTRACT[routeId]; - const params = codecById(runtime.paramsCodec).safeParse(rawParams); + const params = codecById(runtime.paramsCodec, featureCodecs).safeParse(rawParams); if (!params.success) { return { success: false, code: "ROUTE_PARAMS_INVALID" }; } - const search = codecById(runtime.searchCodec).safeParse( + const search = codecById(runtime.searchCodec, featureCodecs).safeParse( searchRecord(rawSearch), ); if (!search.success) { @@ -48,14 +72,19 @@ export function buildRouteUrl( params?: Readonly>; search?: Readonly>; }> = {}, + featureCodecs: FeatureRouteCodecs = {}, ): string { const definition = getRoute(routeId); if (definition.path === "*") { throw new TypeError("The not-found route cannot build a canonical URL"); } const runtime = ROUTE_RUNTIME_CONTRACT[routeId]; - const params = codecById(runtime.paramsCodec).parse(input.params ?? {}); - const search = codecById(runtime.searchCodec).parse(input.search ?? {}); + const params = codecById(runtime.paramsCodec, featureCodecs).parse( + input.params ?? {}, + ); + const search = codecById(runtime.searchCodec, featureCodecs).parse( + input.search ?? {}, + ); const parsedParams: Record = { ...params }; const parsedSearch: Record = { ...search }; let path = definition.path; diff --git a/src/presentation/routes/route-runtime.tsx b/src/presentation/routes/route-runtime.tsx index 8ae93a40..69dfb550 100644 --- a/src/presentation/routes/route-runtime.tsx +++ b/src/presentation/routes/route-runtime.tsx @@ -24,9 +24,10 @@ function runtime( export const PLATFORM_ROUTE_RUNTIME = { APP_HOME: runtime("APP_HOME", () => import("../pages/home-page.tsx")), - EXAMPLES_PLATFORM: runtime( - "EXAMPLES_PLATFORM", - () => import("../examples/platform-overview-page.tsx"), + EXAMPLES_PLATFORM: runtime("EXAMPLES_PLATFORM", () => + import("../examples/platform-overview-page.tsx").then((module) => + module.loadPlatformOverviewPage(), + ), ), EXAMPLES_UI: runtime( "EXAMPLES_UI", diff --git a/tests/architecture/module-hierarchy.test.ts b/tests/architecture/module-hierarchy.test.ts index e6da1f76..3ac2f803 100644 --- a/tests/architecture/module-hierarchy.test.ts +++ b/tests/architecture/module-hierarchy.test.ts @@ -3,7 +3,7 @@ import { defineFeatureModule } from "../../src/features/feature-module.ts"; import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts"; import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts"; -const feature = defineFeatureModule({ id:"f", contracts:{featureId:"f"}, routes:{}, adapters:[], runtimes:[], messages:{}, contractContributions:[] }); +const feature = defineFeatureModule({ id:"f", contracts:{featureId:"f"}, routes:{}, messages:{}, loadRuntime: async () => ({ featureId: "f", apiContract: {}, adapters: [], contractContributions: [] }) }); describe("module hierarchy", () => { it("exposes only direct children and freezes copied arrays", () => { const features = [feature]; diff --git a/tests/architecture/topology-cardinality.test.ts b/tests/architecture/topology-cardinality.test.ts index 2f71aa7f..ab611263 100644 --- a/tests/architecture/topology-cardinality.test.ts +++ b/tests/architecture/topology-cardinality.test.ts @@ -13,10 +13,13 @@ function fakeFeature(id: string) { id, contracts: { featureId: id }, routes: {}, - adapters: [], - runtimes: [], messages: {}, - contractContributions: [], + loadRuntime: async () => ({ + featureId: id, + apiContract: {}, + adapters: [], + contractContributions: [], + }), }); } diff --git a/tests/component/platform-overview-page.test.tsx b/tests/component/platform-overview-page.test.tsx index 17f23933..39360813 100644 --- a/tests/component/platform-overview-page.test.tsx +++ b/tests/component/platform-overview-page.test.tsx @@ -4,9 +4,9 @@ import { render, screen, waitFor, within } from "@testing-library/react"; import { describe, expect, it } from "vitest"; import { SERVER_STATE_PROFILES } from "../../src/contracts/server-state.ts"; -import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/installed-contract-contributions.ts"; +import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts"; import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts"; -import PlatformOverviewPage from "../../src/presentation/examples/platform-overview-page.tsx"; +import { PlatformOverviewPage } from "../../src/presentation/examples/platform-overview-page.tsx"; import { LocaleProvider } from "../../src/presentation/i18n/index.ts"; import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; import { createTestApplication } from "../helpers/create-test-application.ts"; @@ -22,7 +22,7 @@ function renderPage() { return render( - + , ); @@ -112,7 +112,7 @@ describe("platform overview page", () => { })} > - + , ); diff --git a/tests/component/route-status-surfaces.test.tsx b/tests/component/route-status-surfaces.test.tsx index 5344b45b..ffef8894 100644 --- a/tests/component/route-status-surfaces.test.tsx +++ b/tests/component/route-status-surfaces.test.tsx @@ -8,7 +8,8 @@ import { describe, expect, it, vi } from "vitest"; import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts"; import type { ApplicationOutputPorts } from "../../src/application/create-application.ts"; import HomePage from "../../src/presentation/pages/home-page.tsx"; -import PlatformOverviewPage from "../../src/presentation/examples/platform-overview-page.tsx"; +import { PlatformOverviewPage } from "../../src/presentation/examples/platform-overview-page.tsx"; +import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts"; import { LocaleProvider } from "../../src/presentation/i18n/index.ts"; import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; @@ -186,7 +187,7 @@ describe("temporary release loaders", () => { render( - + , ); diff --git a/tests/features/feature-installation-surface.test.ts b/tests/features/feature-installation-surface.test.ts index 7c3fcb1d..727ef131 100644 --- a/tests/features/feature-installation-surface.test.ts +++ b/tests/features/feature-installation-surface.test.ts @@ -1,6 +1,6 @@ import { readFile } from "node:fs/promises"; import { describe, expect, it } from "vitest"; -const files=["installed-product-manifest.ts","installed-feature-adapters.ts","installed-feature-runtimes.tsx","installed-feature-messages.ts","installed-contract-contributions.ts","installed-feature-contracts.ts"]; +const files=["installed-product-manifest.ts","installed-feature-adapters.ts","loaded-feature-runtimes.ts","installed-feature-messages.ts","installed-contract-contributions.ts","installed-feature-contracts.ts"]; describe("feature installation surface", () => { it("contains no reference-specific central imports", async () => { for(const name of files){const source=await readFile(new URL(`../../src/features/${name}`,import.meta.url),"utf8"); expect(source).not.toMatch(/REFERENCE_FEATURE_(ADAPTER|RUNTIME|CONTRACT)/); expect(source).not.toMatch(/REFERENCE_MESSAGE_CATALOGS/);} diff --git a/tests/features/feature-module.test.ts b/tests/features/feature-module.test.ts index 035ad087..d30848a6 100644 --- a/tests/features/feature-module.test.ts +++ b/tests/features/feature-module.test.ts @@ -1,12 +1,22 @@ import { describe, expect, it } from "vitest"; -import { defineFeatureModule } from "../../src/features/feature-module.ts"; +import { + defineFeatureModule, + loadFeatureRuntime, +} from "../../src/features/feature-module.ts"; + +const runtimeOf = async (featureId: string) => ({ + featureId, + apiContract: {}, + adapters: [], + contractContributions: [], +}); describe("defineFeatureModule", () => { it("keeps one stable feature id and freezes the descriptor", () => { const module = defineFeatureModule({ id: "feature-a", contracts: { featureId: "feature-a" }, - routes: {}, adapters: [], runtimes: [], messages: {}, contractContributions: [], + routes: {}, messages: {}, loadRuntime: () => runtimeOf("feature-a"), }); expect(module.id).toBe("feature-a"); expect(Object.isFrozen(module)).toBe(true); @@ -18,8 +28,20 @@ describe("defineFeatureModule", () => { defineFeatureModule({ id: "feature-a", contracts: { featureId: "feature-b" }, - routes: {}, adapters: [], runtimes: [], messages: {}, contractContributions: [], + routes: {}, messages: {}, loadRuntime: () => runtimeOf("feature-a"), }), ).toThrow("Feature module id feature-a does not match contract featureId feature-b"); }); + + // 15-01: the runtime half is loaded lazily, so its owner is checked on load. + it("refuses a runtime half that belongs to another feature", async () => { + const module = defineFeatureModule({ + id: "feature-a", + contracts: { featureId: "feature-a" }, + routes: {}, messages: {}, loadRuntime: () => runtimeOf("feature-b"), + }); + await expect(loadFeatureRuntime(module)).rejects.toThrow( + "Feature module feature-a loaded the runtime of feature-b", + ); + }); }); diff --git a/tests/features/reference-feature/feature-module.test.ts b/tests/features/reference-feature/feature-module.test.ts index 2fd238c8..bf902659 100644 --- a/tests/features/reference-feature/feature-module.test.ts +++ b/tests/features/reference-feature/feature-module.test.ts @@ -1,14 +1,18 @@ import { describe, expect, it } from "vitest"; +import { loadFeatureRuntime } from "../../../src/features/feature-module.ts"; import { REFERENCE_FEATURE_MODULE } from "../../../src/features/reference-feature/feature-module.ts"; describe("REFERENCE_FEATURE_MODULE", () => { - it("owns every install-time contribution under one feature id", () => { + it("owns every install-time contribution under one feature id", async () => { expect(REFERENCE_FEATURE_MODULE.id).toBe("reference-feature"); expect(REFERENCE_FEATURE_MODULE.contracts).toBeDefined(); expect(REFERENCE_FEATURE_MODULE.routes).toBeDefined(); - expect(REFERENCE_FEATURE_MODULE.adapters.length).toBeGreaterThan(0); - expect(REFERENCE_FEATURE_MODULE.runtimes.length).toBeGreaterThan(0); expect(REFERENCE_FEATURE_MODULE.messages).toBeDefined(); - expect(REFERENCE_FEATURE_MODULE.contractContributions.length).toBeGreaterThan(0); + // 15-01. The executable half arrives through loadRuntime. + const runtime = await loadFeatureRuntime(REFERENCE_FEATURE_MODULE); + expect(runtime.featureId).toBe("reference-feature"); + expect(runtime.adapters.length).toBeGreaterThan(0); + expect(runtime.contractContributions.length).toBeGreaterThan(0); + expect(Object.keys(runtime.apiContract.apiOperations).length).toBeGreaterThan(0); }); }); diff --git a/tests/features/reference-feature/reference-contract.test.ts b/tests/features/reference-feature/reference-contract.test.ts index 7f01eb3d..fb7bebcc 100644 --- a/tests/features/reference-feature/reference-contract.test.ts +++ b/tests/features/reference-feature/reference-contract.test.ts @@ -17,6 +17,8 @@ import { REFERENCE_FEATURE_ID, REFERENCE_RESOURCE_INVALIDATION_TOPIC, } from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts"; +import { REFERENCE_API_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-api-contract.ts"; +import { REFERENCE_FEATURE_ROUTE_CODECS } from "../../../src/features/reference-feature/presentation/reference-feature-runtime.ts"; import type { ReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts"; import { createTestApplication } from "../../helpers/create-test-application.ts"; import { createReferenceFeatureInstalledInput } from "../../../src/features/reference-feature/adapters/create-reference-feature-input.ts"; @@ -53,7 +55,11 @@ describe("reference feature boundary contracts", () => { cursor: "a/b", limit: 5, }; - const url = buildRouteUrl("REFERENCE_RESOURCE_LIST", { search: filters }); + const url = buildRouteUrl( + "REFERENCE_RESOURCE_LIST", + { search: filters }, + REFERENCE_FEATURE_ROUTE_CODECS, + ); expect(url).toBe( "/examples/reference-resources?cursor=a%2Fb&limit=5&tags=open&tags=new", ); @@ -61,6 +67,7 @@ describe("reference feature boundary contracts", () => { "REFERENCE_RESOURCE_LIST", {}, new URL(url, "https://app.test").searchParams, + REFERENCE_FEATURE_ROUTE_CODECS, ); expect(parsed).toMatchObject({ success: true, @@ -74,6 +81,7 @@ describe("reference feature boundary contracts", () => { "REFERENCE_RESOURCE_LIST", {}, new URLSearchParams("unknown=value"), + REFERENCE_FEATURE_ROUTE_CODECS, ), ).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" }); expect( @@ -116,13 +124,13 @@ describe("reference feature boundary contracts", () => { "REFERENCE_RESOURCE_FORM", "REFERENCE_RESOURCE_STATUS", ]); - expect(Object.keys(REFERENCE_FEATURE_CONTRACT.apiOperations)).toEqual([ + expect(Object.keys(REFERENCE_API_CONTRACT.apiOperations)).toEqual([ "LIST_REFERENCE_RESOURCES", "CREATE_REFERENCE_RESOURCE", "GET_REFERENCE_RESOURCE", ]); expect( - REFERENCE_FEATURE_CONTRACT.apiOperations.GET_REFERENCE_RESOURCE, + REFERENCE_API_CONTRACT.apiOperations.GET_REFERENCE_RESOURCE, ).toMatchObject({ pathSchema: "ReferenceResourceParams", pathParameterNames: ["resourceId"], diff --git a/tests/features/reference-feature/reference-runtime-composition.test.ts b/tests/features/reference-feature/reference-runtime-composition.test.ts index 1c1a706b..4c4d0540 100644 --- a/tests/features/reference-feature/reference-runtime-composition.test.ts +++ b/tests/features/reference-feature/reference-runtime-composition.test.ts @@ -90,16 +90,18 @@ function referenceBoundQueryKey() { * manifest did not select supplies none. This suite is about the reference * feature being composed, so it asserts that first and narrows once. */ -function referenceInput< - Inputs extends Readonly>>, ->(adapters: Readonly<{ featureInputs: Inputs }>) { - const input = adapters.featureInputs[REFERENCE_FEATURE_ID]; +async function referenceInput( + adapters: Awaited>, +) { + // 15-01. The input is created when the feature's runtime half loads. + const load = adapters.featureLoaders[REFERENCE_FEATURE_ID]; + const input = load ? (await load())[REFERENCE_FEATURE_ID] : undefined; if (!input) { throw new Error( `${REFERENCE_FEATURE_ID} is not installed; the manifest did not select it`, ); } - return input as NonNullable; + return input; } describe("reference feature runtime composition", () => { @@ -136,7 +138,7 @@ describe("reference feature runtime composition", () => { ); await expect( - referenceInput(adapters).listResources({ limit: 20 }), + (await referenceInput(adapters)).listResources({ limit: 20 }), ).resolves.toEqual({ ok: true, value: [ @@ -189,7 +191,7 @@ describe("reference feature runtime composition", () => { }); await expect( - referenceInput(adapters).createResource( + (await referenceInput(adapters)).createResource( { name: "Created resource" }, { intent }, ), @@ -234,7 +236,7 @@ describe("reference feature runtime composition", () => { session.subscribe(notifications); await expect( - referenceInput(adapters).listResources({ limit: 20 }), + (await referenceInput(adapters)).listResources({ limit: 20 }), ).resolves.toMatchObject({ ok: false }); expect(fetcher).not.toHaveBeenCalled(); @@ -259,7 +261,7 @@ describe("reference feature runtime composition", () => { ); await expect( - referenceInput(adapters).listResources({ limit: 20 }), + (await referenceInput(adapters)).listResources({ limit: 20 }), ).resolves.toMatchObject({ ok: false }); expect(fetcher).toHaveBeenCalledOnce(); diff --git a/tests/helpers/fixture-feature.tsx b/tests/helpers/fixture-feature.tsx index 3dccdf1c..026bda41 100644 --- a/tests/helpers/fixture-feature.tsx +++ b/tests/helpers/fixture-feature.tsx @@ -80,28 +80,31 @@ export const FIXTURE_FEATURE_MODULE = defineFeatureModule({ ]), ), ), - apiOperations: Object.freeze({}), invalidation: Object.freeze({ topics: [], namespaces: [], edges: [] }), topicVersions: Object.freeze([]), - schemas: Object.freeze({}), - runtimeSchemas: Object.freeze({}), - mappers: Object.freeze({}), + contractPackages: Object.freeze([]), }), routes: FIXTURE_ROUTES, - adapters: [], - runtimes: [ + messages: Object.freeze({ "ko-KR": FIXTURE_MESSAGES, "en-US": FIXTURE_MESSAGES }), + loadRuntime: async () => Object.freeze({ featureId: FIXTURE_FEATURE_ID, - routeCodecs: Object.freeze({ - FixtureItemsQuery: z.object({ - limit: z.coerce.number().int().min(1).max(100).default(20), - }), + apiContract: Object.freeze({ + apiOperations: Object.freeze({}), + schemas: Object.freeze({}), + runtimeSchemas: Object.freeze({}), + mappers: Object.freeze({}), }), - routeRuntime: Object.freeze({}), + adapters: Object.freeze([]), + contractContributions: Object.freeze([]), }), - ], - messages: Object.freeze({ "ko-KR": FIXTURE_MESSAGES, "en-US": FIXTURE_MESSAGES }), - contractContributions: [], +}); + +// 15-01. Route codecs travel on the context route handle, like the sample's. +const FIXTURE_ROUTE_CODECS = Object.freeze({ + FixtureItemsQuery: z.object({ + limit: z.coerce.number().int().min(1).max(100).default(20), + }), }); function FixturePage() { @@ -116,6 +119,7 @@ export const FIXTURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze( handle: Object.freeze({ routeId: route.routeId, runtime: Object.freeze({ moduleId: `${route.chunkId}-page`, Component: FixturePage }), + codecs: FIXTURE_ROUTE_CODECS, }), }), ), diff --git a/tests/unit/api-operation-v2.test.ts b/tests/unit/api-operation-v2.test.ts index 87079b37..21e8f502 100644 --- a/tests/unit/api-operation-v2.test.ts +++ b/tests/unit/api-operation-v2.test.ts @@ -5,7 +5,7 @@ import { defineRestOperation, type RestOperationV2, } from "../../src/contracts/api-operations.ts"; -import { API_OPERATIONS } from "../../src/features/installed-feature-contracts.ts"; +import { API_OPERATIONS } from "../../src/features/loaded-feature-runtimes.ts"; function operation(operationId = "GET_RESOURCE") { return defineRestOperation({ diff --git a/tests/unit/feature-shape-growth.test.ts b/tests/unit/feature-shape-growth.test.ts index 99cfc0c9..45e0a97f 100644 --- a/tests/unit/feature-shape-growth.test.ts +++ b/tests/unit/feature-shape-growth.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest"; import { FEATURE_SHAPE_BASELINE_PATH, FEATURE_SHAPE_CEILINGS_PATH, + measureInitialJavascriptGzipBytes, renameReferenceFeature, } from "../../scripts/scale/measure-feature-shape-growth.ts"; import { APP_MAX_CONTEXTS } from "../../src/apps/template-app/app-module.ts"; @@ -95,6 +96,25 @@ describe("feature-shape growth measurement (11-04)", () => { } }); + /** + * 15-01. The initial budget (config/performance/budgets.json) is a fixed + * 200 KiB for the whole app, so what one installed feature adds to the + * initial chunk decides how many features fit. Before 15-01 every feature's + * contracts, schemas, mappers, HTTP gateway and API loaded at boot: +3,922 B + * per copy, and the first added feature exceeded the budget. Only what the + * shell needs before a feature route is entered may load at boot (route + * table, navigation and page messages, invalidation identities: 741 B when + * 15-01 landed); the rest loads with the feature's routes. The bound also + * fails if the feature-declarations chunk group in vite.config.ts stops + * matching. + */ + it("adds at most 1 KiB of initial JavaScript per reference-shaped feature (15-01)", async () => { + const withoutCopies = await measureInitialJavascriptGzipBytes(0); + const withOneCopy = await measureInitialJavascriptGzipBytes(1); + + expect(withOneCopy - withoutCopies).toBeLessThanOrEqual(1_024); + }, 120_000); + it("states in the committed rationale what the ceilings rest on", async () => { // The rationale lives next to the baseline, not in a review document: the // history documents may be deleted after copying (README.md). diff --git a/tests/unit/http-operation-v2-v3-parity.test.ts b/tests/unit/http-operation-v2-v3-parity.test.ts index bb6fe398..340c0372 100644 --- a/tests/unit/http-operation-v2-v3-parity.test.ts +++ b/tests/unit/http-operation-v2-v3-parity.test.ts @@ -4,8 +4,10 @@ import type { ApiOperation, RestOperationV2, } from "../../src/contracts/api-operations.ts"; -import { INSTALLED_CONTRACT_CONTRIBUTIONS } from "../../src/features/installed-contract-contributions.ts"; -import { API_OPERATIONS } from "../../src/features/installed-feature-contracts.ts"; +import { + API_OPERATIONS, + INSTALLED_CONTRACT_CONTRIBUTIONS, +} from "../../src/features/loaded-feature-runtimes.ts"; // 07-03 (D-7). FE-REG-API governs the V2 rows while the V3 descriptors are // what executes. Until V2 is generated from V3, both copies must agree. diff --git a/tests/unit/product-feature-selection-build.test.ts b/tests/unit/product-feature-selection-build.test.ts index 987efb1c..2a8242a3 100644 --- a/tests/unit/product-feature-selection-build.test.ts +++ b/tests/unit/product-feature-selection-build.test.ts @@ -65,8 +65,8 @@ describe("VITE_PRODUCT_FEATURES=none build (09-02)", () => { 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"); + pathToFileURL(path.join(root, "src/features/loaded-feature-runtimes.ts")).href + )) as typeof import("../../src/features/loaded-feature-runtimes.ts"); expect(contributions.INSTALLED_CONTRACT_CONTRIBUTIONS).toEqual([]); const manifest = (await import( pathToFileURL(path.join(root, "src/features/installed-product-manifest.ts")).href diff --git a/tests/unit/route-runtime.test.ts b/tests/unit/route-runtime.test.ts index 5e4b3475..57dd8765 100644 --- a/tests/unit/route-runtime.test.ts +++ b/tests/unit/route-runtime.test.ts @@ -1,23 +1,51 @@ import { describe, expect, it } from "vitest"; import { + ROUTE_FEATURE_OWNER, ROUTE_REGISTRY, ROUTE_RUNTIME_CONTRACT, } from "../../src/features/installed-feature-contracts.ts"; -import { ROUTE_RUNTIME } from "../../src/features/installed-feature-runtimes.tsx"; import { PLATFORM_ROUTE_REGISTRY } from "../../src/contracts/routes.ts"; +import { PRODUCT_CONTEXT_MODULES } from "../../src/.generated/product-context-index.ts"; +import { PLATFORM_ROUTE_CODECS } from "../../src/presentation/routes/platform-route-codecs.ts"; import { parseRouteInput } from "../../src/presentation/routes/route-codecs.ts"; +import { PLATFORM_ROUTE_RUNTIME } from "../../src/presentation/routes/route-runtime.tsx"; describe("typed installed route catalog", () => { it("keeps contract and executable runtime contributions complete", () => { expect(Object.keys(ROUTE_RUNTIME_CONTRACT).sort()).toEqual( Object.keys(ROUTE_REGISTRY).sort(), ); - expect(Object.keys(ROUTE_RUNTIME).sort()).toEqual( + expect(Object.keys(PLATFORM_ROUTE_RUNTIME).sort()).toEqual( Object.keys(PLATFORM_ROUTE_REGISTRY).sort(), ); }); + // 15-01. Feature route codecs moved from the boot-time feature module to the + // context route handles; every codec a route names must still resolve. + it("resolves every route's codecs from the platform or its context route handle", async () => { + const featureCodecs = new Map>>(); + for (const context of PRODUCT_CONTEXT_MODULES) { + for (const route of (await context.route?.loadRoutes()) ?? []) { + const handle = route.handle as + | Readonly<{ routeId: string; codecs?: Readonly> }> + | undefined; + if (handle) featureCodecs.set(handle.routeId, handle.codecs ?? {}); + } + } + for (const [routeId, runtime] of Object.entries(ROUTE_RUNTIME_CONTRACT)) { + const available = { + ...PLATFORM_ROUTE_CODECS, + ...(ROUTE_FEATURE_OWNER[routeId] === undefined + ? {} + : featureCodecs.get(routeId)), + }; + for (const codecId of [runtime.paramsCodec, runtime.searchCodec]) { + expect(Object.hasOwn(available, codecId), `${routeId}: ${codecId}`).toBe(true); + } + } + }); + it("accepts the platform not-found splat owner", () => { expect( parseRouteInput( diff --git a/tests/unit/runtime-adapters-auth-profile.test.ts b/tests/unit/runtime-adapters-auth-profile.test.ts index 616f7702..9f83f368 100644 --- a/tests/unit/runtime-adapters-auth-profile.test.ts +++ b/tests/unit/runtime-adapters-auth-profile.test.ts @@ -34,22 +34,30 @@ const fixture = vi.hoisted(() => ({ vi.mock("../../src/features/installed-contract-contributions.ts", async (importOriginal) => { const original = await importOriginal(); - const { composeContractContributions } = await import( - "../../src/contracts/external-contract-runtime.ts" - ); const { TEST_CONTRACT_CONTRIBUTION, TEST_LIST_HTTP_CONTRACT: list } = await import("../helpers/external-contract-fixture.ts"); + const source = TEST_CONTRACT_CONTRIBUTION.source; + if (source.kind !== "EXTERNAL_PACKAGE") throw new Error("fixture source changed"); return { ...original, - COMPOSED_CONTRACT_CONTRIBUTIONS: composeContractContributions([ - { - ...TEST_CONTRACT_CONTRIBUTION, - http: [ - list, - fixture.withProfile(list, "TEST_LIST_ENTITIES_BEARER", "REFERENCE_EXTERNAL_BEARER"), - ] as typeof TEST_CONTRACT_CONTRIBUTION.http, - }, - ]), + // 15-01. The registry fills as feature runtimes load; this one starts with + // the fixture contribution, as if its feature had loaded. + createInstalledContractRegistry: () => { + const registry = original.createInstalledContractRegistry([ + ...original.EXPECTED_CONTRACT_SET_PACKAGES, + source.package, + ]); + registry.install(TEST_CONTRACT_CONTRIBUTION.featureId, [ + { + ...TEST_CONTRACT_CONTRIBUTION, + http: [ + list, + fixture.withProfile(list, "TEST_LIST_ENTITIES_BEARER", "REFERENCE_EXTERNAL_BEARER"), + ] as typeof TEST_CONTRACT_CONTRIBUTION.http, + }, + ]); + return registry; + }, }; }); @@ -58,11 +66,11 @@ vi.mock("../../src/features/installed-feature-adapters.ts", async (importOrigina await importOriginal(); return { ...original, - createInstalledFeatureInputs: ( - ...args: Parameters + createInstalledFeatureLoaders: ( + ...args: Parameters ) => { fixture.http = args[0].http; - return original.createInstalledFeatureInputs(...args); + return original.createInstalledFeatureLoaders(...args); }, }; }); diff --git a/tests/unit/runtime-adapters.test.ts b/tests/unit/runtime-adapters.test.ts index c5234b33..aa9135d7 100644 --- a/tests/unit/runtime-adapters.test.ts +++ b/tests/unit/runtime-adapters.test.ts @@ -379,15 +379,19 @@ describe("runtime adapter composition", () => { }); const application = createApplication( adapters.outputPorts, - adapters.featureInputs, + {}, + adapters.featureLoaders, ); expect(adapters.outputPorts.productFeatures.isActive(disabledId!)).toBe(false); + // 15-01. A switched-off feature gets no loader, so loading installs nothing. + await application.features.load(disabledId!); expect(application.features.has(disabledId!)).toBe(false); expect(() => application.features.get(disabledId as ApplicationFeatureId), ).toThrow(/not installed/u); for (const featureId of activeIds) { + await application.features.load(featureId); expect(application.features.has(featureId)).toBe(true); } adapters.infrastructure.dispose(); @@ -397,10 +401,16 @@ describe("runtime adapter composition", () => { const adapters = await createRuntimeAdapters({ runtime, release, host: {} }); const application = createApplication( adapters.outputPorts, - adapters.featureInputs, + {}, + adapters.featureLoaders, ); for (const featureId of INSTALLED_PRODUCT_FEATURE_IDS) { + // 15-01. Not loaded until the router asks for the feature's routes. + expect(() => + application.features.get(featureId as ApplicationFeatureId), + ).toThrow(/not loaded yet/u); + await application.features.load(featureId); expect(application.features.has(featureId)).toBe(true); expect( application.features.get(featureId as ApplicationFeatureId), diff --git a/tests/unit/second-api-feature-registries.test.ts b/tests/unit/second-api-feature-registries.test.ts index e2a8ba94..c9554c3b 100644 --- a/tests/unit/second-api-feature-registries.test.ts +++ b/tests/unit/second-api-feature-registries.test.ts @@ -33,10 +33,18 @@ const codec = (schemaId: string) => safeParse: (value: unknown) => Object.freeze({ success: true as const, data: value }), }); +// 15-01. Declaration half: what the shell reads at boot. export const SECOND_API_CONTRACT = Object.freeze({ featureId: "${FEATURE_ID}", routes: {}, routeRuntimeContracts: {}, + invalidation: { topics: Object.freeze([]), namespaces: Object.freeze([]), edges: Object.freeze([]) }, + topicVersions: Object.freeze([]), + contractPackages: Object.freeze([]), +} as const); + +// Runtime half: the V2 API contract, loaded with feature-runtime.ts. +export const SECOND_API_V2_CONTRACT = Object.freeze({ apiOperations: Object.freeze({ GET_SECOND_ITEM: defineRestOperation({ method: "GET", @@ -67,8 +75,6 @@ export const SECOND_API_CONTRACT = Object.freeze({ maxEncodedSearchBytes: 0, }), }), - invalidation: { topics: Object.freeze([]), namespaces: Object.freeze([]), edges: Object.freeze([]) }, - topicVersions: Object.freeze([]), schemas: Object.freeze({ SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"), SecondItemRequest: schema("SecondItemRequest", "api-request", "REQUEST"), @@ -104,9 +110,18 @@ export const FEATURE_MODULE = defineFeatureModule({ id: FEATURE_MODULE_ID, contracts: SECOND_API_CONTRACT, routes: {}, - adapters: [], - runtimes: [], messages: {}, + loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME, +} as const); +`; + +const FEATURE_RUNTIME = `import { defineFeatureRuntime } from "../feature-module.ts"; +import { SECOND_API_V2_CONTRACT } from "./contracts/second-api-contract.ts"; + +export const FEATURE_RUNTIME = defineFeatureRuntime({ + featureId: "${FEATURE_ID}", + apiContract: SECOND_API_V2_CONTRACT, + adapters: [], contractContributions: [], } as const); `; @@ -149,6 +164,7 @@ describe("adding a feature with an API operation (F-3, 09-07)", () => { const files: Readonly> = { [`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, [`src/features/${FEATURE_ID}/contracts/second-api-contract.ts`]: FEATURE_CONTRACT, [`src/features/${FEATURE_ID}/adapters/second-api-gateway.ts`]: FEATURE_GATEWAY, diff --git a/tests/unit/two-feature-install-typecheck.test.ts b/tests/unit/two-feature-install-typecheck.test.ts index 756491d0..71b80c28 100644 --- a/tests/unit/two-feature-install-typecheck.test.ts +++ b/tests/unit/two-feature-install-typecheck.test.ts @@ -12,21 +12,14 @@ import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.t * generated feature index, so the repository's own typecheck only ever sees * the features it ships. This installs two more into a copy of `src`, in a * context of their own so the check survives the sample's removal: one with a - * route, a runtime and both locales but no adapter, and one shaped differently - * on every composed axis (an adapter that needs telemetry, no routes, no - * runtime, one locale). It regenerates the index - * with the production generator and runs the app typecheck over the copy. + * route, route codecs and both locales but no adapter, and one shaped + * differently on every composed axis (an adapter that needs telemetry, no + * routes, no codecs, one locale). Each declares its executable half in a + * separate \`feature-runtime.ts\` loaded through \`loadRuntime\` (15-01). It + * regenerates the index with the production generator and runs the app + * typecheck over the copy. */ -const SECOND_FEATURE_MODULE = `import { defineFeatureAdapterContribution } from "../feature-adapter-contribution.ts"; -import { defineFeatureModule } from "../feature-module.ts"; - -type SecondFeatureInput = Readonly<{ ping(): string }>; - -declare module "../../application/ports/in/application-api.ts" { - interface ApplicationFeatureInputs { - "second-feature": SecondFeatureInput; - } -} +const SECOND_FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts"; export const FEATURE_MODULE_ID = "second-feature"; export const FEATURE_CONTEXT_ID = "two-feature-context"; @@ -37,7 +30,6 @@ export const FEATURE_MODULE = defineFeatureModule({ featureId: FEATURE_MODULE_ID, routes: {}, routeRuntimeContracts: {}, - apiOperations: {}, // Frozen empty arrays type as \`readonly never[]\`, not \`readonly []\`. invalidation: { topics: Object.freeze([]), @@ -45,24 +37,39 @@ export const FEATURE_MODULE = defineFeatureModule({ edges: Object.freeze([]), }, topicVersions: Object.freeze([]), - schemas: {}, - runtimeSchemas: {}, - mappers: {}, + contractPackages: Object.freeze([]), }, routes: {}, + messages: { "en-US": { "secondFeature.title": "Second feature" } }, + loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME, +} as const); +`; + +const SECOND_FEATURE_RUNTIME = `import { defineFeatureAdapterContribution } from "../feature-adapter-contribution.ts"; +import { defineFeatureRuntime } from "../feature-module.ts"; + +type SecondFeatureInput = Readonly<{ ping(): string }>; + +declare module "../../application/ports/in/application-api.ts" { + interface ApplicationFeatureInputs { + "second-feature": SecondFeatureInput; + } +} + +export const FEATURE_RUNTIME = defineFeatureRuntime({ + featureId: "second-feature", + apiContract: { apiOperations: {}, schemas: {}, runtimeSchemas: {}, mappers: {} }, adapters: [ defineFeatureAdapterContribution({ - featureId: FEATURE_MODULE_ID, + featureId: "second-feature", needs: ["telemetry"] as const, createInput: () => Object.freeze({ - featureId: FEATURE_MODULE_ID, + featureId: "second-feature", input: Object.freeze({ ping: () => "pong" }), }), }), ], - runtimes: [], - messages: { "en-US": { "secondFeature.title": "Second feature" } }, contractContributions: [], } as const); `; @@ -111,18 +118,18 @@ export const FEATURE_MODULE = defineFeatureModule({ searchCodec: "none", }, }, - apiOperations: {}, invalidation: { topics: [], namespaces: [], edges: [] }, topicVersions: [], - schemas: {}, - runtimeSchemas: {}, - mappers: {}, + contractPackages: [], }, routes: ROUTES, - adapters: [], - runtimes: [{ featureId: FEATURE_MODULE_ID, routeCodecs: {}, routeRuntime: {} }], messages: { "ko-KR": MESSAGES, "en-US": MESSAGES }, - contractContributions: [], + loadRuntime: async () => ({ + featureId: FEATURE_MODULE_ID, + apiContract: { apiOperations: {}, schemas: {}, runtimeSchemas: {}, mappers: {} }, + adapters: [], + contractContributions: [], + }), } as const); `; @@ -152,6 +159,7 @@ describe("installing a second feature (09-01)", () => { "src/features/routed-feature/feature-module.ts": ROUTED_FEATURE_MODULE, "src/features/routed-feature/context-routes.ts": SECOND_FEATURE_ROUTES, "src/features/second-feature/feature-module.ts": SECOND_FEATURE_MODULE, + "src/features/second-feature/feature-runtime.ts": SECOND_FEATURE_RUNTIME, "src/features/second-feature/context-routes.ts": SECOND_FEATURE_ROUTES, }; for (const [file, content] of Object.entries(files)) { diff --git a/vite.config.ts b/vite.config.ts index 6acd6049..fcbcca4c 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,3 +1,5 @@ +import path from "node:path"; + import { defineConfig, loadEnv } from "vite"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; @@ -59,6 +61,83 @@ function assertRuntimeConfigUnderBase( } } +type ModuleGraph = Readonly<{ + getModuleInfo(id: string): Readonly<{ + importedIds: readonly string[]; + dynamicallyImportedIds: readonly string[]; + }> | null; +}>; + +function staticClosure( + graph: ModuleGraph, + roots: readonly string[], + within: (id: string) => boolean = () => true, +): Set { + const reached = new Set(); + const pending = [...roots]; + for (let next = pending.pop(); next !== undefined; next = pending.pop()) { + if (reached.has(next) || !within(next)) continue; + reached.add(next); + pending.push(...(graph.getModuleInfo(next)?.importedIds ?? [])); + } + return reached; +} + +/** + * 15-01. Two chunk groups that keep moving the feature runtime halves out of + * the initial JavaScript from costing more than it saves. + * + * - `feature-declarations`: every installed feature's declaration, the static + * graph under src/features/ that the generated feature index reaches + * (feature-module.ts, its route contract and messages). A declaration is + * shared by the boot graph and its own feature's lazy runtime and pages, + * and rolldown otherwise gives each such set of importers a chunk of its + * own: one more initial file per feature, which doubled what a feature + * added to the initial JavaScript. + * - `feature-platform`: the boot modules the runtime halves also import (HTTP + * executor, contract runtime, zod). Left to rolldown they split into one + * initial chunk per set of importers; the per-file gzip overhead and the + * compression lost across files cost more than the runtime code removed. + * Modules that the boot-failure screen needs are left out, so + * render-boot-failure.tsx never depends on this chunk: it must still render + * when a module of the application graph throws while evaluating (09-03). + * + * Both only regroup modules the boot already loads; nothing lazy becomes + * initial. If feature-declarations comes out empty, the per-feature bound in + * tests/unit/feature-shape-growth.test.ts fails. feature-platform only moves + * the platform total (about 2 KB at 15-01), which the bundle budget + * (FE-GATE-012) checks. + */ +function createFeatureChunkGroups(root: string) { + const at = (file: string) => path.join(root, file); + const featuresRoot = `${at("src/features")}${path.sep}`; + let groups: ReadonlyMap | undefined; + const classify = (graph: ModuleGraph): ReadonlyMap => { + const index = graph.getModuleInfo(at("src/.generated/product-feature-index.ts")); + const declarations = staticClosure(graph, index?.importedIds ?? [], (id) => + id.startsWith(featuresRoot), + ); + const runtimes = staticClosure( + graph, + [...declarations].flatMap((id) => graph.getModuleInfo(id)?.dynamicallyImportedIds ?? []), + ); + const boot = staticClosure(graph, [at("src/bootstrap/boot.tsx")]); + const bootFailure = staticClosure(graph, [at("src/bootstrap/render-boot-failure.tsx")]); + const result = new Map(); + for (const id of declarations) result.set(id, "feature-declarations"); + for (const id of runtimes) { + if (boot.has(id) && !bootFailure.has(id) && !declarations.has(id)) { + result.set(id, "feature-platform"); + } + } + return result; + }; + return (id: string, graph: ModuleGraph): string | null => { + groups ??= classify(graph); + return groups.get(id) ?? null; + }; +} + export default defineConfig(({ mode }) => { assertDeclaredBuildVariables(mode); const base = routerBasePath(process.env); @@ -71,11 +150,21 @@ export default defineConfig(({ mode }) => { sourcemap: false, rollupOptions: { output: { - // 09-03. The entry now imports the app dynamically, so Vite's preload - // helper would land in the entry chunk and every lazy chunk would - // import the entry, whose hash changes with each build id. - manualChunks: (id: string) => - id.includes("vite/preload-helper") ? "preload-helper" : undefined, + codeSplitting: { + groups: [ + // 09-03. The entry now imports the app dynamically, so Vite's + // preload helper would land in the entry chunk and every lazy + // chunk would import the entry, whose hash changes with each + // build id. + { name: "preload-helper", test: /vite[\\/]preload-helper/ }, + { + name: createFeatureChunkGroups(process.cwd()), + // The boot-failure screen's modules stay out of + // feature-platform even when a grouped module imports them. + includeDependenciesRecursively: false, + }, + ], + }, }, }, },