문제 create:feature는 "모든 merge 게이트를 통과하는 가장 작은 기능"을 만든다고 적고, test:feature-scaffold(FE-GATE-020)가 그 주장을 지키는 유일한 드릴이다. 그런데 드릴은 손으로 적은 15개 명령만 돌았고 merge 단계는 명령 참조가 88개다. 그 범위 밖(시각 회귀, a11y, 번들, 계약·스키마·시나리오 테스트 등)에서 생성 기능을 깨는 템플릿 변경이 생겨도 FE-GATE-020은 통과했다(12-01·12-03이 실제로 그렇게 생겼다). 또 제품 기능 제거 드릴 (test:sample-removal -- --feature=<id>)은 어떤 게이트도 돌지 않아, 빈 사유 결함(16-02)이 드러나지 않았다. 고른 방법 - 새 scripts/lib/feature-scaffold-drill.ts가 fixture의 config/ci/gates.json merge 단계를 단계 순서대로, 명령마다 한 번 뽑는다. 음성 fixture 명령은 run-ci-gate.ts처럼 등록된 종료 코드와 진단 ID로 판정한다. - 돌지 않는 명령은 SCAFFOLD_DRILL_EXCLUDED_SCRIPTS에 이유와 함께 둔다: 브라우저 명령 7개(FE-GATE-020 job에 브라우저가 없다. merge_gate matrix browser: false), test:system(bubblewrap·systemd·cgroup 필요, 기능과 무관한 provider 샌드박스 검사), verify:lockfile(연결한 node_modules에 install한다), 제거 드릴 5개(저장소를 다시 복사한다. 이 드릴 자신 포함). merge 단계에 없는 스크립트를 제외 목록에 두면 실패한다. - 생성 기능을 merge 명령 뒤에 test:sample-removal -- --feature=scaffold-feature로 다시 지운다(16-02 둘째 절반). - 생성 명령의 주석·Next 출력과 매뉴얼 두 곳의 주장을 실제 범위로 고쳤다. - 버린 대안: 손 목록에 빠진 명령 더하기. 다음 merge 명령이 다시 빠진다. 복사본 에서 브라우저 게이트까지 전부(리뷰 5.1 (d)). 드릴 job에 브라우저가 없고 수십 분이 든다. 생성 경로만 도는 chromium a11y·시각 1회(5.1 (c)). 12-01·12-03을 고치는 다른 작업이 진행 중이라 지금 넣으면 그 수정 전까지 드릴이 실패한다. 그 둘이 들어오면 제외 목록에서 빼는 것을 다시 본다. 위험·한계 - 드릴 시간이 크게 는다(빌드·release candidate·coverage·제거 드릴 한 번). FE-GATE-020 job(45분)의 임계 경로를 넘으면 리뷰 5.1 재검토 조건대로 줄인다. tests/unit이 한 merge에서 도는 횟수(1101/10-06)도 는다. - 이 커밋 메시지에는 드릴 전체 실행 결과를 적지 않았다(공유 잠금 대기). 검증 - RED: 새 tests/unit/feature-scaffold-drill.test.ts의 "is what test:feature-scaffold runs"가 수정 전 실패. - 수정 뒤 feature-scaffold-drill 5건(merge 명령 전부가 실행 또는 제외, 음성 fixture 기대 유지, merge 단계에 명령을 더하면 드릴이 돈다, 낡은 제외 거부, 드릴이 이 목록을 씀), create-feature, removal-fixture 합계 43건 통과. verify:documentation PASS_SCOPED, check:types 통과, eslint 통과. Refs: docs/reviews/2026-11-03-maturity-review/12-guardrails-ci.md 12-02 Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-02
1472 lines
51 KiB
TypeScript
1472 lines
51 KiB
TypeScript
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 <id>` writes the smallest feature meant to pass
|
|
* every merge gate. test:feature-scaffold runs the merge stage on it except the
|
|
* commands SCAFFOLD_DRILL_EXCLUDED_SCRIPTS names (browser gates, test:system;
|
|
* scripts/lib/feature-scaffold-drill.ts). The feature has 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<string, string>;
|
|
}>;
|
|
|
|
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<typeof namesOf>;
|
|
|
|
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 <an existing 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<string, string>([
|
|
...(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}-schema-metadata.ts`, renderSchemaMetadata(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}_CONTRACT_CONTRIBUTION } from "./contracts/${base}-contract-contribution.ts";
|
|
import { ${upper}_FEATURE_ID } from "./contracts/${base}-feature-contract.ts";
|
|
import { ${upper}_SCHEMA_METADATA } from "./contracts/${base}-schema-metadata.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,
|
|
schemas: ${upper}_SCHEMA_METADATA,
|
|
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 { 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<typeof ${camel}ItemDtoSchema>;
|
|
|
|
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<typeof ${camel}ProblemSchema>;
|
|
|
|
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),
|
|
});
|
|
`;
|
|
}
|
|
|
|
function renderMapper({ names }: Shape): string {
|
|
const { base, pascal } = names;
|
|
return `import {
|
|
mappingSuccess,
|
|
type BoundaryMappingResult,
|
|
} from "../../../contracts/boundary-mapper.ts";
|
|
import 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<readonly ${pascal}ItemView[]> {
|
|
return mappingSuccess(
|
|
Object.freeze(
|
|
payload.map((dto) => Object.freeze({ itemId: dto.id, name: dto.name })),
|
|
),
|
|
);
|
|
}
|
|
`;
|
|
}
|
|
|
|
function renderSchemaMetadata({ names, owner }: Shape): string {
|
|
const { pascal, upper } = names;
|
|
return `const OWNER = "${owner}";
|
|
|
|
/**
|
|
* FE-REG-SCHEMA rows of the feature's schemas (\`check:registries\`). The HTTP
|
|
* operation is written once, in \`${names.base}-contract-contribution.ts\`;
|
|
* FE-REG-API rows are projected from it. Runtime half only:
|
|
* \`feature-runtime.ts\` loads it.
|
|
*/
|
|
export const ${upper}_SCHEMA_METADATA = 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",
|
|
}),
|
|
} 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 HTTP descriptor of ${operationId}, the one place the operation is
|
|
* written: it executes, and FE-REG-API reads it. 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<Record<never, never>>,
|
|
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<unknown, unknown, unknown>[],
|
|
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<Result<readonly ${pascal}ItemView[]>>;
|
|
}>;
|
|
|
|
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<Result<readonly ${pascal}ItemView[]>>;
|
|
}>;
|
|
|
|
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<typeof ${upper}_HTTP_OPERATIONS>,
|
|
): ${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<typeof buildRouteUrl>[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 (
|
|
<CollectionPage
|
|
heading={{
|
|
title: message("${camel}.list.title"),
|
|
description: message("${camel}.list.description"),
|
|
}}
|
|
resultCount={
|
|
query.state.base === "success" || query.state.base === "empty"
|
|
? message("${camel}.list.resultCount", { count: query.data?.length ?? 0 })
|
|
: null
|
|
}
|
|
>
|
|
<AsyncSurface state={query.state} onRetry={query.retry}>
|
|
<ul aria-label={message("${camel}.list.items")}>
|
|
{(query.data ?? []).map((item) => (
|
|
<li key={item.itemId}>{item.name}</li>
|
|
))}
|
|
</ul>
|
|
</AsyncSurface>
|
|
</CollectionPage>
|
|
);
|
|
}
|
|
`;
|
|
}
|
|
|
|
function renderInputTest({ names, operationId }: Shape): string {
|
|
const { base, pascal } = 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 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<TelemetryPort["emit"]>();
|
|
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<TelemetryPort["emit"]>();
|
|
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 });
|
|
});
|
|
});
|
|
`;
|
|
}
|
|
|
|
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(
|
|
<RuntimeApplication
|
|
composition={await createRuntimeComposition({ fetcher, host: {} })}
|
|
/>,
|
|
);
|
|
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<boolean> {
|
|
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<string, string>,
|
|
ownedDirectories: readonly string[] = [],
|
|
): Promise<readonly string[]> {
|
|
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<void> {
|
|
for (const target of [...created].reverse()) {
|
|
await rm(target, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
async function directoryNames(directory: string): Promise<string[]> {
|
|
const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
}
|
|
|
|
async function readInstalledFacts(root: string): Promise<InstalledFacts> {
|
|
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 <id> [--context <context id>] " +
|
|
"[--package @scope/name@x.y.z --digest sha256:<64 hex> --revision <hex>]";
|
|
|
|
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@<exact version>. ${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 ci:gate -- FE-GATE-<NNN> for each gate of the merge stage in config/ci/gates.json (README lists the loop). test:feature-scaffold runs them on a generated feature except the browser gates FE-GATE-008/009 and test:system.",
|
|
` 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<void> {
|
|
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();
|
|
}
|