루트 항목 하나를 옮기려면 코드 7곳의 루트 경로 목록을 같이 고쳐야 했다(복사 대상, 비밀값 검사 범위, 공급망 시험의 필수 입력, 이력 문서 검사, 규모 입력, vite 입력, TS 전용 규칙). 서로 다른 부분집합이고 한 곳에서 선언하지 않았다. 목록이 갈라져 공급망 생성이 깨진 적도 있다 (removal-fixture.ts 주석). 루트에는 JSON Schema 5개만 담은 `schemas/`가 `config/` 옆에 따로 있었다. `artifacts/`(출력 폴더)에는 사람이 쓴 수동 a11y 기록이, `config/hosting/`(호스트 계약)에는 시험 fixture가 섞였다. 고른 방법(design-docs repo-structure/04-frontend-layout.md 9.2절 3단계, 11절 R1·R2, 소유자 승인 2026-11-07): - `config/repository-layout.json`이 루트 항목마다 종류·역할·읽는 곳과 들어가는 목록(`sets`, 항목 안 경로는 `setPaths`)을 적는다. `scripts/lib/repository-layout.ts`가 읽고 검증한다. 6곳은 이름 붙은 집합을 고른다. JSON인 비밀값 검사 정책은 집합의 사본을 두고 시험이 같은지 본다(정책 파일은 릴리스 후보에 실려 형식을 바꾸지 않았다). 공급망 시험의 필수 입력 목록은 그 시험으로 대신한다. - `tests/unit/repository-layout.test.ts`: 등록부에 없는 루트 항목이 추적되면 실패(R1). 7곳이 등록부 모듈을 쓰고 루트 이름 둘 이상의 문자열 배열을 갖지 않는지(R2). - `schemas/artifacts/` → `config/schemas/artifacts/`, recipe 카탈로그 스키마 → `config/schemas/recipes/`. 정책 입력 순서(ASCII)에 맞춰 `config/schemas/`가 `config/security/` 앞에 온다. - 수동 a11y 기록 3개 → `docs/accessibility/route-reviews/`. `artifacts/`는 `.gitkeep`만 추적한다. 기록은 단위 시험이 읽어서 drill 사본에도 복사한다(`fixture-copy` 집합의 `docs/accessibility/route-reviews`). - `config/hosting/response-headers.fixture.json` → `tests/fixtures/hosting/response-headers.json`. 버린 것: 비밀값 검사 정책이 집합 이름을 참조하게 바꾸는 방법. 정책 파일은 릴리스 후보와 로컬 증거 평가가 읽는 형식이라 바꾸면 릴리스 증거 계약이 바뀐다. 루트 항목이 지워졌는데 등록부에 남는 경우는 시험하지 않았다. drill 사본은 일부만 복사해 그 방향을 볼 수 없다. 그런 항목은 그 집합을 쓰는 곳(복사, 비밀값 검사)에서 실패한다. 위험: 하네스 작업(fe-c)이 더할 `AGENTS.md`·`.claude/`를 미리 등록했다 (optional). 등록부가 이력 문서(`SPEC.md`)와 `CLAUDE.md` 이름을 적어서 이력 문서 검사에서 등록부 파일은 뺐다. 다운스트림은 자기 루트 항목을 등록부에 더해야 한다(CHANGELOG). CI 계약 기준선을 다시 받았다(a11y 기록 산출물 id·경로). 검증(desktop): 아래 4단계 커밋까지 쌓은 트리에서 test:unit, check:types, check:ci, lint, verify:documentation을 돌렸다(그 커밋에 적음). 이 커밋 단독으로 test:unit·check:ci·check:types를 돌렸다. Refs: design-docs repo-structure/04-frontend-layout.md 2.4·9.2·11절, README.md 3.4절
1838 lines
66 KiB
TypeScript
1838 lines
66 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 {
|
|
planWriteSlice,
|
|
renderCreatePage,
|
|
renderCreatePageTest,
|
|
renderDetailPage,
|
|
renderForm,
|
|
renderRouteCodecs,
|
|
renderUseCreate,
|
|
renderUseItem,
|
|
renderWriteDescriptors,
|
|
renderWriteGatewayHelpers,
|
|
renderWriteGatewayMethods,
|
|
renderWriteGatewayOperations,
|
|
renderWriteGatewayTests,
|
|
renderWriteMapper,
|
|
renderWriteMessages,
|
|
renderWriteRouteRuntimeContracts,
|
|
renderWriteRoutes,
|
|
renderWriteSchemaRows,
|
|
renderWriteSchemas,
|
|
renderWriteValidators,
|
|
writeSliceMessageKeys,
|
|
type WriteSemantics,
|
|
type WriteSlice,
|
|
} from "./create-feature-write-slice.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, a gateway test and an input test. It reads
|
|
* the paired backend's Envelope, at the path its new-feature.sh maps
|
|
* (`/<plural>`, 1103/03-07). `--with-create` adds the backend scaffold's
|
|
* create and read-by-id with their pages (`create-feature-write-slice.ts`).
|
|
* The templates live in these two files 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;
|
|
/** `--with-create` (NEVER) or `--with-create --keyed` (KEYED). */
|
|
write?: WriteSemantics | 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;
|
|
/** Every route the feature declares, the list first. */
|
|
routes: readonly Readonly<{ routeId: string; path: string }>[];
|
|
/** 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("");
|
|
}
|
|
|
|
/**
|
|
* 1103/03-07. The path segment the paired backend's new-feature.sh maps for
|
|
* the same name: its camel-case name plus `es` after s, x, ch or sh, `ies`
|
|
* for a consonant and y, `s` otherwise.
|
|
*/
|
|
export function backendPathSegment(camel: string): string {
|
|
if (/(?:s|x|ch|sh)$/u.test(camel)) return `${camel}es`;
|
|
if (/[^aeiou]y$/u.test(camel)) return `${camel.slice(0, -1)}ies`;
|
|
return `${camel}s`;
|
|
}
|
|
|
|
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`;
|
|
const write =
|
|
request.write === undefined ? null : planWriteSlice(names, routePath, request.write);
|
|
const planned = [
|
|
{ routeId, path: routePath, chunkId },
|
|
...(write ? [write.detail, write.create] : []),
|
|
];
|
|
for (const own of planned) {
|
|
for (const route of installed.routes) {
|
|
if (
|
|
route.routeId === own.routeId ||
|
|
route.path === own.path ||
|
|
route.chunkId === own.chunkId
|
|
) {
|
|
fail(
|
|
`route ${own.routeId} (${own.path}, ${own.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`,
|
|
...(write ? writeSliceMessageKeys(names, write) : []),
|
|
];
|
|
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: `/${backendPathSegment(names.camel)}`,
|
|
owner: `feature-frontend-${id}`,
|
|
contractPackage: request.contractPackage ?? null,
|
|
write,
|
|
});
|
|
|
|
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)],
|
|
...(write
|
|
? ([
|
|
[`${feature}/presentation/${base}-route-codecs.ts`, renderRouteCodecs({ ...shape, write })],
|
|
[`${feature}/presentation/use-${base}-item.ts`, renderUseItem({ ...shape, write })],
|
|
[`${feature}/presentation/use-${base}-create.ts`, renderUseCreate({ ...shape, write })],
|
|
[`${feature}/presentation/${base}-form.ts`, renderForm({ ...shape, write })],
|
|
[`${feature}/presentation/${base}-detail-page.tsx`, renderDetailPage({ ...shape, write })],
|
|
[`${feature}/presentation/${base}-create-page.tsx`, renderCreatePage({ ...shape, write })],
|
|
] as const)
|
|
: []),
|
|
[`tests/features/${id}/${base}-test-app.tsx`, renderTestApp(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)],
|
|
...(write
|
|
? ([
|
|
[
|
|
`tests/features/${id}/${base}-create-page.test.tsx`,
|
|
renderCreatePageTest({ ...shape, write }),
|
|
],
|
|
] as const)
|
|
: []),
|
|
...planned.map(
|
|
(route) =>
|
|
[`docs/accessibility/route-reviews/${route.routeId}.md`, renderA11yRecord(route.routeId)] as const,
|
|
),
|
|
]);
|
|
return Object.freeze({
|
|
id,
|
|
contextId,
|
|
newContext: existing === undefined,
|
|
routeId,
|
|
routePath,
|
|
topic,
|
|
placeholder: request.contractPackage === undefined,
|
|
routes: Object.freeze(
|
|
planned.map((route) => Object.freeze({ routeId: route.routeId, path: route.path })),
|
|
),
|
|
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;
|
|
/** `--with-create`: the paired backend scaffold's create and read-by-id. */
|
|
write: WriteSlice | 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, write }: 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";
|
|
${write ? `import { ${upper}_ROUTE_CODECS } from "./presentation/${base}-route-codecs.ts";\n` : ""}
|
|
/**
|
|
* 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],${
|
|
write ? `\n codecs: ${upper}_ROUTE_CODECS,` : ""
|
|
}
|
|
}),
|
|
}),
|
|
),
|
|
);
|
|
`;
|
|
}
|
|
|
|
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},
|
|
}),
|
|
${shape.write ? renderWriteRoutes({ ...shape, write: shape.write }) : ""} }),
|
|
routeRuntimeContracts: Object.freeze({
|
|
${routeId}: Object.freeze({
|
|
routeId: "${routeId}",
|
|
moduleId: "${base}-list-page",
|
|
paramsCodec: "none",
|
|
searchCodec: "none",
|
|
}),
|
|
${shape.write ? renderWriteRouteRuntimeContracts({ ...shape, write: shape.write }) : ""} }),
|
|
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(shape: Shape): string {
|
|
const { names, write } = shape;
|
|
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>;
|
|
${write ? renderWriteSchemas({ ...shape, write }) : ""}
|
|
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),
|
|
${write ? renderWriteValidators({ ...shape, write }) : ""}});
|
|
`;
|
|
}
|
|
|
|
function renderMapper(shape: Shape): string {
|
|
const { names, write } = shape;
|
|
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 }>;
|
|
|
|
/**
|
|
* 1103/03-02. The items and how many there are in all. A page list's
|
|
* \`meta.page.total\` counts every page; the array is only this page
|
|
* (the backend's default size is 20). Without \`meta.page\` the total is
|
|
* the items received.
|
|
*/
|
|
export type ${pascal}ItemList = Readonly<{
|
|
items: readonly ${pascal}ItemView[];
|
|
total: number;
|
|
}>;
|
|
|
|
function toView(dto: ${pascal}ItemDto): ${pascal}ItemView {
|
|
return Object.freeze({ itemId: dto.id, name: dto.name });
|
|
}
|
|
|
|
/**
|
|
* 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[],
|
|
{ page }: Readonly<{ page?: Readonly<{ total: number }> }> = {},
|
|
): BoundaryMappingResult<${pascal}ItemList> {
|
|
const items = Object.freeze(payload.map(toView));
|
|
return mappingSuccess(Object.freeze({ items, total: page?.total ?? items.length }));
|
|
}
|
|
${write ? renderWriteMapper({ ...shape, write }) : ""}`;
|
|
}
|
|
|
|
function renderSchemaMetadata(shape: Shape): string {
|
|
const { names, owner, write } = shape;
|
|
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. \`boundary\`, \`direction\` and
|
|
* \`unknownFieldPolicy\` must say where and how each schema is used:
|
|
* tests/unit/schema-metadata-policy.test.ts compares them with the
|
|
* descriptors, the routes and the zod validators.
|
|
*/
|
|
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",
|
|
}),
|
|
${pascal}Problem: Object.freeze({
|
|
schemaId: "${pascal}Problem",
|
|
boundary: "api-problem",
|
|
owner: OWNER,
|
|
runtime: "zod",
|
|
schemaVersion: 1,
|
|
direction: "RESPONSE",
|
|
unknownFieldPolicy: "STRIP_UNKNOWN",
|
|
}),
|
|
${write ? renderWriteSchemaRows({ ...shape, write }) : ""}} as const);
|
|
`;
|
|
}
|
|
|
|
function renderContractContribution(shape: Shape): string {
|
|
const { names, operationId, apiPath, write } = shape;
|
|
const { base, pascal, upper } = names;
|
|
return `import type {
|
|
${write ? "CommandEffectDescriptor,\n " : ""}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,${write ? `\n type ${pascal}CreateRequest,\n type ${pascal}Params,` : ""}
|
|
type ${pascal}Problem,
|
|
} from "./${base}-schemas.ts";
|
|
|
|
/**
|
|
* 1103/03-07. The paired backend's new-feature.sh maps the feature at this
|
|
* resource path (its \`--path\`, by default the plural of the name): POST
|
|
* creates and \`GET /{id}\` reads one. It generates no list: add the \`GET\`
|
|
* page list (\`PageParams\`) on the backend, or the list answers 405. The
|
|
* backend's \`api-base-path\` (\`/v1\`, \`/api\` locally) belongs in
|
|
* \`API_BASE_URL\`, which ends with a slash.
|
|
*/
|
|
const API_PATH = "${apiPath}";
|
|
|
|
/**
|
|
* 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: API_PATH,
|
|
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). Every
|
|
// operation of this contribution says so (1103/16-01: composition refuses
|
|
// one that does not, and check:types one without the line). Write
|
|
// "NONE" on all of them 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
|
|
>;
|
|
${write ? renderWriteDescriptors({ ...shape, write }) : ""}
|
|
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,${
|
|
write
|
|
? `\n ${write.getOperationId}_CONTRACT,\n ${write.createOperationId}_CONTRACT,`
|
|
: ""
|
|
}
|
|
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
|
|
events: Object.freeze([]),
|
|
});
|
|
`;
|
|
}
|
|
|
|
function renderMessageCatalog(shape: Shape): string {
|
|
const { names, routeId, write } = shape;
|
|
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} 목록",
|
|
${write ? renderWriteMessages({ ...shape, write }, "ko") : ""} }),
|
|
"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",
|
|
${write ? renderWriteMessages({ ...shape, write }, "en") : ""} }),
|
|
} as const);
|
|
`;
|
|
}
|
|
|
|
function renderFeatureApi(shape: Shape): string {
|
|
const { names, write } = shape;
|
|
const { base, pascal, upper } = names;
|
|
const writeTypes = write
|
|
? `
|
|
/**
|
|
* A write takes the mutation's intent: it names the operation and, for a
|
|
* KEYED command, carries the idempotency key. The executor refuses a KEYED
|
|
* command without one before sending.
|
|
*/
|
|
export type ${pascal}CommandContext = Readonly<{ signal?: AbortSignal; intent: MutationIntent }>;
|
|
|
|
export type ${pascal}CreateCommand = Readonly<{ name: string }>;
|
|
`
|
|
: "";
|
|
return `import type {} from "../../../application/ports/in/application-api.ts";
|
|
${write ? `import type { MutationIntent } from "../../../contracts/mutation-intent.ts";\n` : ""}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}ItemList,${write ? `\n ${pascal}ItemView,` : ""}
|
|
} from "../contracts/${base}-mapper.ts";
|
|
|
|
export type ${pascal}CallContext = Readonly<{ signal?: AbortSignal }>;
|
|
${writeTypes}
|
|
/** What the feature's pages call. Name methods after what the user does. */
|
|
export type ${pascal}FeatureInput = Readonly<{
|
|
listItems(context?: ${pascal}CallContext): Promise<Result<${pascal}ItemList>>;${
|
|
write
|
|
? `
|
|
getItem(itemId: string, context?: ${pascal}CallContext): Promise<Result<${pascal}ItemView>>;
|
|
createItem(
|
|
command: ${pascal}CreateCommand,
|
|
context: ${pascal}CommandContext,
|
|
): Promise<Result<${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<${pascal}ItemList>>;${
|
|
write
|
|
? `
|
|
get(${write.idParam}: string, context?: ${pascal}CallContext): Promise<Result<${pascal}ItemView>>;
|
|
create(
|
|
command: ${pascal}CreateCommand,
|
|
context: ${pascal}CommandContext,
|
|
): Promise<Result<${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);
|
|
function reported<Value>(kind: string, result: Result<Value>): Result<Value> {
|
|
if (!result.ok && result.error.kind !== "REQUEST_ABORTED") {
|
|
void events.emit({
|
|
kind,
|
|
severity: "warning",
|
|
featureId: ${upper}_FEATURE_ID,
|
|
payload: Object.freeze({ reason: result.error.kind }),
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
return Object.freeze({
|
|
async listItems(context) {
|
|
return reported("${base}.list.failed", await gateway.list(context));
|
|
},${
|
|
write
|
|
? `
|
|
async getItem(itemId, context) {
|
|
return reported("${base}.detail.failed", await gateway.get(itemId, context));
|
|
},
|
|
async createItem(command, context) {
|
|
return reported("${base}.create.failed", await gateway.create(command, context));
|
|
},`
|
|
: ""
|
|
}
|
|
});
|
|
}
|
|
`;
|
|
}
|
|
|
|
function renderHttpGateway(shape: Shape): string {
|
|
const { names, operationId, routeId, write } = shape;
|
|
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,${
|
|
write
|
|
? `
|
|
${write.createOperationId}_CONTRACT,
|
|
${write.getOperationId}_CONTRACT,`
|
|
: ""
|
|
}
|
|
} from "../contracts/${base}-contract-contribution.ts";
|
|
import type { ${upper}_FEATURE_CONTRACT } from "../contracts/${base}-feature-contract.ts";
|
|
import {${write ? `\n map${pascal}Item,` : ""}
|
|
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}",
|
|
// A page list's meta.page arrives as the second argument (1103/03-02).
|
|
mapSuccess: map${pascal}ItemList,
|
|
}),
|
|
${write ? renderWriteGatewayOperations({ ...shape, write }) : ""}} 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);
|
|
},
|
|
${write ? renderWriteGatewayMethods({ ...shape, write }) : ""} });
|
|
}
|
|
`;
|
|
}
|
|
|
|
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, write }: Shape): string {
|
|
const { base, upper } = names;
|
|
const page = (id: string, moduleId: string, file: string) => ` ${id}: Object.freeze({
|
|
moduleId: "${moduleId}",
|
|
Component: lazy(() => import("./${file}")),
|
|
}),
|
|
`;
|
|
return `import { lazy } from "react";
|
|
|
|
/** The lazy page of each route; \`moduleId\` equals the route runtime contract's. */
|
|
export const ${upper}_ROUTE_RUNTIME = {
|
|
${page(routeId, `${base}-list-page`, `${base}-list-page.tsx`)}${
|
|
write
|
|
? page(write.detail.routeId, write.detail.moduleId, `${base}-detail-page.tsx`) +
|
|
page(write.create.routeId, write.create.moduleId, `${base}-create-page.tsx`)
|
|
: ""
|
|
}} as const;
|
|
`;
|
|
}
|
|
|
|
function renderRoutes({ names, write }: Shape): string {
|
|
const { base, camel, pascal, upper } = names;
|
|
if (write === null) {
|
|
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);
|
|
}
|
|
`;
|
|
}
|
|
return `import { buildRouteUrl } from "../../../presentation/routes/route-codecs.ts";
|
|
import { useRouteInput } from "../../../presentation/routes/route-input.tsx";
|
|
import type { ${upper}_FEATURE_CONTRACT } from "../contracts/${base}-feature-contract.ts";
|
|
import { ${upper}_ROUTE_CODECS } from "./${base}-route-codecs.ts";
|
|
|
|
/**
|
|
* 16-04. A link names its route ID and the router's builder fills in the
|
|
* contract's \`path\` through the codecs that parse it, so the contract stays
|
|
* the one place a path is written.
|
|
*/
|
|
export function ${camel}RouteUrl(
|
|
routeId: keyof typeof ${upper}_FEATURE_CONTRACT.routes,
|
|
input?: Parameters<typeof buildRouteUrl>[1],
|
|
): string {
|
|
return buildRouteUrl(routeId, input, ${upper}_ROUTE_CODECS);
|
|
}
|
|
|
|
/** The detail route's id, read back through the codec that accepted it. */
|
|
export function use${pascal}ItemId(): string {
|
|
return ${upper}_ROUTE_CODECS.${pascal}Params.parse(useRouteInput().params).${write.idParam};
|
|
}
|
|
`;
|
|
}
|
|
|
|
function renderUseItems({ names }: 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}ItemList } 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(list: ${pascal}ItemList): QueryResultMeasure {
|
|
let estimatedBytes = 24;
|
|
for (const item of list.items) {
|
|
estimatedBytes +=
|
|
UTF8.encode(item.itemId).byteLength + UTF8.encode(item.name).byteLength + 16;
|
|
}
|
|
return { itemCount: list.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,
|
|
namespace: ${upper}_ITEM_QUERY_NAMESPACE,
|
|
profileId: "LIST_STANDARD",
|
|
measureResult: measureItems,
|
|
execute: (_input: typeof NO_INPUT, { signal }) => input.listItems({ signal }),
|
|
},
|
|
NO_INPUT,
|
|
scope,
|
|
),
|
|
);
|
|
}
|
|
`;
|
|
}
|
|
|
|
function renderListPage({ names, write }: Shape): string {
|
|
const { base, camel, pascal } = names;
|
|
const item = write
|
|
? `<li key={item.itemId}>
|
|
<Link
|
|
to={${camel}RouteUrl("${write.detail.routeId}", {
|
|
params: { ${write.idParam}: item.itemId },
|
|
})}
|
|
>
|
|
{item.name}
|
|
</Link>
|
|
</li>`
|
|
: `<li key={item.itemId}>{item.name}</li>`;
|
|
return `${write ? `import { Link } from "react-router-dom";\n\n` : ""}import {
|
|
AsyncSurface,
|
|
CollectionPage,
|
|
EmptySurface,
|
|
} from "../../../presentation/design-system/index.ts";
|
|
import { useLocale } from "../../../presentation/i18n/index.ts";
|
|
${write ? `import { ${camel}RouteUrl } from "./${base}-routes.ts";\n` : ""}import { use${pascal}Items } from "./use-${base}-items.ts";
|
|
|
|
/**
|
|
* The result count is the backend's total (\`meta.page.total\`), not the
|
|
* length of this page. 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"),
|
|
}}${
|
|
write
|
|
? `
|
|
actions={[
|
|
{
|
|
kind: "link",
|
|
label: message("${camel}.list.create"),
|
|
to: ${camel}RouteUrl("${write.create.routeId}"),
|
|
variant: "primary",
|
|
},
|
|
]}`
|
|
: ""
|
|
}
|
|
resultCount={
|
|
query.data ? message("${camel}.list.resultCount", { count: query.data.total }) : null
|
|
}
|
|
>
|
|
<AsyncSurface state={query.state} onRetry={query.retry}>
|
|
{query.data?.items.length ? (
|
|
<ul aria-label={message("${camel}.list.items")}>
|
|
{query.data.items.map((item) => (
|
|
${item}
|
|
))}
|
|
</ul>
|
|
) : (
|
|
<EmptySurface />
|
|
)}
|
|
</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({
|
|
items: Object.freeze([Object.freeze({ itemId: "item-1", name: "First item" })]),
|
|
total: 1,
|
|
});
|
|
|
|
/** A gateway whose other methods are never called. */
|
|
function gatewayListing(list: () => Promise<unknown>) {
|
|
return { list } as unknown as Parameters<typeof create${pascal}FeatureInput>[0];
|
|
}
|
|
|
|
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(
|
|
gatewayListing(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(
|
|
gatewayListing(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 emit = vi.fn<TelemetryPort["emit"]>();
|
|
const input = create${pascal}FeatureInput(
|
|
gatewayListing(async () => ({ ok: false, error: failure })),
|
|
{ telemetry: { emit } },
|
|
);
|
|
|
|
await expect(input.listItems()).resolves.toEqual({ ok: false, error: failure });
|
|
expect(emit).not.toHaveBeenCalled();
|
|
});
|
|
});
|
|
`;
|
|
}
|
|
|
|
function renderPageTest({ names, operationId, routeId, apiPath }: Shape): string {
|
|
const { base, camel, upper } = names;
|
|
return `// @vitest-environment jsdom
|
|
|
|
import { screen } from "@testing-library/react";
|
|
import { http, HttpResponse } from "msw";
|
|
import { setupServer } from "msw/node";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
|
|
|
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";
|
|
import { API, openSignedIn } from "./${base}-test-app.tsx";
|
|
|
|
const MESSAGES = ${upper}_MESSAGE_CATALOGS["ko-KR"];
|
|
|
|
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 = await openSignedIn(${camel}RouteUrl("${routeId}"));
|
|
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();
|
|
});
|
|
|
|
// 1103/03-02. The backend's page list counts every page in meta.page.
|
|
it("counts the items the backend counted, not the first page", async () => {
|
|
api.use(
|
|
http.get(\`\${API}${apiPath}\`, () =>
|
|
HttpResponse.json({
|
|
success: true,
|
|
data: [{ id: "item-1", name: "First item" }],
|
|
meta: { page: { number: 0, size: 20, total: 41, sort: null } },
|
|
}),
|
|
),
|
|
);
|
|
await openList();
|
|
|
|
expect(await screen.findByText("총 41개 항목")).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 renderTestApp({ names }: Shape): string {
|
|
return `import { render, screen } from "@testing-library/react";
|
|
import userEvent from "@testing-library/user-event";
|
|
|
|
import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts";
|
|
import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx";
|
|
import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts";
|
|
|
|
/**
|
|
* The whole app for the ${names.id} page tests: boot documents from here,
|
|
* every API call to MSW at \`API\`. Retries are off so a failure shows at
|
|
* once; the gateway test runs the app's default of two.
|
|
*/
|
|
export const API = "https://api.test";
|
|
|
|
const RUNTIME_CONFIG = {
|
|
APP_ENV: "local",
|
|
API_BASE_URL: API,
|
|
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" },
|
|
};
|
|
|
|
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);
|
|
};
|
|
|
|
/** Opens a URL of the feature through the router and signs in (demo mode). */
|
|
export async function openSignedIn(url: string) {
|
|
const user = userEvent.setup();
|
|
window.history.pushState({}, "", url);
|
|
render(
|
|
<RuntimeApplication
|
|
composition={await createRuntimeComposition({ fetcher, host: {} })}
|
|
/>,
|
|
);
|
|
await user.click(await screen.findByRole("button", { name: KO_MESSAGES["action.signIn"] }));
|
|
return user;
|
|
}
|
|
`;
|
|
}
|
|
|
|
function renderGatewayTest(shape: Shape): string {
|
|
const { names, apiPath, write } = shape;
|
|
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";
|
|
${write ? `import { defineMutationIntent } from "../../../src/contracts/mutation-intent.ts";\n` : ""}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 a descriptor stops
|
|
* reading that wire (1103/16-01). Add a case here for each operation you add.
|
|
*/
|
|
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, category = "VALIDATION") {
|
|
return {
|
|
success: false,
|
|
error: {
|
|
code,
|
|
category,
|
|
message: "backend message",
|
|
retryable: false,
|
|
...(details === undefined ? {} : { details }),
|
|
},
|
|
meta: META,
|
|
};
|
|
}
|
|
${write ? renderWriteGatewayHelpers({ ...shape, write }) : ""}
|
|
/**
|
|
* The app's default retry limit (MAX_RETRY_ATTEMPTS 2 in config/runtime) with
|
|
* no backoff wait, so the descriptors' own retry budgets decide.
|
|
*/
|
|
function gateway() {
|
|
const executor = createContractHttpExecutor({
|
|
baseUrl: API,
|
|
maxRetryAttempts: 2,
|
|
random: () => 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,
|
|
...(context.intent === undefined ? {} : { intent: context.intent }),
|
|
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: { items: [{ itemId: "item-1", name: "First item" }], total: 1 },
|
|
});
|
|
});
|
|
|
|
// 1103/03-02. A page list counts every page in meta.page.
|
|
it("reads the total of a page list from meta.page", async () => {
|
|
answer(200, {
|
|
success: true,
|
|
data: [{ id: "item-1", name: "First item" }],
|
|
meta: { ...META, page: { number: 0, size: 20, total: 41, sort: null } },
|
|
});
|
|
|
|
await expect(gateway().list()).resolves.toMatchObject({ ok: true, value: { total: 41 } });
|
|
});
|
|
|
|
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: { items: [], total: 0 },
|
|
});
|
|
});
|
|
|
|
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" },
|
|
});
|
|
});
|
|
${write ? renderWriteGatewayTests({ ...shape, write }) : ""}});
|
|
`;
|
|
}
|
|
|
|
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),
|
|
});
|
|
}
|
|
|
|
/**
|
|
* 1105/16-01. Tracked template files that change with every added feature,
|
|
* and the command that writes each. A feature branch commits them with the
|
|
* feature; two feature branches change the same lines, and the merge takes
|
|
* the command again instead of a hand-merged value. docs/manual/03 (A) and
|
|
* the "Adding a feature" table in docs/architecture/starter-experience.md
|
|
* list them (tests/unit/feature-tracked-files.test.ts).
|
|
*/
|
|
export const FEATURE_TRACKED_FILE_REWRITES = Object.freeze([
|
|
Object.freeze({
|
|
path: "public/release-manifest.json",
|
|
command: "node scripts/write-dev-release-manifest.ts",
|
|
when: "create:feature runs it: the dev server's manifest names the installed contract packages",
|
|
}),
|
|
Object.freeze({
|
|
path: "config/scale/feature-shape-ceilings.json",
|
|
command: "node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write",
|
|
when: "by hand with the feature: test:unit compares it with a build",
|
|
}),
|
|
]);
|
|
|
|
const USAGE =
|
|
"Usage: pnpm create:feature <id> [--context <context id>] [--with-create [--keyed]] " +
|
|
"[--package @scope/name@x.y.z --digest sha256:<64 hex> --revision <hex>]";
|
|
|
|
export 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" },
|
|
"with-create": { type: "boolean" },
|
|
keyed: { type: "boolean" },
|
|
},
|
|
});
|
|
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 ?? "",
|
|
});
|
|
}
|
|
if (values.keyed === true && values["with-create"] !== true) {
|
|
fail(`--keyed needs --with-create. ${USAGE}`);
|
|
}
|
|
const write: WriteSemantics | undefined =
|
|
values["with-create"] === true ? (values.keyed === true ? "KEYED" : "NEVER") : undefined;
|
|
return Object.freeze({ id, context: values.context, contractPackage, write });
|
|
}
|
|
|
|
function report(plan: FeaturePlan): string {
|
|
const lines = [
|
|
`create:feature: ${plan.id} in ${plan.contextId}${plan.newContext ? " (new context)" : ""}, ${plan.routes
|
|
.map((route) => `route ${route.routeId} at ${route.path}`)
|
|
.join(", ")}`,
|
|
...[...plan.files.keys()].map((file) => ` created ${file}`),
|
|
"",
|
|
"Next:",
|
|
` 1. Before a release, have a person review and sign ${plan.routes
|
|
.map((route) => `docs/accessibility/route-reviews/${route.routeId}.md`)
|
|
.join(", ")} (FE-GATE-028). The merge gates check only their 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)`,
|
|
" A failing gate's log is artifacts/quality/gates/FE-GATE-<NNN>.txt. Locally FE-GATE-013 needs VITE_COMMIT_SHA=$(git rev-parse HEAD); to run them as CI does, set CI=true and the CI build identity (README).",
|
|
" 3. The initial JavaScript changes. Rewrite config/scale/feature-shape-ceilings.json with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write and commit it with the feature; test:unit compares it with a build. corepack pnpm check:bundle checks the budget.",
|
|
" public/release-manifest.json (the dev server's manifest) now names the feature's contract package; commit it with the feature.",
|
|
" Two feature branches change the same lines of these files. On a merge conflict, take either side and run the command again:",
|
|
...FEATURE_TRACKED_FILE_REWRITES.map((file) => ` ${file.path}: ${file.command}`),
|
|
" 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}`);
|
|
}
|
|
// 1103 X2 #3. The dev server's release manifest names the installed
|
|
// contract packages; the new feature declares one.
|
|
const manifest = spawnSync(
|
|
process.execPath,
|
|
[path.join(scriptDirectory, "write-dev-release-manifest.ts")],
|
|
{ cwd: root, encoding: "utf8" },
|
|
);
|
|
if (manifest.status !== 0) {
|
|
fail(`public/release-manifest.json could not be rewritten:\n${manifest.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();
|
|
}
|