문제
- 새 기능은 참조 기능을 복사해 이름을 바꾸는 방법뿐이다. 리뷰 16 실험 E
에서 이 방법은 12번 막혔다. 접두어 없는 전역 ID(NoRequest, qinv topic,
navigationOrder)는 치환으로 바뀌지 않고, 토큰 경계 없는 치환은
preference·supportReference를 깨뜨린다. 제품이 참조 기능을 지우면 복사할
원본도 없다.
고른 방법 (결정 D1·D2, 오케스트레이터 결정 2·4)
- scripts/create-feature.ts: pnpm create:feature <id> [--context <ctx>]
[--package @scope/name@x.y.z --digest sha256:… --revision <hex>].
템플릿을 이 파일 안에 두고 참조 기능을 import하지 않는다(D1).
- 뼈대: 파라미터 없는 목록 라우트 1, GET 1(SAFE, EXTERNAL_BEARER),
쿼리 1, topic 1, CollectionPage 1, ko-KR·en-US 문구. domain/ 없음.
검증은 공유 zodValidator, 링크는 route ID와 buildRouteUrl
(<base>-routes.ts). 빈 배열 응답은 공유 빈 상태로 그린다.
- 전역 ID는 모두 기능 접두어를 단다(D2): 스키마·mapper·operation·
contribution·policy·diagnostics·chunk·route·namespace·definitionId·
문구 키·telemetry kind·owner. topic은 qinv. + 무작위 26자(Crockford
base32)이고 설치된 topic과 겹치면 거부한다. navigationOrder는 설치된
최댓값 + 10.
- 패키지 인자가 없으면 결정 2의 자리표시자 상수를 import해 쓰고 경고를
출력한다. 인자가 있으면 external-contract-runtime의 신원 검사
(composeContractContributions)로 형식을 확인한다.
- 거부: kebab이 아닌 id, 기존 기능·context id(디렉터리 이름 포함),
같은 접두어를 쓰는 기존 기능, 이미 있는 <base>-context(--context 안내),
같은 라우트 루트·route ID·경로·chunk·문구 키.
- 폴더 밖은 새 context 선언과 pending a11y 기록만 쓴다. 기존 파일은
덮어쓰지 않고(wx), 쓰기나 직후 생성기 실행이 실패하면 만든 것을 지운다.
- 출력: 만든 파일, a11y 서명(FE-GATE-028), 돌릴 게이트 목록, 기준선
재승인이 필요 없다는 안내, 자리표시자 교체 방법.
- 테스트: tests/unit/create-feature.test.ts(렌더 결과만: 접두어, 샘플
토큰 없음, topic 형식·중복, 순서, 거부, 덮어쓰기·되돌리기).
생성된 기능의 테스트는 input 단위 테스트와 런타임 조립·라우터를 거치는
페이지 테스트다. MSW는 createHttpScenarioHandler(설치 계약)를 쓴다.
- 느린 드릴 test:feature-scaffold: removal-fixture로 만든 복사본(README·
CHANGELOG·docs 포함)에 기능을 만들고 커밋한 뒤 types, lint,
architecture, registries, i18n, design-system, diagnostics,
documentation, unit, component, integration, features, coverage,
check:ci, build를 돌린다. FE-GATE-020에 넣고 gates.json, 계약 기준선,
ci-workflow-generation 테스트의 개수를 맞췄다(workflow는 그대로).
- 결정 4: test:sample-removal이 기능 0개 검사 뒤 같은 복사본에서
create:feature로 기능을 만들고 같은 게이트를 scaffold- 이름으로 다시
돌린다.
- tests/release 고정 manifest가 계약 집합을 빈 배열로 고정해, EXTERNAL_
PACKAGE를 쓰는 첫 기능에서 7건이 release-mismatch로 깨졌다. 16-02가
tests/runtime-schema에 한 것처럼 설치된 집합에서 만든다.
- 버린 대안: 참조 기능 복사+토큰 치환(D1에 어긋나고 전역 ID를 놓친다),
topic을 뼈대에서 빼기(실제 기능이 같은 문제를 다시 만난다), 생성
테스트가 tests/mocks의 bootstrap·server를 쓰기(부팅 문서는 테스트 안의
fetcher가 주고, MSW는 setupServer와 http-scenarios만 쓴다).
위험·한계
- 생성기 파일이 1,408줄이다. 대부분 템플릿 문자열이다.
- context-module.ts는 생성기가 글로 읽는 선언이라 실행되지 않는다(참조
context와 같다). 나머지 생성 모듈은 생성된 테스트가 모두 실행한다
(함수 100%, 문장 100%, 페이지 분기 1개 미실행).
- --context reference-context로 참조 context에 넣으면 참조 기능의
installed-context-routing 테스트(라우트 4개 정확히 일치)가 깨진다.
드릴은 새 context를 쓴다.
- test:feature-scaffold, test:sample-removal, check:architecture는
pnpm이 필요해 worktree에서 돌리지 않았다.
- tests/unit/feature-shape-growth.test.ts는 기준 커밋에서도 1 KiB를 넘어
실패한다(이번 측정 1035·1068). 기능이 하나 더 있으면 통과한다.
검증
- RED: 생성한 기능을 넣고 돌리면 tests/release 7건 실패("expected
{ state: 'release-mismatch' } to match { state: 'booted' }"),
ci-workflow-generation 1건 실패(98 vs 99). 접두어 테스트는 템플릿의
스키마 ID를 "NoRequest"로 바꾼 변이에서 실패한다.
- GREEN(worktree에 order-feature 생성): tsc app·test·node rc=0, 전체
eslint rc=0, check-registries "11 registries PASS; compatibility=
additive"(기준선 재승인 없음), verify-documentation-readiness
PASS_SCOPED, check-i18n PASS, check-design-system·check-diagnostics·
check-adapter-inventory PASS, check-ci-contract·workflow·artifact
schema PASS, 생성 테스트 7/7, run-vitest tests/unit·component·features
238파일 통과, integration·contract·runtime-schema·platform·architecture·
release·scripts 59파일 통과(pnpm을 띄우는 2파일 제외).
- --context reference-context와 --package 변형도 tsc·registries·생성
테스트 통과. 참조 기능을 지운 복사본에서 생성 → tsc app·test, i18n,
생성 테스트·release·router 테스트 통과(결정 4 모의).
- 생성물을 지운 뒤 같은 검사 통과(feature-shape-growth 기존 실패 1건
제외), git status 깨끗.
1409 lines
49 KiB
TypeScript
1409 lines
49 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 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<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}-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)],
|
|
[`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<typeof ${camel}ItemDtoSchema>;
|
|
|
|
export const ${camel}ItemListPayloadSchema = z.array(${camel}ItemDtoSchema).max(100);
|
|
|
|
/** Problem details; a backend message is never kept. */
|
|
export const ${camel}ProblemSchema = z
|
|
.object({
|
|
type: z.string().min(1).max(512),
|
|
title: z.string().min(1).max(240),
|
|
status: z.int().min(100).max(599),
|
|
code: z.string().min(1).max(120).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),
|
|
});
|
|
|
|
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<readonly ${pascal}ItemView[]> {
|
|
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<Record<string, InstalledBoundaryMapper>>);
|
|
`;
|
|
}
|
|
|
|
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,
|
|
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 {
|
|
// Spec §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, 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<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 });
|
|
});
|
|
});
|
|
|
|
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(
|
|
<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();
|
|
});
|
|
|
|
// tests/e2e/accessibility.spec.ts answers every API with [].
|
|
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 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 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<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();
|
|
}
|