import { spawnSync } from "node:child_process"; import { randomBytes } from "node:crypto"; import { access, mkdir, readdir, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; import { parseArgs } from "node:util"; import { composeContractContributions, ContractContributionError, } from "../src/contracts/external-contract-runtime.ts"; import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts"; /** * U7. `pnpm create:feature ` writes the smallest feature that passes every * merge gate: one list route without params, one GET (SAFE, EXTERNAL_BEARER), * one query, one invalidation topic, one CollectionPage with ko-KR and en-US * copy, and a router page test plus an input test. The templates live in this * file and import nothing from a sample feature, so the command keeps working * after a product deletes the sample (test:sample-removal runs it there). * * Every global id carries the feature prefix (review 16, 8.3): a copied id * collides in a registry that is global. The invalidation topic is random. * Outside the feature folder it writes only the context declaration (for a * new context) and the route's pending accessibility record; it never * overwrites a file, and a failed run leaves nothing behind. */ export type InstalledFacts = Readonly<{ appIds: readonly string[]; /** Declared feature ids and every src/features directory name. */ featureIds: readonly string[]; contexts: readonly Readonly<{ id: string; routePath: string }>[]; contextDirectories: readonly string[]; routes: readonly Readonly<{ routeId: string; path: string; chunkId: string; navigationOrder: number | null; }>[]; topics: readonly string[]; messageKeys: readonly string[]; }>; export type ContractPackageIdentity = Readonly<{ packageId: string; version: string; digest: string; sourceRevision: string; }>; export type FeatureRequest = Readonly<{ id: string; context?: string | undefined; contractPackage?: ContractPackageIdentity | undefined; }>; export type FeaturePlan = Readonly<{ id: string; contextId: string; newContext: boolean; routeId: string; routePath: string; topic: string; /** No package was given; the placeholder identity is pinned. */ placeholder: boolean; /** Repository-relative path -> content. */ files: ReadonlyMap; }>; export class CreateFeatureError extends Error {} const KEBAB = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u; /** Telemetry kinds allow 40 characters per segment; the base is one. */ const MAX_ID_LENGTH = 40; const TOPIC_SUFFIX = /^[0-9a-z]{26}$/u; /** Crockford base32, lower case: 32 symbols, so `byte & 31` has no bias. */ const TOPIC_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"; const NEW_CONTEXT_MAX_FEATURES = 20; const NAVIGATION_STEP = 10; export function randomTopicSuffix(): string { return [...randomBytes(26)] .map((byte) => TOPIC_ALPHABET[byte & 31]) .join(""); } function baseOf(id: string): string { return id.endsWith("-feature") && id !== "feature" ? id.slice(0, -"-feature".length) : id; } function namesOf(id: string) { const base = baseOf(id); const pascal = base .split("-") .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) .join(""); return Object.freeze({ id, base, upper: base.toUpperCase().replaceAll("-", "_"), pascal, camel: pascal.charAt(0).toLowerCase() + pascal.slice(1), title: base.charAt(0).toUpperCase() + base.slice(1).replaceAll("-", " "), }); } type Names = ReturnType; function fail(message: string): never { throw new CreateFeatureError(message); } function assertKebab(value: string, label: string, maxLength: number): void { if (!KEBAB.test(value) || value.length > maxLength) { fail( `${label} "${value}" must be kebab-case (lower-case words joined by single hyphens), at most ${maxLength} characters`, ); } } function assertPackageIdentity( featureId: string, identity: ContractPackageIdentity, ): void { try { composeContractContributions([ { contributionId: "create-feature-check", featureId, source: { kind: "EXTERNAL_PACKAGE", package: { ...identity, digest: identity.digest as `sha256:${string}`, runtimeProtocolVersion: 1, }, }, http: [], events: [], }, ]); } catch (error) { fail( `contract package ${identity.packageId}@${identity.version} is not a pinned identity: ${ error instanceof ContractContributionError ? error.reason : String(error) }`, ); } } /** The routes, files and ids of one feature. Pure apart from the topic. */ export function planFeature( request: FeatureRequest, installed: InstalledFacts, topicSuffix: () => string = randomTopicSuffix, ): FeaturePlan { const { id } = request; assertKebab(id, "feature id", MAX_ID_LENGTH); const names = namesOf(id); const contextIds = new Set([ ...installed.contexts.map((context) => context.id), ...installed.contextDirectories, ]); if (installed.featureIds.includes(id) || contextIds.has(id)) { fail(`feature id ${id} is already a feature or context`); } const sameBase = installed.featureIds.find( (featureId) => baseOf(featureId) === names.base, ); if (sameBase !== undefined) { fail( `feature id ${id} would prefix its ids with "${names.base}", which ${sameBase} already uses`, ); } const contextId = request.context ?? `${names.base}-context`; assertKebab(contextId, "context id", 64); if (installed.featureIds.includes(contextId)) { fail(`context id ${contextId} is a feature id`); } const existing = installed.contexts.find((context) => context.id === contextId); if (request.context === undefined && contextIds.has(contextId)) { fail( `context ${contextId} already exists; pass --context ${contextId} to add the feature to it`, ); } if (existing === undefined && contextIds.has(contextId)) { fail(`src/contexts has a ${contextId} directory without a context declaration`); } const contextRoot = existing ? existing.routePath.replace(/\/?\*$/u, "") : contextId.replace(/-context$/u, ""); if ( existing === undefined && installed.contexts.some((context) => context.routePath === `${contextRoot}/*`) ) { fail(`another context already owns the route root ${contextRoot}/*`); } if (existing === undefined && installed.appIds.length !== 1) { fail( `a new context needs exactly one deployable app (declared: ${installed.appIds.join(", ") || "none"}); pass --context `, ); } // A new context gives the feature its root; in an existing one the feature // takes a segment below the root. const routePath = existing ? `/${contextRoot}/${names.base}` : `/${contextRoot}`; const routeId = `${names.upper}_LIST`; const chunkId = `route-${names.base}-list`; for (const route of installed.routes) { if (route.routeId === routeId || route.path === routePath || route.chunkId === chunkId) { fail( `route ${routeId} (${routePath}, ${chunkId}) collides with installed route ${route.routeId} (${route.path}, ${route.chunkId})`, ); } } const messageKeys = [ `route.${routeId}.navigation`, `route.${routeId}.title`, `${names.camel}.list.title`, `${names.camel}.list.description`, `${names.camel}.list.resultCount`, `${names.camel}.list.items`, ]; const takenKeys = messageKeys.filter((key) => installed.messageKeys.includes(key)); if (takenKeys.length > 0) { fail(`message keys already exist: ${takenKeys.join(", ")}`); } const suffix = topicSuffix(); const topic = `qinv.${suffix}`; if (!TOPIC_SUFFIX.test(suffix)) fail(`invalid generated topic ${topic}`); if (installed.topics.includes(topic)) { fail(`generated topic ${topic} is already installed; run the command again`); } if (request.contractPackage) assertPackageIdentity(id, request.contractPackage); const navigationOrder = Math.max( 0, ...installed.routes.flatMap((route) => route.navigationOrder === null ? [] : [route.navigationOrder], ), ) + NAVIGATION_STEP; const appId = installed.appIds[0] ?? ""; const shape: Shape = Object.freeze({ names, contextId, routeId, routePath, chunkId, navigationOrder, topic, operationId: `${names.upper}_LIST_ITEMS`, apiPath: `/api/${names.base}-items`, owner: `feature-frontend-${id}`, contractPackage: request.contractPackage ?? null, }); const feature = `src/features/${id}`; const { base } = names; const files = new Map([ ...(existing ? [] : ([ [ `src/contexts/${contextId}/context-module.ts`, renderContextModule(contextId, appId, contextRoot), ], ] as const)), [`${feature}/feature-module.ts`, renderFeatureModule(shape)], [`${feature}/feature-runtime.ts`, renderFeatureRuntime(shape)], [`${feature}/context-routes.ts`, renderContextRoutes(shape)], [`${feature}/contracts/${base}-feature-contract.ts`, renderFeatureContract(shape)], [`${feature}/contracts/${base}-schemas.ts`, renderSchemas(shape)], [`${feature}/contracts/${base}-mapper.ts`, renderMapper(shape)], [`${feature}/contracts/${base}-api-contract.ts`, renderApiContract(shape)], [ `${feature}/contracts/${base}-contract-contribution.ts`, renderContractContribution(shape), ], [`${feature}/contracts/${base}-message-catalog.ts`, renderMessageCatalog(shape)], [`${feature}/application/${base}-feature-api.ts`, renderFeatureApi(shape)], [`${feature}/adapters/${base}-http-gateway.ts`, renderHttpGateway(shape)], [`${feature}/adapters/create-${base}-feature-input.ts`, renderCreateInput(shape)], [`${feature}/presentation/${base}-feature-runtime.ts`, renderRouteRuntime(shape)], [`${feature}/presentation/${base}-routes.ts`, renderRoutes(shape)], [`${feature}/presentation/use-${base}-items.ts`, renderUseItems(shape)], [`${feature}/presentation/${base}-list-page.tsx`, renderListPage(shape)], [`tests/features/${id}/${base}-feature-input.test.ts`, renderInputTest(shape)], [`tests/features/${id}/${base}-list-page.test.tsx`, renderPageTest(shape)], [`tests/features/${id}/${base}-http-gateway.test.ts`, renderGatewayTest(shape)], [`artifacts/tests/a11y-manual/${routeId}.md`, renderA11yRecord(routeId)], ]); return Object.freeze({ id, contextId, newContext: existing === undefined, routeId, routePath, topic, placeholder: request.contractPackage === undefined, files, }); } type Shape = Readonly<{ names: Names; contextId: string; routeId: string; routePath: string; chunkId: string; navigationOrder: number; topic: string; operationId: string; apiPath: string; owner: string; contractPackage: ContractPackageIdentity | null; }>; const GENERATED = "Generated by `pnpm create:feature`."; function renderContextModule(contextId: string, appId: string, root: string): string { return `/** * Ownership declaration of the ${contextId} bounded context * (docs/architecture/starter-experience.md, "Ownership declarations"): the * app that owns it, its route root and its direct-feature budget. * ${GENERATED} */ export const CONTEXT_MODULE_ID = "${contextId}"; export const CONTEXT_APP_ID = "${appId}"; export const CONTEXT_ROUTE_PATH = "${root}/*"; export const CONTEXT_MAX_FEATURES = ${NEW_CONTEXT_MAX_FEATURES}; `; } function renderFeatureModule({ names, contextId }: Shape): string { const { base, upper } = names; return `import { defineFeatureModule } from "../feature-module.ts"; import { ${upper}_FEATURE_CONTRACT, ${upper}_FEATURE_ID, } from "./contracts/${base}-feature-contract.ts"; import { ${upper}_MESSAGE_CATALOGS } from "./contracts/${base}-message-catalog.ts"; export const FEATURE_MODULE_ID = "${names.id}" satisfies typeof ${upper}_FEATURE_ID; /** Owning bounded context (route root and budget live in its declaration). */ export const FEATURE_CONTEXT_ID = "${contextId}"; /** * Declaration only: this file and what it imports statically are in the * initial chunk. The executable half, \`feature-runtime.ts\`, is imported * dynamically when a route of this feature is entered. ${GENERATED} */ export const FEATURE_MODULE = defineFeatureModule({ id: FEATURE_MODULE_ID, contracts: ${upper}_FEATURE_CONTRACT, routes: ${upper}_FEATURE_CONTRACT.routes, messages: ${upper}_MESSAGE_CATALOGS, loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME, } as const); `; } function renderFeatureRuntime({ names }: Shape): string { const { base, upper } = names; return `import { defineFeatureRuntime } from "../feature-module.ts"; import { ${upper}_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-${base}-feature-input.ts"; import { ${upper}_API_CONTRACT } from "./contracts/${base}-api-contract.ts"; import { ${upper}_CONTRACT_CONTRIBUTION } from "./contracts/${base}-contract-contribution.ts"; import { ${upper}_FEATURE_ID } from "./contracts/${base}-feature-contract.ts"; /** * The executable half. \`feature-module.ts\` imports this file dynamically, so * none of it is in the initial chunk. */ export const FEATURE_RUNTIME = defineFeatureRuntime({ featureId: ${upper}_FEATURE_ID, apiContract: ${upper}_API_CONTRACT, adapters: [${upper}_FEATURE_ADAPTER_CONTRIBUTION], contractContributions: [${upper}_CONTRACT_CONTRIBUTION], } as const); `; } function renderContextRoutes({ names }: Shape): string { const { base, upper } = names; return `import type { RouteObject } from "react-router-dom"; import { ${upper}_FEATURE_CONTRACT } from "./contracts/${base}-feature-contract.ts"; import { ${upper}_ROUTE_RUNTIME } from "./presentation/${base}-feature-runtime.ts"; /** * The routes the owning context loads when its root is visited. A route with * params or search also puts its codecs on the handle (\`codecs\`). */ export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze( Object.values(${upper}_FEATURE_CONTRACT.routes).map((definition) => Object.freeze({ id: definition.routeId, path: definition.path, handle: Object.freeze({ routeId: definition.routeId, runtime: ${upper}_ROUTE_RUNTIME[definition.routeId], }), }), ), ); `; } function renderContractPackage({ names, contractPackage }: Shape): Readonly<{ imports: string; doc: string; fields: string; }> { if (contractPackage === null) { return { imports: `import { PLACEHOLDER_CONTRACT_PACKAGE_DIGEST, PLACEHOLDER_CONTRACT_PACKAGE_REVISION, PLACEHOLDER_CONTRACT_PACKAGE_VERSION, } from "../../../contracts/deployment-admission.ts"; `, doc: ` * PLACEHOLDER: no package was given to create:feature. Local and development * builds work; release admission refuses this identity for staging and * production. Pin the published package's id, exact version, sha256 digest * and source revision here.`, fields: ` packageId: "@org-contracts/${names.base}", version: PLACEHOLDER_CONTRACT_PACKAGE_VERSION, digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST, runtimeProtocolVersion: 1 as const, sourceRevision: PLACEHOLDER_CONTRACT_PACKAGE_REVISION,`, }; } return { imports: "", doc: ` * Pinned when the feature was created; change all four fields together.`, fields: ` packageId: "${contractPackage.packageId}", version: "${contractPackage.version}", digest: "${contractPackage.digest}", runtimeProtocolVersion: 1 as const, sourceRevision: "${contractPackage.sourceRevision}",`, }; } function renderFeatureContract(shape: Shape): string { const { names, routeId } = shape; const { base, upper } = names; const contractPackage = renderContractPackage(shape); return `${contractPackage.imports}import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts"; import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts"; export const ${upper}_FEATURE_ID = "${names.id}"; export const ${upper}_ITEM_QUERY_NAMESPACE = defineQueryNamespaceIdentity( "${base}-item", 1, ); /** Random, not copied: a topic id is global and a copy collides. */ export const ${upper}_ITEM_INVALIDATION_TOPIC = defineQueryInvalidationTopic("${shape.topic}"); /** * The contract package this feature's API comes from. The release manifest is * checked against it at boot. ${contractPackage.doc} */ export const ${upper}_CONTRACT_PACKAGE = Object.freeze({ ${contractPackage.fields} }); /** * The declaration half: what the shell reads before a route of this feature * is entered. It is in the initial chunk, so it holds data only. Route, chunk, * schema, operation and topic ids are global; keep the feature prefix. */ export const ${upper}_FEATURE_CONTRACT = Object.freeze({ featureId: ${upper}_FEATURE_ID, routes: Object.freeze({ ${routeId}: Object.freeze({ routeId: "${routeId}", path: "${shape.routePath}", paramsSchema: null, searchSchema: null, access: "session-required", loadingSurface: "${base}-list", errorSurface: "feature-boundary", chunkId: "${shape.chunkId}", title: "${names.title}", navigationLabel: "${names.title}", navigationOrder: ${shape.navigationOrder}, }), }), routeRuntimeContracts: Object.freeze({ ${routeId}: Object.freeze({ routeId: "${routeId}", moduleId: "${base}-list-page", paramsCodec: "none", searchCodec: "none", }), }), invalidation: Object.freeze({ topics: Object.freeze([${upper}_ITEM_INVALIDATION_TOPIC]), namespaces: Object.freeze([${upper}_ITEM_QUERY_NAMESPACE]), edges: Object.freeze([ Object.freeze({ topicId: ${upper}_ITEM_INVALIDATION_TOPIC, namespace: ${upper}_ITEM_QUERY_NAMESPACE, }), ]), }), topicVersions: Object.freeze([ Object.freeze({ topicId: ${upper}_ITEM_INVALIDATION_TOPIC, topicVersion: 1 }), ]), contractPackages: Object.freeze([${upper}_CONTRACT_PACKAGE]), } as const); `; } function renderSchemas({ names }: Shape): string { const { camel, pascal, upper } = names; return `import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts"; import { z } from "../../../contracts/zod.ts"; import { zodValidator } from "../../../contracts/zod-validator.ts"; /** The GET takes no input. Schema ids are global, so this one is prefixed too. */ export const ${camel}NoRequestSchema = z.object({}).strict(); export const ${camel}ItemDtoSchema = z .object({ id: z.string().min(1).max(120), name: z.string().min(1).max(240), }) .strip(); export type ${pascal}ItemDto = z.output; export const ${camel}ItemListPayloadSchema = z.array(${camel}ItemDtoSchema).max(100); /** * The paired backend's Envelope \`error\` (clean-architecture-backend-template * docs/web/http-contract.md §1). Branch on \`code\`; the backend message is * never kept. */ export const ${camel}ProblemSchema = z .object({ code: z.string().regex(/^[A-Z0-9_]{1,64}$/u), category: z.string().min(1).max(64).optional(), retryable: z.boolean().optional(), details: z.unknown().optional(), }) .strip(); export type ${pascal}Problem = z.output; export const ${upper}_VALIDATORS = Object.freeze({ ${pascal}NoRequest: zodValidator("${pascal}NoRequest", ${camel}NoRequestSchema), ${pascal}ItemListPayload: zodValidator( "${pascal}ItemListPayload", ${camel}ItemListPayloadSchema, ), ${pascal}Problem: zodValidator("${pascal}Problem", ${camel}ProblemSchema), }); export const ${upper}_RUNTIME_SCHEMA_CODECS = Object.freeze({ ${pascal}NoRequest: runtimeSchemaCodecFromValidator(${upper}_VALIDATORS.${pascal}NoRequest), ${pascal}ItemListPayload: runtimeSchemaCodecFromValidator( ${upper}_VALIDATORS.${pascal}ItemListPayload, ), }); `; } function renderMapper({ names, owner }: Shape): string { const { base, camel, pascal, upper } = names; return `import { mappingFailure, mappingSuccess, type BoundaryMappingResult, type InstalledBoundaryMapper, } from "../../../contracts/boundary-mapper.ts"; import { ${camel}ItemListPayloadSchema, type ${pascal}ItemDto, } from "./${base}-schemas.ts"; /** What the page shows. A wire field never reaches presentation by its wire name. */ export type ${pascal}ItemView = Readonly<{ itemId: string; name: string }>; /** * The HTTP contract has already validated the wire shape (\`outputValidator\`), * so this owns only wire -> view. Put business rules in a \`domain/\` model * when the feature has some. */ export function map${pascal}ItemList( payload: readonly ${pascal}ItemDto[], ): BoundaryMappingResult { return mappingSuccess( Object.freeze( payload.map((dto) => Object.freeze({ itemId: dto.id, name: dto.name })), ), ); } /** The registry row (FE-REG-API). The registry is untyped, so it checks the shape. */ export const ${upper}_BOUNDARY_MAPPERS = Object.freeze({ ${pascal}ItemListMapper: Object.freeze({ mapperId: "${pascal}ItemListMapper", mapperVersion: 1, inputSchemaId: "${pascal}ItemListPayload", outputContractId: "${pascal}ItemList", owner: "${owner}", maxOutputItems: 100, map(value: unknown) { const parsed = ${camel}ItemListPayloadSchema.safeParse(value); return parsed.success ? map${pascal}ItemList(parsed.data) : mappingFailure("MAPPING_INVARIANT_REJECTED"); }, }), } satisfies Readonly>); `; } function renderApiContract({ names, operationId, apiPath, owner }: Shape): string { const { base, pascal, upper } = names; return `import { defineRestOperation } from "../../../contracts/api-operations.ts"; import { ${upper}_BOUNDARY_MAPPERS } from "./${base}-mapper.ts"; import { ${upper}_RUNTIME_SCHEMA_CODECS } from "./${base}-schemas.ts"; const OWNER = "${owner}"; /** * The V2 API contract \`check:registries\` governs (FE-REG-API). The executable * descriptor of the same operation is in \`${base}-contract-contribution.ts\`; * tests/unit/http-operation-v2-v3-parity.test.ts fails when they disagree. * Runtime half only: \`feature-runtime.ts\` loads it. */ export const ${upper}_API_CONTRACT = Object.freeze({ runtimeSchemas: ${upper}_RUNTIME_SCHEMA_CODECS, mappers: ${upper}_BOUNDARY_MAPPERS, schemas: Object.freeze({ ${pascal}NoRequest: Object.freeze({ schemaId: "${pascal}NoRequest", boundary: "api-request", owner: OWNER, runtime: "zod", schemaVersion: 1, direction: "REQUEST", unknownFieldPolicy: "REJECT_UNKNOWN", }), ${pascal}ItemListPayload: Object.freeze({ schemaId: "${pascal}ItemListPayload", boundary: "api-response", owner: OWNER, runtime: "zod", schemaVersion: 1, direction: "RESPONSE", unknownFieldPolicy: "STRIP_UNKNOWN", }), }), apiOperations: Object.freeze({ ${operationId}: defineRestOperation({ method: "GET", path: "${apiPath}", operationId: "${operationId}", auth: "external-session", timeoutMs: null, idempotency: "safe", retry: "runtime", requestSource: "none", requestSchema: "${pascal}NoRequest", responseSchema: "${pascal}ItemListPayload", owner: OWNER, contractVersion: 2, protocol: "REST", semantics: "QUERY", replayPolicy: "SAFE", idempotencyKeyPolicy: "NONE", mapperId: "${pascal}ItemListMapper", successStatuses: [200], responseMediaTypes: ["application/json"], maxResponseBytes: 262_144, providerId: "PRIMARY_API", authProfileId: "EXTERNAL_BEARER", csrfProfileId: "NO_CSRF_BEARER", pathSchema: "${pascal}NoRequest", pathParameterNames: [], maxEncodedSearchBytes: 0, }), }), } as const); `; } function renderContractContribution({ names, operationId, apiPath }: Shape): string { const { base, pascal, upper } = names; return `import type { InstalledContractContribution, InstalledHttpContract, } from "../../../contracts/external-contract-runtime.ts"; import { ${upper}_CONTRACT_PACKAGE, ${upper}_FEATURE_ID, } from "./${base}-feature-contract.ts"; import { ${upper}_VALIDATORS, type ${pascal}ItemDto, type ${pascal}Problem, } from "./${base}-schemas.ts"; /** * The executable (V3) descriptor of ${operationId}. It belongs to the contract * package pinned in \`${base}-feature-contract.ts\`: import \`@org-contracts/*\` * only in this file (external-contract-package-single-import-path) and take * the package's descriptor instead of this local one. */ export const ${operationId}_CONTRACT = Object.freeze({ contract: Object.freeze({ operationId: "${operationId}", method: "GET" as const, pathTemplate: "${apiPath}", inputValidator: ${upper}_VALIDATORS.${pascal}NoRequest, outputValidator: ${upper}_VALIDATORS.${pascal}ItemListPayload, problemValidator: ${upper}_VALIDATORS.${pascal}Problem, acceptedStatuses: Object.freeze([200]), emptyBodyStatuses: Object.freeze([]), retrySemantics: "SAFE" as const, requestBody: "NONE" as const, responseBody: "REQUIRED_JSON" as const, // The paired backend wraps every JSON body (http-contract.md §1). Drop // this line for a backend that sends the DTO and problem details bare. responseEnvelope: "ENVELOPE_V1" as const, commandRecovery: null, commandEffect: null, projectRequest() { return Object.freeze({ pathValues: Object.freeze({}), queryEntries: Object.freeze([]), body: null, }); }, }), frontend: Object.freeze({ policyId: "${upper}_LIST_V1", requestByteLimit: 0, responseByteLimit: 262_144, totalDeadlineMs: 10_000, retryBudget: 2 as const, authProfileId: "EXTERNAL_BEARER", diagnosticsOperation: "${base}.list", }), }) satisfies InstalledHttpContract< Readonly>, readonly ${pascal}ItemDto[], ${pascal}Problem >; export const ${upper}_CONTRACT_CONTRIBUTION: InstalledContractContribution = Object.freeze({ contributionId: "${names.id}-http-v1", featureId: ${upper}_FEATURE_ID, source: Object.freeze({ kind: "EXTERNAL_PACKAGE" as const, package: ${upper}_CONTRACT_PACKAGE, }), http: Object.freeze([ ${operationId}_CONTRACT, ]) as readonly InstalledHttpContract[], events: Object.freeze([]), }); `; } function renderMessageCatalog({ names, routeId }: Shape): string { const { camel, title, upper } = names; return `/** ko-KR is the source catalog; every locale has the same keys and placeholders. */ export const ${upper}_MESSAGE_CATALOGS = Object.freeze({ "ko-KR": Object.freeze({ "route.${routeId}.navigation": "${title}", "route.${routeId}.title": "${title}", "${camel}.list.title": "${title}", "${camel}.list.description": "create:feature가 만든 목록입니다. 제품 문구로 바꾸세요.", "${camel}.list.resultCount": "총 {count}개 항목", "${camel}.list.items": "${title} 목록", }), "en-US": Object.freeze({ "route.${routeId}.navigation": "${title}", "route.${routeId}.title": "${title}", "${camel}.list.title": "${title}", "${camel}.list.description": "A list create:feature generated. Replace this copy with the product's.", "${camel}.list.resultCount": "Total items: {count}", "${camel}.list.items": "${title} items", }), } as const); `; } function renderFeatureApi({ names }: Shape): string { const { base, pascal, upper } = names; return `import type {} from "../../../application/ports/in/application-api.ts"; import type { Result } from "../../../contracts/result.ts"; import { failOpenTelemetryPort, NO_OP_TELEMETRY_PORT, type TelemetryPort, } from "../../../platform/telemetry/telemetry-port.ts"; import { ${upper}_FEATURE_ID } from "../contracts/${base}-feature-contract.ts"; import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; export type ${pascal}CallContext = Readonly<{ signal?: AbortSignal }>; /** What the feature's pages call. Name methods after what the user does. */ export type ${pascal}FeatureInput = Readonly<{ listItems(context?: ${pascal}CallContext): Promise>; }>; declare module "../../../application/ports/in/application-api.ts" { interface ApplicationFeatureInputs { "${names.id}": ${pascal}FeatureInput; } } /** The port the feature's HTTP adapter implements. */ export type ${pascal}Gateway = Readonly<{ list(context?: ${pascal}CallContext): Promise>; }>; export function create${pascal}FeatureInput( gateway: ${pascal}Gateway, { telemetry = NO_OP_TELEMETRY_PORT }: Readonly<{ telemetry?: TelemetryPort }> = {}, ): ${pascal}FeatureInput { // scale-architecture.md §24, §26: telemetry is best-effort and never changes the result. const events = failOpenTelemetryPort(telemetry); return Object.freeze({ async listItems(context) { const result = await gateway.list(context); if (!result.ok && result.error.kind !== "REQUEST_ABORTED") { void events.emit({ kind: "${base}.list.failed", severity: "warning", featureId: ${upper}_FEATURE_ID, payload: Object.freeze({ reason: result.error.kind }), }); } return result; }, }); } `; } function renderHttpGateway({ names, operationId, routeId }: Shape): string { const { base, pascal, upper } = names; return `import { defineFeatureHttpOperationForRoutes, type FeatureHttpBinding, } from "../../../adapters/http/index.ts"; import type { ${pascal}Gateway } from "../application/${base}-feature-api.ts"; import { ${operationId}_CONTRACT } from "../contracts/${base}-contract-contribution.ts"; import type { ${upper}_FEATURE_CONTRACT } from "../contracts/${base}-feature-contract.ts"; import { map${pascal}ItemList } from "../contracts/${base}-mapper.ts"; const define${pascal}HttpOperation = defineFeatureHttpOperationForRoutes< keyof typeof ${upper}_FEATURE_CONTRACT.routes >(); export const ${upper}_HTTP_OPERATIONS = Object.freeze({ ${operationId}: define${pascal}HttpOperation({ contract: ${operationId}_CONTRACT, routeId: "${routeId}", mapSuccess: map${pascal}ItemList, }), } as const); export function create${pascal}HttpGateway( http: FeatureHttpBinding, ): ${pascal}Gateway { return Object.freeze({ list(context) { return http.execute("${operationId}", Object.freeze({}), context); }, }); } `; } function renderCreateInput({ names }: Shape): string { const { base, pascal, upper } = names; return `import { createFeatureHttpBinding } from "../../../adapters/http/index.ts"; import { defineFeatureAdapterContribution } from "../../feature-adapter-contribution.ts"; import { create${pascal}FeatureInput } from "../application/${base}-feature-api.ts"; import { ${upper}_FEATURE_ID } from "../contracts/${base}-feature-contract.ts"; import { create${pascal}HttpGateway, ${upper}_HTTP_OPERATIONS, } from "./${base}-http-gateway.ts"; /** The feature receives only the capabilities it names in \`needs\`. */ export const ${upper}_FEATURE_ADAPTER_CONTRIBUTION = defineFeatureAdapterContribution({ featureId: ${upper}_FEATURE_ID, needs: ["http", "telemetry"] as const, createInput: ({ http, telemetry }) => Object.freeze({ featureId: ${upper}_FEATURE_ID, input: create${pascal}FeatureInput( create${pascal}HttpGateway(createFeatureHttpBinding(http, ${upper}_HTTP_OPERATIONS)), { telemetry }, ), }), }); `; } function renderRouteRuntime({ names, routeId }: Shape): string { const { base, upper } = names; return `import { lazy } from "react"; /** The lazy page of each route; \`moduleId\` equals the route runtime contract's. */ export const ${upper}_ROUTE_RUNTIME = { ${routeId}: Object.freeze({ moduleId: "${base}-list-page", Component: lazy(() => import("./${base}-list-page.tsx")), }), } as const; `; } function renderRoutes({ names }: Shape): string { const { base, camel, upper } = names; return `import { buildRouteUrl } from "../../../presentation/routes/route-codecs.ts"; import type { ${upper}_FEATURE_CONTRACT } from "../contracts/${base}-feature-contract.ts"; /** * 16-04. A link names its route ID and the router's builder fills in the * contract's \`path\`, so the contract stays the one place a path is written. * Once a route has params or search, pass its codecs as the third argument. */ export function ${camel}RouteUrl( routeId: keyof typeof ${upper}_FEATURE_CONTRACT.routes, input?: Parameters[1], ): string { return buildRouteUrl(routeId, input); } `; } function renderUseItems({ names, operationId }: Shape): string { const { base, pascal, upper } = names; return `import { bindQuery, type QueryResultMeasure } from "../../../contracts/server-state.ts"; import { useApplicationQuery } from "../../../presentation/adapters/query/application-query.ts"; import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx"; import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx"; import { ${upper}_FEATURE_ID, ${upper}_ITEM_QUERY_NAMESPACE, } from "../contracts/${base}-feature-contract.ts"; import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; const UTF8 = new TextEncoder(); const NO_INPUT = Object.freeze({}); /** * §10.4. Bounded estimate of the mapped value: string bytes plus a fixed * per-item overhead, never \`JSON.stringify\`. */ function measureItems(items: readonly ${pascal}ItemView[]): QueryResultMeasure { let estimatedBytes = 16; for (const item of items) { estimatedBytes += UTF8.encode(item.itemId).byteLength + UTF8.encode(item.name).byteLength + 16; } return { itemCount: items.length, estimatedBytes }; } export function use${pascal}Items() { const input = useApplicationFeature(${upper}_FEATURE_ID); const scope = useServerStateScope(); return useApplicationQuery( bindQuery( { definitionId: "${base}-item-list-v1", definitionVersion: 1, owner: ${upper}_FEATURE_ID, namespace: ${upper}_ITEM_QUERY_NAMESPACE, operationId: "${operationId}", profileId: "LIST_STANDARD", measureResult: measureItems, execute: (_input: typeof NO_INPUT, { signal }) => input.listItems({ signal }), }, NO_INPUT, scope, ), ); } `; } function renderListPage({ names }: Shape): string { const { base, camel, pascal } = names; return `import { AsyncSurface, CollectionPage, } from "../../../presentation/design-system/index.ts"; import { useLocale } from "../../../presentation/i18n/index.ts"; import { use${pascal}Items } from "./use-${base}-items.ts"; /** An empty list renders the shared empty state under the page heading. */ export default function ${pascal}ListPage() { const { message } = useLocale(); const query = use${pascal}Items(); return (
    {(query.data ?? []).map((item) => (
  • {item.name}
  • ))}
); } `; } function renderInputTest({ names, operationId }: Shape): string { const { base, pascal, upper } = names; return `import { describe, expect, it, vi } from "vitest"; import { createFailure } from "../../../src/contracts/errors.ts"; import { create${pascal}FeatureInput } from "../../../src/features/${names.id}/application/${base}-feature-api.ts"; import { ${upper}_BOUNDARY_MAPPERS } from "../../../src/features/${names.id}/contracts/${base}-mapper.ts"; import type { TelemetryPort } from "../../../src/platform/telemetry/telemetry-port.ts"; const ITEMS = Object.freeze([Object.freeze({ itemId: "item-1", name: "First item" })]); describe("${names.id} application input", () => { it("returns the gateway's items without telemetry", async () => { const emit = vi.fn(); const input = create${pascal}FeatureInput( { list: async () => ({ ok: true, value: ITEMS }) }, { telemetry: { emit } }, ); await expect(input.listItems()).resolves.toEqual({ ok: true, value: ITEMS }); expect(emit).not.toHaveBeenCalled(); }); it("returns a failed load and reports its kind", async () => { const failure = createFailure("REQUEST_TIMEOUT", "${operationId}", 0); const emit = vi.fn(); const input = create${pascal}FeatureInput( { list: async () => ({ ok: false, error: failure }) }, { telemetry: { emit } }, ); await expect(input.listItems()).resolves.toEqual({ ok: false, error: failure }); expect(emit).toHaveBeenCalledWith({ kind: "${base}.list.failed", severity: "warning", featureId: "${names.id}", payload: { reason: "REQUEST_TIMEOUT" }, }); }); it("does not report a load its caller aborted", async () => { const failure = createFailure("REQUEST_ABORTED", "${operationId}", 0); const input = create${pascal}FeatureInput({ list: async () => ({ ok: false, error: failure }), }); await expect(input.listItems()).resolves.toEqual({ ok: false, error: failure }); }); }); describe("${names.id} registry mapper", () => { it("maps a list payload and rejects any other shape", () => { const { map } = ${upper}_BOUNDARY_MAPPERS.${pascal}ItemListMapper; expect(map([{ id: "item-1", name: "First item" }])).toEqual({ ok: true, value: ITEMS }); expect(map({ items: [] })).toEqual({ ok: false, code: "MAPPING_INVARIANT_REJECTED" }); }); }); `; } function renderPageTest({ names, operationId, routeId }: Shape): string { const { base, camel, upper } = names; return `// @vitest-environment jsdom import { render, screen } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { setupServer } from "msw/node"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts"; import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx"; import { ${operationId}_CONTRACT } from "../../../src/features/${names.id}/contracts/${base}-contract-contribution.ts"; import { ${upper}_MESSAGE_CATALOGS } from "../../../src/features/${names.id}/contracts/${base}-message-catalog.ts"; import { ${camel}RouteUrl } from "../../../src/features/${names.id}/presentation/${base}-routes.ts"; import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts"; import { createHttpScenarioHandler } from "../../mocks/handlers/http-scenarios.ts"; const MESSAGES = ${upper}_MESSAGE_CATALOGS["ko-KR"]; const RUNTIME_CONFIG = { APP_ENV: "local", API_BASE_URL: "https://api.test", REQUEST_TIMEOUT_MS: 10_000, MAX_RETRY_ATTEMPTS: 0, TELEMETRY_ENABLED: false, AUTH_MODE: "demo", CONFIG_SCHEMA_VERSION: "1", API_CONTRACT_VERSION: "1", RELEASE_MANIFEST_URL: "/release-manifest.json", BUILD_ID: "local-build", RELEASE_ID: "local-release", }; const RELEASE_MANIFEST = { schemaVersion: 1, appVersion: "0.0.0", buildId: "local-build", commitSha: "local", configSchemaVersion: "1", apiContractVersion: "1", assetManifestHash: "test-hash", releaseId: "local-release", builtAt: "2026-01-01T00:00:00.000Z", routeChunks: { "route-home": "assets/home.js" }, }; /** The boot documents come from here; every API call goes to MSW. */ const fetcher: typeof fetch = (input, init) => { const url = new URL(input instanceof Request ? input.url : String(input), "http://app.test"); if (url.pathname === "/config.json") return Promise.resolve(Response.json(RUNTIME_CONFIG)); if (url.pathname === "/release-manifest.json") { return Promise.resolve(Response.json(RELEASE_MANIFEST)); } return fetch(input instanceof Request ? input : url, init); }; const api = setupServer(); beforeAll(() => api.listen({ onUnhandledRequest: "error" })); afterEach(() => api.resetHandlers()); afterAll(() => api.close()); /** Enters the list through the router, as a signed-in user. */ async function openList() { const user = userEvent.setup(); window.history.pushState({}, "", ${camel}RouteUrl("${routeId}")); render( , ); await user.click(await screen.findByRole("button", { name: KO_MESSAGES["action.signIn"] })); expect( await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }), ).toBeVisible(); return user; } describe("${names.id} list page through the router", () => { it("lists the items the API returns", async () => { api.use( createHttpScenarioHandler(${operationId}_CONTRACT, { payload: [{ id: "item-1", name: "First item" }], }), ); await openList(); expect(await screen.findByText("First item")).toBeVisible(); }); // The backend answers an empty list as \`data: []\`, never by dropping \`data\`. it("renders an empty list as the empty state", async () => { api.use(createHttpScenarioHandler(${operationId}_CONTRACT, { scenario: "empty", payload: [] })); await openList(); expect(await screen.findByRole("heading", { name: KO_MESSAGES["async.empty"] })).toBeVisible(); }); it("shows a failed load and loads again on retry", async () => { api.use( createHttpScenarioHandler(${operationId}_CONTRACT, { scenario: "server-terminal-503", payload: [], }), ); const user = await openList(); const retry = await screen.findByRole("button", { name: KO_MESSAGES["action.retry"] }); api.use( createHttpScenarioHandler(${operationId}_CONTRACT, { payload: [{ id: "item-2", name: "Second item" }], }), ); await user.click(retry); expect(await screen.findByText("Second item")).toBeVisible(); }); }); `; } function renderGatewayTest({ names, apiPath }: Shape): string { const { base, pascal, upper } = names; return `import { http, HttpResponse, type JsonBodyType } from "msw"; import { setupServer } from "msw/node"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { createContractHttpExecutor, createFeatureHttpBinding, type InstalledHttpOperationExecutor, } from "../../../src/adapters/http/index.ts"; import { create${pascal}HttpGateway, ${upper}_HTTP_OPERATIONS, } from "../../../src/features/${names.id}/adapters/${base}-http-gateway.ts"; /** * The paired backend's wire (clean-architecture-backend-template * docs/web/http-contract.md §1): every JSON body is an Envelope, and a null * field is dropped with its key. The bodies are written out here rather than * taken from the shared scenarios, so this fails if the contract stops * reading that wire. */ const API = "https://api.test"; const META = { requestId: "req-1", traceId: "0af7651916cd43dd8448eb211c80319c" }; const api = setupServer(); beforeAll(() => api.listen({ onUnhandledRequest: "error" })); afterEach(() => api.resetHandlers()); afterAll(() => api.close()); function answer(status: number, body: JsonBodyType) { api.use(http.get(\`\${API}${apiPath}\`, () => HttpResponse.json(body, { status }))); } function failure(code: string, details?: JsonBodyType) { return { success: false, error: { code, category: "VALIDATION", message: "backend message", retryable: false, ...(details === undefined ? {} : { details }), }, meta: META, }; } function gateway() { const executor = createContractHttpExecutor({ baseUrl: API, maxRetryAttempts: 0, attachCredentials: () => ({ kind: "READY" as const, headers: { authorization: "Bearer test-token" }, }), }); const installed: InstalledHttpOperationExecutor = Object.freeze({ execute: (contract, input, context) => executor.execute(contract, input, { routeId: context.routeId, scope: Object.freeze({ generation: 1, fingerprint: "${names.id}-test-scope", identities: Object.freeze({}) as never, signal: new AbortController().signal, isCurrent: () => true, }), }), }); return create${pascal}HttpGateway(createFeatureHttpBinding(installed, ${upper}_HTTP_OPERATIONS)); } describe("${names.id} HTTP gateway on the paired backend's Envelope", () => { it("reads the success Envelope's data", async () => { answer(200, { success: true, data: [{ id: "item-1", name: "First item" }], meta: META }); await expect(gateway().list()).resolves.toEqual({ ok: true, value: [{ itemId: "item-1", name: "First item" }], }); }); it("reads an Envelope whose null keys the backend dropped", async () => { // No id keys: the answer was written before the request id filter. answer(200, { success: true, data: [], meta: {} }); await expect(gateway().list()).resolves.toEqual({ ok: true, value: [] }); }); it("reads the failure Envelope's code and drops its message", async () => { answer(404, failure("NOT_FOUND")); const result = await gateway().list(); expect(result).toMatchObject({ ok: false, error: { kind: "NOT_FOUND", code: "NOT_FOUND", httpStatus: 404 }, }); expect(JSON.stringify(result)).not.toContain("backend message"); }); it("reads a parameter validation failure's field list", async () => { answer( 400, failure("VALIDATION_FAILED", [{ field: "size", code: "MAX", message: "too large" }]), ); await expect(gateway().list()).resolves.toMatchObject({ ok: false, error: { kind: "VALIDATION_REJECTED", code: "VALIDATION_FAILED", validationIssues: [{ path: "size", code: "MAX" }], }, }); }); it("refuses a bare DTO", async () => { answer(200, [{ id: "item-1", name: "First item" }]); await expect(gateway().list()).resolves.toMatchObject({ ok: false, error: { kind: "ENVELOPE_MISMATCH" }, }); }); }); `; } function renderA11yRecord(routeId: string): string { return `# ${routeId} accessibility review Status: pending-manual-review Route ID: ${routeId} Release ID: Reviewer: Reviewed at: Signature: Attestation: pending M1 Keyboard: pending M2 Visible focus: pending M3 Route focus: pending M4 Modal focus: pending M5 Error association: pending M6 Color signal: pending M7 Reduced motion: pending Screen reader: pending Notes: Human review pending. ${GENERATED} `; } async function exists(target: string): Promise { return access(target).then( () => true, () => false, ); } /** * Writes every file or none. An existing file or feature directory is never * overwritten; a write that fails removes what this call created. */ export async function writeFeatureFiles( root: string, files: ReadonlyMap, ownedDirectories: readonly string[] = [], ): Promise { const taken: string[] = []; for (const relative of [...ownedDirectories, ...files.keys()]) { if (await exists(path.join(root, relative))) taken.push(relative); } if (taken.length > 0) { throw new CreateFeatureError(`refusing to overwrite: ${taken.join(", ")}`); } const created: string[] = []; try { for (const [relative, content] of files) { const target = path.join(root, relative); const firstDirectory = await mkdir(path.dirname(target), { recursive: true }); if (firstDirectory !== undefined) created.push(firstDirectory); await writeFile(target, content, { flag: "wx" }); created.push(target); } } catch (error) { await rollBack(created); throw error; } return Object.freeze(created); } async function rollBack(created: readonly string[]): Promise { for (const target of [...created].reverse()) { await rm(target, { recursive: true, force: true }); } } async function directoryNames(directory: string): Promise { const entries = await readdir(directory, { withFileTypes: true }).catch(() => []); return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name); } async function readInstalledFacts(root: string): Promise { const source = await createFileSystemDeclarationSource(root); const contexts = source.appIds().flatMap((appId) => source.contextsOf(appId)); // The script's generator run (package.json) made these current. const { ROUTE_REGISTRY, INVALIDATION_REGISTRY } = await import( "../src/features/installed-feature-contracts.ts" ); const { KO_MESSAGES } = await import("../src/presentation/i18n/catalog.ts"); return Object.freeze({ appIds: source.appIds(), featureIds: [ ...new Set([ ...contexts.flatMap((context) => source.featuresOf(context.id).map((feature) => feature.id), ), ...(await directoryNames(path.join(root, "src/features"))), ]), ], contexts: contexts.map(({ id, routePath }) => ({ id, routePath })), contextDirectories: await directoryNames(path.join(root, "src/contexts")), routes: Object.values(ROUTE_REGISTRY).map((route) => ({ routeId: route.routeId, path: route.path, chunkId: route.chunkId, navigationOrder: route.navigationOrder, })), topics: [...INVALIDATION_REGISTRY.topics], messageKeys: Object.keys(KO_MESSAGES), }); } const USAGE = "Usage: pnpm create:feature [--context ] " + "[--package @scope/name@x.y.z --digest sha256:<64 hex> --revision ]"; function parseRequest(argv: readonly string[]): FeatureRequest { const args = argv[0] === "--" ? argv.slice(1) : [...argv]; const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { context: { type: "string" }, package: { type: "string" }, digest: { type: "string" }, revision: { type: "string" }, }, }); const [id, ...extra] = positionals; if (id === undefined || extra.length > 0) fail(USAGE); const given = [values.package, values.digest, values.revision].filter( (value) => value !== undefined, ); if (given.length !== 0 && given.length !== 3) { fail(`--package, --digest and --revision go together. ${USAGE}`); } let contractPackage: ContractPackageIdentity | undefined; if (values.package !== undefined) { const at = values.package.lastIndexOf("@"); if (at <= 0) fail(`--package must be @scope/name@. ${USAGE}`); contractPackage = Object.freeze({ packageId: values.package.slice(0, at), version: values.package.slice(at + 1), digest: values.digest ?? "", sourceRevision: values.revision ?? "", }); } return Object.freeze({ id, context: values.context, contractPackage }); } function report(plan: FeaturePlan): string { const lines = [ `create:feature: ${plan.id} in ${plan.contextId}${plan.newContext ? " (new context)" : ""}, route ${plan.routeId} at ${plan.routePath}`, ...[...plan.files.keys()].map((file) => ` created ${file}`), "", "Next:", ` 1. Before a release, have a person review and sign artifacts/tests/a11y-manual/${plan.routeId}.md (FE-GATE-028). The merge gates check only its format.`, " 2. Run the merge gates: corepack pnpm check:types, lint, check:architecture, check:registries, check:i18n, check:design-system, check:diagnostics, verify:documentation, test:unit, test:component, test:integration, test:coverage, check:ci, build.", ` The feature's own tests: node scripts/run-vitest.ts run tests/features/${plan.id} (test:coverage runs them in CI)`, " The registry baseline does not change: new routes, operations, schemas and invalidation topics are additive.", ]; return `${lines.join("\n")}\n`; } async function main(): Promise { const scriptDirectory = path.dirname(fileURLToPath(import.meta.url)); const root = path.resolve(scriptDirectory, ".."); let request: FeatureRequest; try { request = parseRequest(process.argv.slice(2)); } catch (error) { process.stderr.write(`create:feature: ${error instanceof Error ? error.message : String(error)}\n`); process.exitCode = 2; return; } try { const plan = planFeature(request, await readInstalledFacts(root)); const created = await writeFeatureFiles(root, plan.files, [ `src/features/${plan.id}`, `tests/features/${plan.id}`, ]); // The generator reads the new declarations; it fails on any it rejects. const generated = spawnSync( process.execPath, [path.join(scriptDirectory, "generate-product-feature-index.ts")], { cwd: root, encoding: "utf8" }, ); if (generated.status !== 0) { await rollBack(created); fail(`the feature index generator rejected the feature, nothing was kept:\n${generated.stderr}`); } process.stdout.write(report(plan)); if (plan.placeholder) { process.stderr.write( `create:feature warning: no --package was given, so src/features/${plan.id}/contracts/${namesOf(plan.id).base}-feature-contract.ts pins the placeholder contract identity. ` + "Local and development builds work; release admission refuses it for staging and production. " + "Pin the published package's id, version, digest and revision there, and take the package's descriptor in the contract contribution.\n", ); } } catch (error) { process.stderr.write(`create:feature: ${error instanceof Error ? error.message : String(error)}\n`); process.exitCode = 1; } } if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { await main(); }