chore(review): 1103 기능 생성기·기능 패턴 조치 브랜치를 합친다

Refs: docs/reviews/2026-11-03-maturity-review/README.md 03-07 09-06 16-01 16-04~16-07

# Conflicts:
#	docs/manual/01-add-a-feature.md
#	docs/manual/reference/create-feature.md
#	docs/manual/reference/patterns.md
#	scripts/create-feature.ts
#	scripts/test-feature-scaffold.ts
This commit is contained in:
DongHyeonka
2026-11-04 23:49:27 +09:00
25 changed files with 2269 additions and 222 deletions
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"snapshotDigest": "8f5ae6dde9c6a293144e5bccad1765367f06ac3a6b58a6229c69426703158c9c",
"snapshotDigest": "319a798ca3c9a87d7e2943177d952b13941622f4faec23c28f36024196a9e91d",
"owner": "DongHyeonka",
"reason": "1103/13-04 FE-REG-ENV runtime rows state required and defaultValue as runtimeConfigV2ArtifactSchema reads them (TELEMETRY_ENABLED, AUTH_MODE, RELEASE_MANIFEST_URL, CAPABILITY_OVERRIDES, FEATURE_OVERRIDES); defaultValue may be an object",
"approvedAt": "2026-11-04T11:26:00.863Z"
"reason": "1103/16-04 FE-REG-API problemSchema가 FE-REG-SCHEMA api-problem 행을 참조한다",
"approvedAt": "2026-11-04T14:04:44.377Z"
}
+18 -2
View File
@@ -419,6 +419,11 @@
"field": "responseSchema",
"registryId": "FE-REG-SCHEMA",
"targetField": "schemaId"
},
{
"field": "problemSchema",
"registryId": "FE-REG-SCHEMA",
"targetField": "schemaId"
}
],
"keyField": "operationId",
@@ -543,7 +548,7 @@
"registryId": "FE-REG-SCHEMA",
"owner": "feature-frontend-contract-schema-registry",
"source": "src/features/loaded-feature-runtimes.ts",
"rowCount": 7,
"rowCount": 8,
"contract": {
"requiredFields": [
"schemaId",
@@ -566,7 +571,8 @@
"route-search",
"route-search-api-request",
"api-request",
"api-response"
"api-response",
"api-problem"
],
"runtime": [
"zod"
@@ -602,6 +608,15 @@
"runtime": "zod",
"schemaId": "NotFoundSplat"
},
"ReferenceProblem": {
"boundary": "api-problem",
"direction": "RESPONSE",
"owner": "feature-frontend-reference-feature-vertical-slice",
"runtime": "zod",
"schemaId": "ReferenceProblem",
"schemaVersion": 1,
"unknownFieldPolicy": "STRIP_UNKNOWN"
},
"ReferenceResourceListPayload": {
"boundary": "api-response",
"direction": "RESPONSE",
@@ -1407,6 +1422,7 @@
],
"optionalAttributes": [
"duration_bucket",
"effect_certainty",
"operation_id"
],
"requiredAttributes": [
+7 -1
View File
@@ -227,6 +227,11 @@
"field": "responseSchema",
"registryId": "FE-REG-SCHEMA",
"targetField": "schemaId"
},
{
"field": "problemSchema",
"registryId": "FE-REG-SCHEMA",
"targetField": "schemaId"
}
],
"consumerIdentityField": "operationId",
@@ -269,7 +274,8 @@
"route-search",
"route-search-api-request",
"api-request",
"api-response"
"api-response",
"api-problem"
],
"runtime": ["zod"]
},
+65 -19
View File
@@ -29,10 +29,17 @@
1단계의 생성 명령이 3~8단계와 10단계의 가장 작은 판을 한 번에 만든다.
- 라우트 1개 (파라미터 없는 목록)
- GET 1개 (`SAFE`, `EXTERNAL_BEARER`)
- GET 1개 (`SAFE`, `EXTERNAL_BEARER`). 경로는 짝 백엔드 `new-feature.sh`와 같은 `/<plural>`이다
- 쿼리 1개와 무효화 topic 1개
- `CollectionPage` 페이지 1개와 ko-KR·en-US 문구
- 테스트 2개 (application input 단위 테스트, 라우터를 거치는 페이지 테스트)
- `CollectionPage` 페이지 1개와 ko-KR·en-US 문구. 결과 수는 백엔드가 보낸 `meta.page.total`이다
- 테스트 3개와 테스트용 앱 파일 1개 (application input 단위 테스트, 라우터를 거치는 페이지 테스트, 백엔드 본문을 적은 gateway 테스트, `<base>-test-app.tsx`)
`--with-create`를 주면 짝 백엔드 `new-feature.sh`가 만드는 나머지 두 엔드포인트를 함께 만든다.
- 상세 GET(`GET /<plural>/{id}`)과 `DetailPage` 상세 페이지
- 작성 POST(`POST /<plural>`, 201)와 `FormPage` 작성 폼, 결과 불명 화면
- 작성 폼 테스트: 201 저장 뒤 상세 열기, 400 `<FEATURE>_INVALID`를 이름 칸에 보이고 다시 저장, 응답을 잃은 저장
- 작성은 기본이 `NEVER`다. 백엔드 생성기의 create가 `NOT_IDEMPOTENT`라서다. 백엔드 create를 KEYED로 바꿨으면 `--keyed`를 함께 준다([02 결정표 3절](02-decision-tables.md#3-재시도-의미)).
그래서 3~8단계는 "처음부터 쓰기"가 아니라 "생성된 파일을 실제 계약과 화면으로 바꾸기"다.
@@ -102,6 +109,8 @@ corepack pnpm create:feature invoice-feature
① **정할 것**
- `--context <context id>`: 0단계에서 기존 context를 골랐을 때만 준다.
- `--with-create`: 상세와 작성까지 만든다. 짝 백엔드에서 `scripts/new-feature.sh <Name>`을 같은 이름으로 돌렸을 때 준다(예: 프론트 `invoice-feature`, 백엔드 `Invoice` → 둘 다 `/invoices`).
- `--keyed`: `--with-create`와 함께만. 백엔드 create를 멱등성 executor 뒤에 두었을 때(KEYED) 준다.
- `--package @scope/name@x.y.z --digest sha256:<64 hex> --revision <hex>`: 계약 패키지가 이미 배포됐을 때 준다. 셋은 함께 준다.
- 둘 다 없으면 새 context와 자리표시자 계약 신원으로 만든다.
- 자리표시자 신원: 패키지가 아직 없을 때 쓰는 가짜 신원이다. 로컬·개발 빌드는 되고, staging·production 승인은 거절한다.
@@ -117,7 +126,9 @@ corepack pnpm create:feature invoice-feature
- 명령 자체가 거부한다. ID 형식, 기존 기능·context와 겹침, 라우트·경로·chunk·문구 키 충돌, topic 충돌, 패키지 신원 형식.
- 생성기가 거부한다. 선언 헤더가 리터럴이 아님, 없는 context, 예산 초과.
- 이때 명령은 만든 파일을 모두 지우고 `the feature index generator rejected the feature, nothing was kept:`로 끝난다.
- **못 잡음**: `--context reference-context`로 참조 context에 넣으면 참조 기능 테스트 tests/features/reference-feature/installed-context-routing.test.ts가 깨진다. 그 테스트는 참조 context의 라우트 수를 정확히 비교한다. 참조 context에는 넣지 않는다.
- 생성한 context 선언은 `tests/unit/create-feature.test.ts`가 생성기의 선언 읽기와 앱 모듈 조립으로 실행한다. 라우트가 그 루트 밖이면 그 테스트가 실패한다.
- `--context reference-context`로 참조 context에 넣을 수는 있다. 참조 기능의 라우팅 테스트는 참조 기능 자신의 라우트만 본다.
- 다만 경로가 `/examples/reference-resources/<base>`가 된다. 참조 기능을 지우면 context가 그 기능 때문에 남고, 그 경로 문자열이 제거 드릴(`test:sample-removal`)의 잔여 검사(`reference-resource`)에 걸린다(추론, 실행하지 않음). 남길 기능은 제품 context에 둔다.
④ **쓸 스킬**: `clean-architecture`, `codebase-design`
@@ -181,6 +192,9 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope
- 검증기는 `src/contracts/zod-validator.ts`의 `zodValidator(schemaId, schema)` 하나를 쓴다. 기능마다 복사하지 않는다.
- 검증을 일부러 생략할 때는 `src/contracts/unvalidated-payload.ts`의 `unvalidatedPayload(schemaId, reason)`를 쓴다. 이유가 빈 문자열이면 throw한다. 생략 목록은 `listUnvalidatedPayloads`가 보여 준다.
- zod는 `src/contracts/zod.ts`로만 import한다.
- 경로는 짝 백엔드 컨트롤러의 매핑과 같은 `/<plural>`이다. 생성된 descriptor는 `API_PATH` 상수 하나를 쓴다. 백엔드에 `--path`를 줬으면 이 상수를 같은 값으로 바꾼다.
- 백엔드의 `api-base-path`(기본 `/v1`, 로컬 `/api`)는 descriptor에 적지 않는다. `config/runtime/<profile>.json`의 `API_BASE_URL`에 붙이고 끝을 `/`로 둔다(예: `https://api.example.com/v1/`). 끝 `/`가 없으면 실행기가 `URL_ORIGIN_ESCAPED`로 보내지 않는다.
- 백엔드 생성기는 목록 엔드포인트를 만들지 않는다. 백엔드에 `GET /<plural>` 페이지 목록(`PageParams`)을 더하기 전에는 생성된 목록이 405를 받는다.
- 계약 패키지(`@org-contracts/*`)는 `contracts/<service>-contract-contribution.ts` 이름의 파일에서만 import한다.
- 패키지 신원 네 필드(`packageId`, `version`, `digest`, `sourceRevision`)는 `<base>-feature-contract.ts`의 상수 하나에 있다. 바꿀 때는 넷을 함께 바꾼다.
- 근거: `scale-architecture.md` §13(재시도), §20~§22(검증 경계와 예산).
@@ -193,7 +207,10 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope
- Envelope: 성공·실패 본문을 한 번 더 감싸는 공통 바깥 객체다(`http-contract.md` §1).
- 성공: `{ "success": true, "data": ..., "meta": ... }`
- 실패: `{ "success": false, "error": { "code", ... }, "meta": ... }`
- 이 모양을 읽게 하는 것은 V3 descriptor(`<base>-contract-contribution.ts`)의 한 줄 `responseEnvelope: "ENVELOPE_V1"`이다. 뼈대에 들어 있다.
- 이 모양을 읽게 하는 것은 V3 descriptor(`<base>-contract-contribution.ts`)의 한 줄 `responseEnvelope: "ENVELOPE_V1"`이다. 생성된 operation에는 모두 들어 있다.
- operation을 손으로 더할 때마다 이 줄을 적는다. 이 값은 operation마다 따로다.
- 한 계약 기여 안에서 이 값이 다른 operation이 있으면 계약 조립이 거부한다(`<id>/<operationId>: responseEnvelope NONE, but <other> in the same contribution reads ENVELOPE_V1; ...`). 기여 하나는 백엔드 하나의 패키지라서다. 그래서 줄을 빠뜨리면 앱을 조립하는 테스트와 `check:registries`가 실패한다.
- **못 잡음**: 기여 안의 operation 모두에서 이 줄을 빼는 것. 그때는 아래 MSW 줄의 손글씨 gateway 테스트만 잡는다.
```text
성공 status → Envelope 확인 → data를 outputValidator로 검증 → mapSuccess
@@ -206,7 +223,7 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope
- 업무 규칙 거절(`<FEATURE>_INVALID`, `*_ALREADY_EXISTS` 등)은 표에 없어 결과 불명이 된다. 그 엔드포인트가 쓰기 전에만 내는 code면 `commandEffect.refusedBeforeWrite`에 적는다. 적어야 사용자가 값을 고쳐 다시 저장할 수 있다(02 결정표 4절).
- `mapProblem`이 없거나 `undefined`를 돌려주면 백엔드 code·필드 오류·status별 kind로 읽는다(`src/adapters/http/backend-envelope.ts`).
- 바이트 상한(`responseByteLimit`)과 구조 예산은 Envelope 전체에 걸린다.
- MSW: `createHttpScenarioHandler`는 descriptor의 `responseEnvelope`를 보고 Envelope로 답한다(`tests/mocks/handlers/http-scenarios.ts`). 생성된 `tests/features/<id>/<base>-http-gateway.test.ts`는 백엔드 본문을 그대로 적어 검사한다.
- MSW: `createHttpScenarioHandler`는 descriptor의 `responseEnvelope`를 보고 Envelope로 답한다(`tests/mocks/handlers/http-scenarios.ts`). 그래서 시나리오 테스트는 선언이 틀려도 통과한다. 생성된 `tests/features/<id>/<base>-http-gateway.test.ts`는 백엔드 본문을 그대로 적어 검사한다. operation을 더하면 이 파일에도 그 operation의 백엔드 본문 테스트를 더한다.
- `http-contract.md`는 status·`code`의 **뜻**(예: 409 `IDEMPOTENT_IN_FLIGHT`)의 정본이다. 기능 코드에서 그 code는 problem의 `code`로 읽는다.
**짝 백엔드가 아닌 백엔드**
@@ -238,22 +255,32 @@ DTO와 problem details(`type`·`title`·`status`)를 감싸지 않고 보내는
- `route-search-api-request`: 라우트 검색값이면서 GET 쿼리다. 목록 검색이 이 경우다.
- `api-request`: 요청 입력.
- `api-response`: 응답 DTO.
- `api-problem`: 실패 본문(`problemValidator`). Envelope operation이면 `error` 객체다. FE-REG-API의 `problemSchema`가 이 행을 가리킨다.
예: 공지 기능의 검색값 GET과 경로 파라미터 GET. 입력에 관한 칸만 적었다.
스키마 메타데이터의 `boundary`·`direction`·`unknownFieldPolicy`는 손으로 적지만 `tests/unit/schema-metadata-policy.test.ts`(`test:unit`)가 실제 쓰임과 대조한다.
- `boundary`: descriptor의 입력·응답·실패 검증기와 라우트의 `paramsSchema`·`searchSchema`에서 쓰인 자리로 정해진다. 다르면 `<schemaId>: row <적은 값>, used as <맞는 값>`으로 실패한다. 쓰이는데 행이 없으면 `<schemaId>: no FE-REG-SCHEMA row`.
- `direction`: 입력은 `REQUEST`, 응답·실패는 `RESPONSE`.
- `unknownFieldPolicy`: zod가 모르는 키를 거부하면(`.strict()`) `REJECT_UNKNOWN`, 버리면(`.strip()`) `STRIP_UNKNOWN`.
- 이 테스트는 설치된 기능을 읽는다. 기능을 더한 상태에서 `test:unit`을 돌릴 때 잡힌다.
예: 공지 기능의 검색값 GET과 경로 파라미터 GET. 입력에 관한 칸과 응답 모양 줄만 적었다.
```ts
// GET /api/notices?q=... inputValidator 스키마 NoticeListQuery (boundary: "route-search-api-request")
pathTemplate: "/api/notices",
// GET /notices?q=... inputValidator 스키마 NoticeListQuery (boundary: "route-search-api-request")
pathTemplate: "/notices",
inputValidator: zodValidator("NoticeListQuery", noticeListQuerySchema),
responseEnvelope: "ENVELOPE_V1" as const,
projectRequest: (input) => Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze(input.q === undefined ? [] : [Object.freeze(["q", input.q] as const)]),
body: null,
}),
// GET /api/notices/{noticeId} inputValidator 스키마 NoticeParams (boundary: "route-params")
pathTemplate: "/api/notices/{noticeId}",
// GET /notices/{noticeId} inputValidator 스키마 NoticeParams (boundary: "route-params")
pathTemplate: "/notices/{noticeId}",
inputValidator: zodValidator("NoticeParams", noticeParamsSchema),
responseEnvelope: "ENVELOPE_V1" as const,
projectRequest: (input) => Object.freeze({
pathValues: Object.freeze({ noticeId: input.noticeId }),
queryEntries: Object.freeze([]),
@@ -263,8 +290,9 @@ projectRequest: (input) => Object.freeze({
③ **잡는 검사 / 못 잡는 것**
- descriptor의 입력·응답 스키마 ID가 스키마 메타데이터에 없으면 `check:registries`가 실패한다.
- 메시지: `FE-REG-API.<operationId>.requestSchema references unknown FE-REG-SCHEMA.schemaId=<id>` (`responseSchema`도 같다)
- descriptor의 입력·응답·실패 스키마 ID가 스키마 메타데이터에 없으면 `check:registries`가 실패한다.
- 메시지: `FE-REG-API.<operationId>.requestSchema references unknown FE-REG-SCHEMA.schemaId=<id>` (`responseSchema`, `problemSchema`도 같다)
- 스키마 메타데이터의 `boundary`·`direction`·`unknownFieldPolicy`가 실제 쓰임과 다르면 `test:unit`의 `tests/unit/schema-metadata-policy.test.ts`가 실패한다(위 "입력과 스키마 메타데이터").
- 인증 프로필 이름이 틀리면 계약 조립이 거부해 operation을 적재하는 모든 게이트가 실패한다.
- 오류의 `reason`: `<featureId>/<operationId>: unknown authProfileId <id>`
- 스키마 ID나 operation ID가 겹치면 적재 때 그 ID를 말하며 실패한다.
@@ -295,6 +323,7 @@ projectRequest: (input) => Object.freeze({
- input 메서드 이름. 사용자가 하는 일로 짓는다(`listItems`, `createInvoice`).
- 반환 타입. `Result<Value>`(`src/contracts/result.ts`)를 쓴다.
- 쓰기 메서드의 호출 문맥. 쓰기는 뮤테이션의 `intent`를 받아 gateway까지 넘긴다(`Readonly<{ signal?: AbortSignal; intent: MutationIntent }>`). `KEYED` 쓰기의 멱등 키가 intent에 있다. `--with-create`의 `<Base>CommandContext`가 이 모양이다.
- 실패 telemetry의 `kind`. `<base>.<동작>.failed` 꼴로 접두어를 붙인다.
② **기준**
@@ -369,7 +398,8 @@ projectRequest: (input) => Object.freeze({
- `presentation/<base>-feature-runtime.ts`: 지연 로드 페이지 표. `moduleId`는 계약과 같아야 한다.
- `context-routes.ts`: context가 적재하는 라우트 목록. 생성된 판은 계약의 라우트를 그대로 옮긴다.
- `presentation/<base>-routes.ts`: 링크용 URL 함수. route ID를 받아 `buildRouteUrl`(`src/presentation/routes/route-codecs.ts`)로 경로를 채운다.
- 문구 `route.<ROUTE_ID>.title`, `route.<ROUTE_ID>.navigation` (ko-KR, en-US).
- 문구 `route.<ROUTE_ID>.title`, `route.<ROUTE_ID>.navigation` (ko-KR, en-US). 화면의 문서 제목과 메뉴 이름은 이 문구다.
- 계약 `routes`의 `title`·`navigationLabel`은 화면이 읽지 않는다. FE-REG-ROUTE 기준선 행과 lab 측정(`scripts/test-performance.ts`, 플랫폼 라우트만)이 읽는다. 생성 명령은 문구와 같은 값을 넣는다. 값을 바꾸면 `check:registries`가 behavior-change로 기록한다.
- 기능 폴더 밖: `artifacts/tests/a11y-manual/<ROUTE_ID>.md`(pending 기록). 생성 명령이 만든다.
① **정할 것**
@@ -428,14 +458,28 @@ projectRequest: (input) => Object.freeze({
- profile: `LIST_STANDARD`, `DETAIL_STANDARD`, `LOOKUP_STABLE`, `VOLATILE_STATUS` 중 하나. 캐시 시간 정책이다. 정의는 `src/contracts/server-state.ts`.
- `measureResult`: 결과 크기 추정 함수. 캐시 예산에 쓴다.
- `definitionId`: 쿼리·뮤테이션 정의 이름.
- 쓰기가 있으면 뮤테이션 정책: `requiresIdempotencyKey`, `duplicatePolicy`, `invalidate`.
- 쓰기가 있으면 뮤테이션 정책: `duplicatePolicy`, `invalidate`. operation ID와 멱등 키 여부는 정하지 않는다. descriptor에서 받는다(아래).
② **기준**
- topic은 복사하지 않는다. 새 topic이 더 필요하면 값을 새로 만든다.
- 형식: `qinv.` + 소문자·숫자 26자. `scripts/create-feature.ts`의 `randomTopicSuffix`가 쓰는 방식이다.
- `measureResult`에서 `JSON.stringify`를 쓰지 않는다. 문자열 바이트와 항목당 고정 크기로 어림한다(생성된 `measureItems` 참고).
- `KEYED` 쓰기는 `requiresIdempotencyKey: true`, `duplicatePolicy: "REJECT_WHILE_ACTIVE"`, `invalidate: [topic]`을 쓴다.
- 뮤테이션 정책의 operation ID와 `requiresIdempotencyKey`는 `commandMutationIdentity(<OPERATION>_CONTRACT)`(`src/contracts/server-state.ts`)로 descriptor에서 받는다. 손으로 적지 않는다.
- 실행기는 intent의 operation ID가 descriptor와 다르면 보내기 전에 거부한다. 손으로 적은 ID에 오타가 있으면 저장이 항상 실패하고, 화면은 "요청을 처리할 수 없습니다"다.
- `requiresIdempotencyKey`는 `retrySemantics`가 `KEYED`일 때만 참이다.
- 쓰기 정책은 `duplicatePolicy: "REJECT_WHILE_ACTIVE"`, `invalidate: [topic]`을 쓴다.
```ts
const INVOICE_CREATE_MUTATION_POLICY = Object.freeze({
definitionId: "invoice-create-v1",
definitionVersion: 1,
...commandMutationIdentity(INVOICE_CREATE_CONTRACT),
duplicatePolicy: "REJECT_WHILE_ACTIVE" as const,
invalidate: Object.freeze([INVOICE_ITEM_INVALIDATION_TOPIC]),
});
```
- 예제(참조 기능): src/features/reference-feature/presentation/use-reference-feature.ts의 생성 뮤테이션 정책.
③ **잡는 검사 / 못 잡는 것**
@@ -444,7 +488,9 @@ projectRequest: (input) => Object.freeze({
- topic 형식이 틀리면 `Query invalidation topic is invalid.`로 실패한다.
- 등록되지 않은 profile은 실행 때 `Unregistered server-state profile: <id>`로 실패한다.
- topic·namespace·edge를 더하기만 하면 레지스트리 기준선은 바뀌지 않는다(additive). 9단계에서 할 일이 없다.
- **못 잡음**: `bindQuery`의 `operationId` 오타. 타입이 `string`이라 operation과 묶이지 않는다.
- 뮤테이션 정책의 operation ID를 `commandMutationIdentity`로 받으면 descriptor 상수 이름의 오타는 `check:types`가 막는다. 쓰기 descriptor 대신 GET descriptor를 넘기면 바인딩 때 `commandMutationIdentity: <operationId> is a GET; a mutation binds a write operation`으로 throw한다.
- **못 잡음**: 뮤테이션 정책에 operation ID를 문자열로 직접 적은 것. 타입이 `string`이라 오타가 통과하고, 저장할 때 실행기가 보내기 전에 거부한다(`MISSING_IDEMPOTENCY_KEY` 위반). `commandMutationIdentity`를 쓴다.
- `bindQuery`의 `owner`·`operationId`, 뮤테이션 정책의 `owner`는 적지 않는다. 읽는 곳이 없어 `@deprecated` 선택 칸이 됐고, 다음 릴리스에서 지운다. 요청 기록의 operation ID는 descriptor의 것이다.
- **못 잡음**: `definitionId` 중복. 유일성 검사가 없다.
④ **쓸 스킬**: 정해 둔 스킬 없음. 이 절과 02 결정표로 판단한다.
@@ -458,14 +504,14 @@ projectRequest: (input) => Object.freeze({
① **정할 것**
- 페이지 템플릿. [02 결정표 6절](02-decision-tables.md#6-페이지-템플릿)
- `KEYED` 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기).
- 쓰기가 있으면 결과 불명 화면. `AsyncSurface`의 `onReconcileUnknownEffect`(확인), `onResendUnknownEffect`(같은 키로 다시 보내기). 다시 보내기 버튼은 키가 있는 요청(`KEYED`)에만 그려진다. `NEVER` 쓰기는 확인만 남는다.
- 폼이면 서버 422 오류를 받을 필드(`useAppForm`의 `allowedServerFields`).
② **기준**
- 화면 문구는 모두 catalog에서 가져온다(`message(key)`).
- 링크는 6단계의 URL 함수로 만든다.
- 결과 불명 화면 예제(참조 기능): src/features/reference-feature/presentation/reference-resource-form-page.tsx
- 결과 불명 화면 예제: `create:feature <id> --with-create`의 `presentation/<base>-create-page.tsx`(짝 백엔드 Envelope), 참조 기능의 src/features/reference-feature/presentation/reference-resource-form-page.tsx(problem details)
③ **잡는 검사 / 못 잡는 것**
+32 -2
View File
@@ -88,14 +88,44 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|---|---|---|---|
| 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 |
| 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다. 예외: 짝 백엔드가 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절)로 답하면 `retryBudget` 안에서 같은 키로 다시 보낸다 | 된다 | 하지 않는다 |
| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 참조 기능은 `retryBudget: 0` | — | `retryBudget: 0` 필수 |
| 뮤테이션 정책 | `requiresIdempotencyKey: true` | — | — |
| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 짝 백엔드는 `retryBudget: 1`(아래 표), 참조 기능은 `0` | — | `retryBudget: 0` 필수 |
| 뮤테이션 정책 | `...commandMutationIdentity(<OPERATION>_CONTRACT)`가 `requiresIdempotencyKey: true`를 준다 | 같은 함수가 `false`를 준다 | 같은 함수가 `false`를 준다 |
- 멱등 키: 서버가 "같은 쓰기 요청"을 알아보게 하는 값이다.
- 결과를 모를 때 새 키로 다시 보내면 안 된다. 서버는 새 키를 다른 요청으로 보고 막지 못한다.
**기준**: 원칙 3. 서버 계약에 적힌 보장으로 고른다. 모르면 `NEVER`로 두고 백엔드에 묻는다.
**짝 백엔드의 생성 기능에 붙일 때 (1103/16-07, 03-07)**
짝 백엔드 `new-feature.sh`가 만드는 create는 `NOT_IDEMPOTENT`다(`Create__Feature__UseCase.java.tmpl`). `Idempotency-Key`를 읽지 않는다. 그래서 프론트 쪽 값은 백엔드 create를 그대로 두었는지로 정해진다.
```text
백엔드 create
├─ 생성한 그대로 (NOT_IDEMPOTENT, 키를 읽지 않음)
│ → 프론트 NEVER ← create:feature <id> --with-create
└─ IdempotencyExecutor 뒤로 옮김 (KEYED, 백엔드 docs/manual/05-idempotency.md "KEYED로 만드는 순서")
→ 프론트 KEYED ← create:feature <id> --with-create --keyed
```
백엔드가 키를 읽지 않는데 프론트를 `KEYED`로 두면 안 된다. 결과 불명 화면의 "같은 요청으로 다시 보내기"가 새 항목을 하나 더 만든다. 같은 키가 중복을 막는다는 보장이 백엔드에 없다.
두 경우의 값이다. 생성 명령이 이 값을 쓴다. 손으로 만들 때도 같은 값을 쓴다.
| 값 | `NEVER` (백엔드 그대로) | `KEYED` (백엔드 KEYED) | 이유 |
|---|---|---|---|
| `retrySemantics` | `"NEVER"` | `"KEYED"` | 백엔드가 키를 읽는지 |
| `frontend.retryBudget` | `0` (조립이 강제) | `1` | 백엔드는 503 `IDEMPOTENCY_UNAVAILABLE`(작업 실행 전 거절)에 "같은 키로 다시"를 요구한다. 실행기는 이 답에만 같은 키로 스스로 다시 보낸다. 실제 상한은 min(`retryBudget`, 앱 `MAX_RETRY_ATTEMPTS`(기본 2), 하드 상한 2)이다. 응답을 잃은 뒤에는 스스로 다시 보내지 않는다 |
| `commandRecovery` | `null` | `{ mode: "IDEMPOTENCY_REPLAY", operationIdentityField: "idempotencyKey" }` | 조립이 `KEYED`에 요구한다. `operationIdentityField`는 같은 요청을 알아보는 값의 이름이다. 실행기는 intent의 `idempotencyKey`를 `Idempotency-Key` 헤더로 보낸다. 이 칸은 FE-REG-API에 기록되고 실행기는 읽지 않는다 |
| 호출 문맥의 `intent` | 넘긴다(키 없음) | 넘긴다(키 있음) | 뮤테이션 조정자가 만든 intent를 input → gateway → 바인딩까지 그대로 넘긴다(생성된 `<Base>CommandContext`가 `intent`를 필수로 받는다). 빠뜨리면 `KEYED`는 보내기 전에 거부된다 |
| `commandEffect.classifyStatus` | `() => "NOT_APPLIED"` | 같다 | 생성된 create의 401은 보안 필터 체인, 403은 use case의 `@RequiresPermission` 프록시, 429는 rate-limit interceptor(`preHandle`)가 use case 전에 낸다. use case 안에서 `AuthorizationPort`를 쓰기 뒤에 부르게 바꾸면 403이 쓰기 뒤에도 나올 수 있다. 그때는 이 칸을 지운다(= `MAYBE_APPLIED`) |
| `commandEffect.refusedBeforeWrite` | `["<FEATURE>_INVALID"]` | 같다 | 이름 규칙을 트랜잭션 전에 검사한다(4절) |
| `acceptedStatuses` | `[201]` | `[201]` | `ResponseEntity.created`. 같은 키 재생도 첫 요청과 같은 201이다 |
| 결과 불명 화면 | 확인만. 다시 보내기 버튼 없음 | "같은 요청으로 다시 보내기"가 같은 키로 보낸다 | 키 없는 재전송은 서버가 새 요청으로 본다 |
| 생성 테스트 | 응답 유실 → 결과 불명, 다시 보내기 없음, 키 헤더 없음 | 응답 유실 → 같은 키로 다시 보내기. 503 `IDEMPOTENCY_UNAVAILABLE` → 같은 키로 1회 자동 재전송 | `tests/features/<id>/<base>-create-page.test.tsx`, `<base>-http-gateway.test.ts` |
- 테스트 하네스의 재시도 상한: 생성된 gateway 테스트는 앱 기본값(`maxRetryAttempts: 2`)으로 돈다. 그래야 `retryBudget: 1`의 재전송이 보인다. 페이지 테스트(`<base>-test-app.tsx`)는 실패를 바로 보이려고 `MAX_RETRY_ATTEMPTS: 0`이다.
**정본**: 백엔드가 멱등 키 요청에 어떻게 답하는지는 `clean-architecture-backend-template/docs/web/http-contract.md` §2(멱등성 응답)다. 여기에 표를 옮기지 않는다.
**어디에 적나**: `contracts/<base>-contract-contribution.ts`의 `retrySemantics`, `commandRecovery`, `frontend.retryBudget`. 다른 파일에 다시 적지 않는다.
+33 -11
View File
@@ -1,24 +1,27 @@
# create:feature 참조
모든 merge 게이트를 통과하도록 만든 가장 작은 기능을 만드는 명령이다. 정본은 `scripts/create-feature.ts`다.
모든 merge 게이트를 통과하는 가장 작은 기능을 만드는 명령이다. 정본은 `scripts/create-feature.ts`이고, `--with-create`가 더하는 부분은 `scripts/create-feature-write-slice.ts`다.
`test:feature-scaffold`가 생성한 기능으로 `config/ci/gates.json`의 merge 단계 명령을 돌려 확인한다. 브라우저 게이트(FE-GATE-008·009의 브라우저 명령)와 `test:system`은 빼고 돈다. 뺀 명령과 이유는 `scripts/lib/feature-scaffold-drill.ts`에 있다.
템플릿 문자열이 그 파일 안에 있고, 참조 기능을 import하지 않는다. 그래서 참조 기능을 지운 프로젝트에서도 동작한다.
템플릿 문자열이 두 파일 안에 있고, 참조 기능을 import하지 않는다. 그래서 참조 기능을 지운 프로젝트에서도 동작한다.
## 사용법
```bash
corepack pnpm create:feature <id> [--context <context id>] [--package @scope/name@x.y.z --digest sha256:<64 hex> --revision <hex>]
corepack pnpm create:feature <id> [--context <context id>] [--with-create [--keyed]] [--package @scope/name@x.y.z --digest sha256:<64 hex> --revision <hex>]
```
| 인자 | 규칙 |
|---|---|
| `<id>` | 케밥 표기, 40자 이하. 기존 기능·context ID와 겹치면 거부 |
| `--context` | 기존 context ID. 없으면 `<base>-context`를 새로 만든다 |
| `--with-create` | 짝 백엔드 `new-feature.sh`의 작성(`POST /<plural>`)·상세(`GET /<plural>/{id}`)와 그 페이지를 더한다. 작성은 `NEVER` |
| `--keyed` | `--with-create`와 함께만. 작성을 `KEYED`로 만든다. 백엔드 create를 멱등성 executor 뒤에 둔 뒤에 쓴다 |
| `--package` | `@scope/name@<정확한 버전>`. `--digest`, `--revision`과 함께만 |
| `--digest` | `sha256:` + 소문자 hex 64자리 |
| `--revision` | 소스 리비전. 소문자 hex 7~64자리 |
- `<base>`: ID에서 끝의 `-feature`를 뗀 것이다. `invoice-feature`면 `invoice`. 모든 전역 ID의 접두어가 된다.
- API 경로: 짝 백엔드 `new-feature.sh`와 같은 규칙이다. `<base>`의 camel 표기 뒤에 s, x, ch, sh로 끝나면 `es`, 자음+y로 끝나면 y를 `ies`로, 그 밖에는 `s`를 붙인다. `invoice` → `/invoices`, `purchase-order` → `/purchaseOrders`, `company` → `/companies`. 백엔드의 `api-base-path`는 `API_BASE_URL`에 붙인다.
- 패키지 인자가 없으면 자리표시자 신원을 쓰고 표준 오류로 경고한다.
- 패키지 인자가 있으면 계약 조립기와 같은 신원 검사(`composeContractContributions`)로 형식을 확인한다.
@@ -54,24 +57,41 @@ corepack pnpm create:feature <id> [--context <context id>] [--package @scope/nam
- `presentation/<base>-feature-runtime.ts`: 지연 로드 페이지 표
- `presentation/<base>-routes.ts`: route ID → URL 함수(`buildRouteUrl`)
- `presentation/use-<base>-items.ts`: 쿼리 바인딩
- `presentation/<base>-list-page.tsx`: `CollectionPage` 목록 페이지
- `presentation/<base>-list-page.tsx`: `CollectionPage` 목록 페이지. 결과 수는 `meta.page.total`
`--with-create`가 더하는 파일:
- `presentation/<base>-route-codecs.ts`: 상세 라우트 params codec
- `presentation/use-<base>-item.ts`: 상세 쿼리
- `presentation/use-<base>-create.ts`: 작성 뮤테이션 정책(`commandMutationIdentity`)
- `presentation/<base>-form.ts`: 폼 스키마. 이름 길이는 요청 스키마의 상수(`<BASE>_NAME_MAX_LENGTH` = 백엔드 `NAME_MAX_LENGTH` 100)를 쓴다
- `presentation/<base>-detail-page.tsx`: `DetailPage`
- `presentation/<base>-create-page.tsx`: `FormPage`. 저장하면 상세를 연다. 결과 불명이면 `AsyncSurface`를 보인다
`domain/`은 만들지 않는다. 업무 규칙이 생기면 사람이 만든다.
기능 테스트 폴더 `tests/features/<id>/`:
- `<base>-feature-input.test.ts`: input과 mapper 단위 테스트
- `<base>-list-page.test.tsx`: 라우터를 거치는 페이지 테스트(목록, 빈 목록, 실패 후 다시 시도)
- `<base>-test-app.tsx`: 앱 전체를 조립해 로그인하고 URL로 들어가는 도우미. 페이지 테스트가 같이 쓴다
- `<base>-feature-input.test.ts`: input 단위 테스트
- `<base>-list-page.test.tsx`: 라우터를 거치는 페이지 테스트(목록, `meta.page.total`, 빈 목록, 실패 후 다시 시도)
- `<base>-http-gateway.test.ts`: 짝 백엔드 본문을 손으로 적은 gateway 테스트. 하네스의 재시도 상한은 앱 기본값 2다
- `<base>-create-page.test.tsx`(`--with-create`): 201 저장 뒤 상세, 400 `<FEATURE>_INVALID` 필드 오류와 다시 저장, 응답을 잃은 저장(`NEVER`는 다시 보내기 없음, `KEYED`는 같은 키로 다시 보내기)
기능 폴더 밖:
- `src/contexts/<base>-context/context-module.ts`: 새 context일 때만
- `artifacts/tests/a11y-manual/<ROUTE_ID>.md`: pending 기록
- `artifacts/tests/a11y-manual/<ROUTE_ID>.md`: 라우트마다 pending 기록
## 뼈대 모양
- 라우트 1개: 파라미터·검색값 없는 목록, `session-required`, `feature-boundary`.
- GET 1개: `SAFE`, `EXTERNAL_BEARER`, 응답은 항목 배열.
- GET 1개: `SAFE`, `EXTERNAL_BEARER`, 응답은 Envelope 안의 항목 배열. 목록 값은 `{ items, total }`이다.
- `--with-create`: 라우트 `<BASE>_DETAIL`(`<목록>/items/:<base>Id`)·`<BASE>_CREATE`(`<목록>/new`), operation `<BASE>_GET_ITEM`·`<BASE>_CREATE_ITEM`.
- 작성 `NEVER`: `retryBudget: 0`, 멱등 키 없음. 응답을 잃으면 결과 불명이고 다시 보내기 버튼이 없다.
- 작성 `KEYED`(`--keyed`): `commandRecovery` `IDEMPOTENCY_REPLAY`, `retryBudget: 1`(503 `IDEMPOTENCY_UNAVAILABLE` 뒤 같은 키로 한 번).
- 둘 다 `acceptedStatuses: [201]`, `refusedBeforeWrite: ["<BASE>_INVALID"]`, `classifyStatus`는 401·403·429를 `NOT_APPLIED`로 본다. 값과 이유는 [02 결정표 3절](../02-decision-tables.md#3-재시도-의미).
- 모든 operation이 `responseEnvelope: "ENVELOPE_V1"`이다.
- 쿼리 1개: `LIST_STANDARD` profile.
- 무효화 topic 1개, namespace 1개, edge 1개.
- 빈 배열 응답은 공유 빈 상태 화면으로 그린다. `tests/e2e/accessibility.spec.ts`는 이 목록 조회에 빈 목록을 Envelope 모양으로 답하고, 경고 상자가 없는지 본 뒤 axe를 돌린다. 그래서 생성한 라우트는 빈 상태 화면으로 검사된다.
@@ -127,14 +147,16 @@ corepack pnpm generate:feature-index
- `tests/unit/create-feature.test.ts` (`test:unit`, FE-GATE-005)
- 렌더 결과만 본다. 저장소를 건드리지 않는다.
- 접두어, 참조 기능 이름이 없음, topic 형식과 충돌, `navigationOrder`, 거부 조건, 덮어쓰기 거부와 되돌리기.
- 백엔드 경로 규칙, `--with-create`·`--keyed`의 descriptor 값, 모든 operation의 Envelope 선언.
- 생성한 context 선언을 임시 폴더에 써서 생성기의 선언 읽기(`createFileSystemDeclarationSource`)로 읽고, 그 모듈을 import해 라우트 루트가 기능 라우트를 모두 받는지 앱 모듈 조립으로 확인한다.
- `test:feature-scaffold` (FE-GATE-020)
- 저장소 복사본에 기능 하나를 만들고 커밋한 뒤 게이트를 돈다.
- 저장소 복사본에 기능 둘(기본 하나, `--with-create --keyed` 하나)을 만들고 커밋한 뒤 게이트를 돈다.
- 타입, lint, 아키텍처, 레지스트리, i18n, 디자인 시스템, 진단, 문서, unit, component, integration, 기능 테스트, 커버리지, CI 계약, 빌드.
- `test:sample-removal` (FE-GATE-020)
- 참조 기능을 지운 복사본에서 이 명령으로 기능을 만들고 같은 게이트를 다시 돈다. 명령이 참조 기능에 기대지 않는다는 증거다.
- 참조 기능을 지운 복사본에서 이 명령(`--with-create`)으로 기능을 만들고 같은 게이트를 다시 돈다. 명령과 쓰기 slice가 참조 기능에 기대지 않는다는 증거다.
## 알려진 한계
- `--context reference-context`로 참조 context에 넣으면 참조 기능 테스트 tests/features/reference-feature/installed-context-routing.test.ts가 깨진다. 그 테스트는 참조 context의 라우트 수를 정확히 비교한다.
- `--context reference-context`로 참조 context에 넣은 기능은 경로가 `/examples/reference-resources/<base>`다. 참조 기능을 지우면 context가 남고 그 경로가 제거 드릴의 잔여 검사에 걸린다. 남길 기능은 제품 context에 둔다.
- 드릴은 `check:bundle`(FE-GATE-012), 브라우저 테스트(`test:a11y`, `test:e2e`)를 돌리지 않는다.
- 새 context는 앱이 하나일 때만 만든다. 앱이 여럿이면 `--context`로 기존 context를 고른다.
+5 -1
View File
@@ -42,6 +42,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| `contract package <packageId>@<version> is not a pinned identity: <reason>` | 패키지 신원 형식. `<reason>` 예: `<id>: package version must be exact SemVer`, `<id>: package digest`, `<id>: package sourceRevision`, `<id>: packageId` | `--package`, `--digest`, `--revision` |
| `--package, --digest and --revision go together. ...` | 셋 중 일부만 줬다 | 셋을 함께 준다 |
| `--package must be @scope/name@<exact version>. ...` | 버전 없는 패키지 이름 | `@scope/name@1.2.3` 꼴 |
| `--keyed needs --with-create. ...` | `--keyed`만 줬다 | `--with-create --keyed` |
| `refusing to overwrite: <paths>` | 쓸 파일이나 기능 폴더가 이미 있다 | 그 경로를 확인하고 지우거나 다른 ID |
| `the feature index generator rejected the feature, nothing was kept:` | 생성기가 거부했다. 만든 파일은 모두 지웠다 | 뒤따르는 생성기 메시지(아래 절) |
@@ -82,7 +83,8 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
|---|---|---|
| `Invalid or duplicate schema definition: <schemaId>` | 스키마 ID 중복 또는 메타 형식 | `contracts/<base>-schema-metadata.ts`. 접두어를 붙인다 |
| `duplicate operation: <operationId>` (계약 조립 오류의 `reason`) | operation ID 중복 | `contracts/<base>-contract-contribution.ts`. 접두어를 붙인다 |
| `FE-REG-API.<operationId>.requestSchema references unknown FE-REG-SCHEMA.schemaId=<id>` | descriptor의 입력 스키마 ID가 스키마 메타데이터에 없다 (`responseSchema`도 같은 꼴) | `contracts/<base>-schema-metadata.ts` |
| `FE-REG-API.<operationId>.requestSchema references unknown FE-REG-SCHEMA.schemaId=<id>` | descriptor의 입력 스키마 ID가 스키마 메타데이터에 없다 (`responseSchema`, `problemSchema`도 같은 꼴. 실패 본문 행은 `boundary: "api-problem"`) | `contracts/<base>-schema-metadata.ts` |
| `<schemaId>: row <boundary>, used as <boundary>` (`tests/unit/schema-metadata-policy.test.ts`) | 스키마 메타 행의 `boundary`가 그 스키마가 쓰인 자리와 다르다. `no FE-REG-SCHEMA row`는 쓰이는데 행이 없다 | `contracts/<base>-schema-metadata.ts` |
| `Unregistered route codec: <codecId>` | URL 함수가 기능 codec을 `buildRouteUrl`에 넘기지 않았다 | `presentation/<base>-routes.ts` |
| `contract package <packageId> is declared, but no loaded contribution pins it` | 계약 `contractPackages`에 적은 패키지를 계약 기여가 쓰지 않는다 | `contracts/<base>-contract-contribution.ts`의 `source` |
| `<id> contributes contract package <packageId>, which no installed feature declares in contracts.contractPackages` | 계약 기여의 신원과 계약 선언의 신원이 다르다 | 둘 다 `<BASE>_CONTRACT_PACKAGE` 하나를 쓰게 한다 |
@@ -101,6 +103,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| `<id>/<operationId>: <GET·HEAD> is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>` | 읽기에 `KEYED`나 `NEVER`를 적었다 | V3 `retrySemantics`. 재시도를 막으려면 `frontend.retryBudget: 0` |
| `<id>/<operationId>: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` |
| `<id>/<operationId>: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` |
| `<id>/<operationId>: responseEnvelope NONE, but <other> in the same contribution reads ENVELOPE_V1; ...` | 한 계약 기여 안에서 operation 하나만 응답 모양이 다르다. 손으로 더한 operation에 `responseEnvelope` 줄을 빠뜨린 경우다 | 그 operation에 `responseEnvelope: "ENVELOPE_V1" as const`를 적는다. 정말 다른 백엔드면 기여를 나눈다 |
| `<id>: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `<BASE>_CONTRACT_PACKAGE.version` |
### 라우트·context
@@ -123,6 +126,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| `Query invalidation topic is invalid.` | topic 형식이 `qinv.` + 26자가 아니다 | `defineQueryInvalidationTopic` 값 |
| `Orphan invalidation topic: <topic>` | edge가 없는 topic | 계약 `invalidation.edges` |
| `Unregistered server-state profile: <profileId>` | 없는 profile | 쿼리 바인딩의 `profileId` |
| `commandMutationIdentity: <operationId> is a GET; a mutation binds a write operation` | 뮤테이션 정책에 읽기 descriptor를 넘겼다 | 정책의 `commandMutationIdentity(...)` 인자를 쓰기 descriptor로 |
### 조립 기여
+7 -7
View File
@@ -3,7 +3,7 @@
기능을 만들 때 쓰는 패턴과, 그 패턴의 정의와 예제가 어디 있는지 적는다.
- **정의**: 플랫폼(기능 밖)에서 패턴을 제공하는 파일.
- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `참조 기능`은 src/features/reference-feature/다. 참조 기능은 지울 수 있으므로 그 경로는 백틱 없이 적는다. 백틱 경로는 문서 검사(`verify:documentation`)가 존재를 확인한다.
- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature <id> --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `참조 기능`은 src/features/reference-feature/다(Envelope가 아닌 problem details 모양). 참조 기능은 지울 수 있으므로 그 경로는 백틱 없이 적는다. 백틱 경로는 문서 검사(`verify:documentation`)가 존재를 확인한다.
- 예제가 없는 패턴은 **없음**이라고 적었다. 그 패턴은 정의를 읽고 직접 쓴다.
참조 기능은 예제일 뿐이다. 복사해 이름을 바꾸지 않는다. 모양을 보고 생성 뼈대에 옮긴다.
@@ -27,7 +27,7 @@
| 라우트 선언 | `src/contracts/routes.ts`, `src/contracts/route-runtime-contract.ts` | 생성 뼈대 계약 `routes`, `routeRuntimeContracts` | 조립(중복 route ID), `check:registries`(경로·chunk 중복) |
| context 라우트 적재 | `src/platform/routing/context-route-module.ts` | 생성 뼈대 `context-routes.ts` | context 적재(계약에 없는 handle) |
| route ID로 URL 만들기 | `src/presentation/routes/route-codecs.ts`의 `buildRouteUrl` | 생성 뼈대 `presentation/<base>-routes.ts`, 참조 기능 `presentation/reference-routes.ts` | 타입(기능의 route ID만 받음) |
| 파라미터·검색값 codec | `src/presentation/routes/route-codecs.ts` | 참조 기능 `presentation/reference-route-codecs.ts` | 해석 실패 시 잘못된 경로 화면 |
| 파라미터·검색값 codec | `src/presentation/routes/route-codecs.ts` | 쓰기 slice `presentation/<base>-route-codecs.ts`(상세 params), 참조 기능 `presentation/reference-route-codecs.ts` | 해석 실패 시 잘못된 경로 화면 |
| URL 검색값 읽기 | `src/presentation/routes/route-input.tsx`의 `useRouteInput` + 검색값 codec | 참조 기능 `presentation/reference-routes.ts` | 해석 실패 시 잘못된 경로 화면 |
| URL 검색값을 바꾸는 폼 | `buildRouteUrl`의 `search`, 디자인 시스템 `SearchField`, `CollectionPage`의 `toolbar` | 기능 예제 없음. 아래 짧은 예 | 라우터를 거치는 페이지 테스트 |
@@ -84,7 +84,7 @@ const search = (q: string) =>
| 검증 생략 | `src/contracts/unvalidated-payload.ts`의 `unvalidatedPayload` | 없음 (기능 예제) | 이유가 비면 throw, `listUnvalidatedPayloads`가 목록을 보임 |
| DTO → 화면 값 mapper | `src/contracts/boundary-mapper.ts`의 `BoundaryMappingResult` | 생성 뼈대 `contracts/<base>-mapper.ts` | 타입 검사 |
| gateway port + HTTP 어댑터 | `src/adapters/http/index.ts`의 `createFeatureHttpBinding`, `defineFeatureHttpOperationForRoutes` | 생성 뼈대 `adapters/<base>-http-gateway.ts` | 음성 타입 fixture (operation ID, route ID, 입력) |
| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 |
| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 쓰기 slice `adapters/<base>-http-gateway.ts`(400 `<BASE>_INVALID` → 이름 칸), 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 |
| 결과와 실패 | `src/contracts/result.ts`, `src/contracts/errors.ts` | 생성 뼈대 `application/<base>-feature-api.ts` | `FailureKind` 닫힌 어휘(타입) |
| 실패 → 화면 행동 | `src/contracts/errors.ts`의 `action` | 참조 기능 `presentation/use-reference-failure-action.ts` | 페이지 테스트 |
| 파일 업로드 (짝 백엔드 Fileserver) | `src/adapters/http/index.ts`의 `createFileserverUploadClient` (`POST /v1/files`) | 없음 (기능 예제). 조립은 [02 결정표 7절](../02-decision-tables.md#7-파일-업로드) | `tests/integration/fileserver-upload.test.ts` |
@@ -93,10 +93,10 @@ const search = (q: string) =>
| 패턴 | 정의 | 예제 | 검사 |
|---|---|---|---|
| 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use-<base>-items.ts` | profile ID (실행 때). `operationId`는 `string`이라 묶이지 않음 |
| 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use-<base>-items.ts` | profile ID (실행 때). `owner`·`operationId`는 읽는 곳이 없는 `@deprecated` 칸이라 적지 않는다 |
| 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) |
| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책 | 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 기능 테스트 |
| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만 |
| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/<base>-contract-contribution.ts`, `presentation/use-<base>-create.ts`), 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름), 기능 테스트 |
| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/<base>-create-page.tsx`, 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만(쓰기 slice는 `<base>-create-page.test.tsx`) |
| 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (참조 기능은 생성 명령만 있다) | — |
| 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 |
| 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (참조 기능은 커서 필터만, 다음 커서 없음) | 런타임 테스트만 |
@@ -108,7 +108,7 @@ const search = (q: string) =>
|---|---|---|---|
| 페이지 템플릿 | `src/presentation/templates/page-templates.tsx` | 생성 뼈대 `CollectionPage`, 참조 기능 페이지 4개 | `page-templates-own-layout-only` |
| 비동기 상태 화면 | `src/presentation/components/async-surface.tsx`의 `AsyncSurface` | 생성 뼈대 목록 페이지 | 페이지 테스트 |
| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 참조 기능 `presentation/reference-resource-form.ts`와 폼 페이지 | 페이지 테스트(422 허용 필드, 이탈 확인) |
| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 쓰기 slice `presentation/<base>-form.ts`와 `<base>-create-page.tsx`, 참조 기능 `presentation/reference-resource-form.ts`와 폼 페이지 | 페이지 테스트(서버 필드 오류, 이탈 확인) |
| 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/<base>-message-catalog.ts` | `lint`(문구 literal), `check:i18n`(ko-KR·en-US 키) |
| 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 참조 기능 403 화면 테스트 | 가드 테스트. 역할·권한 힌트 예제는 없음 |
File diff suppressed because it is too large Load Diff
+490 -161
View File
File diff suppressed because it is too large Load Diff
+11 -3
View File
@@ -21,7 +21,8 @@ import {
/**
* U7. A feature from `create:feature` passes the merge gates without an edit
* and breaks no other test. A copy of the repository, sample feature
* included, gets one generated feature and then runs the merge stage of its
* included, gets a default feature and a `--with-create --keyed` one, then
* runs the merge stage of its
* config/ci/gates.json: every command except those
* SCAFFOLD_DRILL_EXCLUDED_SCRIPTS names with a reason (the browser gates,
* test:system, the install check and the removal drills). 1103/12-02: this
@@ -35,6 +36,8 @@ import {
* (decision 4), which proves the command needs nothing from it.
*/
const FEATURE_ID = "scaffold-feature";
/** 1103/09-06. The `--with-create --keyed` slice, in its own context. */
const WRITE_FEATURE_ID = "scaffold-write-feature";
const REPORT = "artifacts/tests/feature-scaffold.xml";
const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath");
@@ -57,8 +60,13 @@ try {
...REMOVAL_FIXTURE_DOCUMENT_TARGETS,
]);
const created = check("create-feature", "create:feature", [FEATURE_ID]);
const checks: RemovalCheck[] = [created];
if (created.passed) {
const createdWrite = check("create-feature-write", "create:feature", [
WRITE_FEATURE_ID,
"--with-create",
"--keyed",
]);
const checks: RemovalCheck[] = [created, createdWrite];
if (created.passed && createdWrite.passed) {
// Commits the copy with the feature, as a project would: git-based
// checks (git grep, git ls-files) then see the feature's files.
sealRemovalFixtureRepository(fixtureRoot);
+3
View File
@@ -465,8 +465,11 @@ try {
// from create:feature and runs the same gates again: the command and the
// feature it writes need nothing from the sample.
if (isSample) {
// 1103/09-06. With the write slice (NEVER), which needs nothing from
// the sample either.
const created = check("scaffold-create-feature", "create:feature", [
"scaffold-feature",
"--with-create",
]);
checks.push(created);
if (created.passed) {
@@ -644,6 +644,28 @@ function assertRefusedBeforeWrite(
}
}
/**
* 1103/16-01. `responseEnvelope` is per operation so one app can read two
* backends, but one contribution is one backend's package: its operations
* share one frame. A hand-added operation without the line used to pass every
* gate and the MSW scenarios (they answer whatever the descriptor declares)
* and read the real backend's Envelope as a DTO. Missing and `"NONE"` are the
* same frame. Two backends take two contributions.
*/
function assertSameWireFrame(
installed: InstalledHttpContract<unknown, unknown, unknown>,
first: InstalledHttpContract<unknown, unknown, unknown> | undefined,
featureId: string,
): void {
if (first === undefined) return;
const frame = installed.contract.responseEnvelope ?? "NONE";
const firstFrame = first.contract.responseEnvelope ?? "NONE";
if (frame === firstFrame) return;
fail(
`${featureId}/${installed.contract.operationId}: responseEnvelope ${frame}, but ${first.contract.operationId} in the same contribution reads ${firstFrame}; a contribution is one backend's package, so declare the same responseEnvelope on every operation or split the contribution per backend`,
);
}
function assertEventContract(
event: InstalledEventContract<unknown, unknown>,
featureId: string,
@@ -1006,6 +1028,7 @@ export function composeContractContributions(
featureId,
);
assertHttpContract(snapshot, featureId, authProfiles);
assertSameWireFrame(snapshot, installedHttp[0], featureId);
const operationId = snapshot.contract.operationId;
const previous = httpByOperationId.get(operationId);
if (previous) fail(`duplicate operation: ${operationId}`);
+3 -1
View File
@@ -8,7 +8,9 @@ export type SchemaDefinition = Readonly<{
| "route-search"
| "route-search-api-request"
| "api-request"
| "api-response";
| "api-response"
/** 1103/16-04. An operation's failure body (`problemValidator`). */
| "api-problem";
owner: string;
runtime: "zod";
schemaVersion?: number;
+48 -3
View File
@@ -8,6 +8,7 @@ import {
} from "./query-keys.ts";
import type { CacheScopeSnapshot } from "./server-state-scope.ts";
import type { MutationIntent } from "./mutation-intent.ts";
import type { HttpMethod, RetrySemantics } from "./external-contract-runtime.ts";
/**
* §10.2. The four fixed profiles. A feature selects one by ID; it never
@@ -173,8 +174,14 @@ type QueryDefinitionNamespace =
export type QueryDefinition<Input, Value> = Readonly<{
definitionId: string;
definitionVersion: number;
owner: string;
operationId: string;
/**
* @deprecated 1103/16-06. Never read: the bound query does not carry it,
* and the HTTP execution records the descriptor's own operation id. Leave
* it out; it is removed in a later release.
*/
owner?: string;
/** @deprecated 1103/16-06. Never read, like `owner`. */
operationId?: string;
profileId: ServerStateProfileId;
/**
* 03-01. `"NONE"` declares a query no save invalidates (a static lookup).
@@ -258,12 +265,50 @@ export const MUTATION_COORDINATOR_BOUNDS = Object.freeze({
settledRetentionMs: 0,
});
/**
* 1103/16-05, 1101/03-03. The two values a mutation policy shares with its
* command's HTTP descriptor, read from the descriptor rather than written a
* second time: the operation id its intent names (the executor refuses an
* intent whose id is not its descriptor's, before sending, reported as a
* missing idempotency key) and whether the intent carries a key (a KEYED
* command only). Spread it into the policy:
*
* ...commandMutationIdentity(INVOICE_CREATE_CONTRACT),
*
* A misspelt descriptor constant fails the type check; a hand-written id
* string fails only when the form sends.
*/
export function commandMutationIdentity(
command: Readonly<{
contract: Readonly<{
operationId: string;
method: HttpMethod;
retrySemantics: RetrySemantics;
}>;
}>,
): Readonly<{ operationId: string; requiresIdempotencyKey: boolean }> {
const { operationId, method, retrySemantics } = command.contract;
if (method === "GET" || method === "HEAD") {
throw new TypeError(
`commandMutationIdentity: ${operationId} is a ${method}; a mutation binds a write operation`,
);
}
return Object.freeze({
operationId,
requiresIdempotencyKey: retrySemantics === "KEYED",
});
}
export type BoundMutation<Input, Value> = Readonly<{
definitionId: string;
definitionVersion: number;
operationId: string;
requiresIdempotencyKey: boolean;
owner: string;
/**
* @deprecated 1103/16-06. The mutation coordinator never reads it. Leave
* it out; it is removed in a later release.
*/
owner?: string;
duplicatePolicy: MutationDuplicatePolicy;
scope: CacheScopeSnapshot;
execute(
@@ -50,4 +50,14 @@ export const REFERENCE_SCHEMA_METADATA = Object.freeze({
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
// 1103/16-04. FE-REG-API's problemSchema references this row.
ReferenceProblem: Object.freeze({
schemaId: "ReferenceProblem",
boundary: "api-problem",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
});
@@ -14,8 +14,10 @@ import type {
ReferenceListFilters,
} from "../application/reference-feature-api.ts";
import type { ReferenceResourceView } from "../contracts/reference-mapper.ts";
import { CREATE_REFERENCE_RESOURCE_CONTRACT } from "../contracts/reference-feature-contract-contribution.ts";
import {
bindQuery,
commandMutationIdentity,
type BoundMutation,
type QueryResultMeasure,
} from "../../../contracts/server-state.ts";
@@ -53,9 +55,9 @@ function measureResourceList(
const REFERENCE_CREATE_MUTATION_POLICY = Object.freeze({
definitionId: "reference-resource-create-v1",
definitionVersion: 1,
operationId: "CREATE_REFERENCE_RESOURCE",
requiresIdempotencyKey: true,
owner: REFERENCE_FEATURE_ID,
// 1103/16-05. The operation id and the key requirement are the
// descriptor's, so a misspelt id cannot pass the type check.
...commandMutationIdentity(CREATE_REFERENCE_RESOURCE_CONTRACT),
duplicatePolicy: "REJECT_WHILE_ACTIVE" as const,
invalidate: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]),
});
@@ -86,9 +88,7 @@ export function useReferenceDetail(resourceId: string) {
{
definitionId: "reference-resource-detail-v1",
definitionVersion: 1,
owner: REFERENCE_FEATURE_ID,
namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE,
operationId: "GET_REFERENCE_RESOURCE",
profileId: "DETAIL_STANDARD",
measureResult: measureResourceView,
execute: (selectedResourceId: string, { signal }) =>
@@ -120,9 +120,7 @@ export function useReferenceFeature() {
{
definitionId: "reference-resource-list-v1",
definitionVersion: 1,
owner: REFERENCE_FEATURE_ID,
namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE,
operationId: "LIST_REFERENCE_RESOURCES",
profileId: "LIST_STANDARD",
measureResult: measureResourceList,
execute: (selectedFilters: ReferenceListFilters, { signal }) =>
@@ -55,6 +55,37 @@ describe("scope-bound query commit fence", () => {
);
});
// 1103/16-06. `owner` and `operationId` were required and nothing read
// them: the bound query never carried them. A definition leaves them out.
it("binds the same query without the owner and operation id it never read", () => {
const scope = scopeSnapshot();
const bound = bindQuery(
{
definitionId: "resource-detail-v1",
definitionVersion: 1,
namespace: "resource",
namespaceVersion: 1,
profileId: "DETAIL_STANDARD" as const,
measureResult: measureOne,
execute: async () => ({ ok: true as const, value: "value" }),
},
"resource-1",
scope,
);
expect(bound.queryKey).toEqual([
"query",
2,
"resource",
1,
"scope-fingerprint-0001",
1,
"scope-identity-token-0001",
]);
expect(Object.keys(bound)).not.toContain("owner");
expect(Object.keys(bound)).not.toContain("operationId");
});
it("discards a successful result whose scope was fenced during execution", async () => {
const client = queryClient();
const scope = scopeSnapshot();
@@ -1,11 +1,18 @@
import { describe, expect, it } from "vitest";
import { TEMPLATE_APP_MODULE } from "../../../src/apps/template-app.ts";
import { REFERENCE_FEATURE_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
import { createAppRouteModules } from "../../../src/platform/routing/context-route-module.ts";
// 16-02. Other installed features bring their own contexts; only the
// reference context is this sample's to check.
const REFERENCE_CONTEXT_ID = "reference-context";
// X1 (2026-11-04). A product feature may join the reference context
// (`create:feature <id> --context reference-context`) and load its routes with
// it; only the reference feature's own routes are this sample's to check.
const REFERENCE_ROUTE_IDS: ReadonlySet<string> = new Set(
Object.keys(REFERENCE_FEATURE_CONTRACT.routes),
);
describe("installed context routing", () => {
it("boots one bounded-context entry instead of flattening feature routes", () => {
@@ -19,7 +26,9 @@ describe("installed context routing", () => {
(module) => module.id === REFERENCE_CONTEXT_ID,
);
expect(context).toBeDefined();
const routes = await context!.loadRoutes();
const routes = (await context!.loadRoutes()).filter((route) =>
REFERENCE_ROUTE_IDS.has(String(route.id)),
);
expect(routes.map((route) => [route.id, route.path])).toEqual([
["REFERENCE_RESOURCE_LIST", "/examples/reference-resources"],
["REFERENCE_RESOURCE_DETAIL", "/examples/reference-resources/items/:resourceId"],
+2
View File
@@ -93,6 +93,8 @@ describe("FE-REG-API rows projected from HTTP descriptors", () => {
...TEST_LIST_HTTP_CONTRACT,
contract: {
...TEST_LIST_HTTP_CONTRACT.contract,
// 1103/16-01. One contribution reads one frame.
responseEnvelope: "ENVELOPE_V1" as const,
outputValidator: unvalidatedPayload(
"TestEntityListPayload",
"typed by the package",
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { commandMutationIdentity } from "../../src/contracts/server-state.ts";
import {
TEST_CREATE_HTTP_CONTRACT,
TEST_LIST_HTTP_CONTRACT,
} from "../helpers/external-contract-fixture.ts";
/**
* 1103/16-05, 1101/03-03. A mutation policy used to restate its command's
* operation id and key requirement as free values. A misspelt id passed the
* type check and the registries, and the executor refused every save before
* sending, as a missing idempotency key. The policy now takes both from the
* HTTP descriptor.
*/
describe("commandMutationIdentity", () => {
it("takes the operation id and the key requirement from a KEYED descriptor", () => {
expect(commandMutationIdentity(TEST_CREATE_HTTP_CONTRACT)).toEqual({
operationId: "TEST_CREATE_ENTITY",
requiresIdempotencyKey: true,
});
});
it.each(["NEVER", "IDEMPOTENT"] as const)(
"sends no key for a %s command",
(retrySemantics) => {
expect(
commandMutationIdentity({
contract: { ...TEST_CREATE_HTTP_CONTRACT.contract, retrySemantics },
}),
).toEqual({ operationId: "TEST_CREATE_ENTITY", requiresIdempotencyKey: false });
},
);
it("refuses a read descriptor", () => {
expect(() => commandMutationIdentity(TEST_LIST_HTTP_CONTRACT)).toThrow(
"commandMutationIdentity: TEST_LIST_ENTITIES is a GET; a mutation binds a write operation",
);
});
});
+248
View File
@@ -1,17 +1,20 @@
import { access, mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import {
CreateFeatureError,
parseRequest,
planFeature,
randomTopicSuffix,
writeFeatureFiles,
type FeatureRequest,
type InstalledFacts,
} from "../../scripts/create-feature.ts";
import { createFileSystemDeclarationSource } from "../../scripts/generate-product-feature-index.ts";
import { PLACEHOLDER_CONTRACT_PACKAGE_DIGEST } from "../../src/contracts/deployment-admission.ts";
/**
@@ -155,6 +158,251 @@ describe("create:feature rendering", () => {
files.get("tests/features/invoice-feature/invoice-http-gateway.test.ts"),
).toContain('success: true, data: [{ id: "item-1", name: "First item" }]');
});
// 1103/03-07. The paired backend's new-feature.sh maps /<plural> (its
// camel-case name plus s, es or ies); the frontend's list reads the same
// resource path. The backend's api-base-path belongs in API_BASE_URL.
it.each([
["invoice-feature", "/invoices"],
["purchase-order-feature", "/purchaseOrders"],
["batch-feature", "/batches"],
["box-feature", "/boxes"],
["company-feature", "/companies"],
["day-feature", "/days"],
["status-feature", "/statuses"],
])("lists %s at the backend scaffold's resource path %s", (id, apiPath) => {
const base = id.slice(0, -"-feature".length);
const contribution = plan({ id }).files.get(
`src/features/${id}/contracts/${base}-contract-contribution.ts`,
);
expect(contribution).toContain(`const API_PATH = "${apiPath}";`);
});
// 1103/03-02. A page list's meta.page.total counts every page.
it("shows the total the backend counted, not the length of the first page", () => {
const { files } = plan({ id: "invoice-feature" });
expect(files.get("src/features/invoice-feature/contracts/invoice-mapper.ts")).toContain(
"total: page?.total ?? items.length",
);
expect(
files.get("src/features/invoice-feature/presentation/invoice-list-page.tsx"),
).toContain('message("invoice.list.resultCount", { count: query.data.total })');
});
});
/**
* 1103/09-06, 03-07. `--with-create` adds the paired backend scaffold's other
* two endpoints (POST /<plural>, GET /<plural>/{id}) with a detail page, a
* create form and the unknown-result handling. test:feature-scaffold and
* test:sample-removal generate it and run the gates on it.
*/
describe("create:feature --with-create", () => {
const contributionOf = (files: ReadonlyMap<string, string>) =>
files.get("src/features/invoice-feature/contracts/invoice-contract-contribution.ts") ?? "";
it("prefixes every id of the slice and adds its routes, pages and tests", () => {
const created = plan({ id: "invoice-feature", write: "NEVER" });
const text = [...created.files.values()].join("\n");
// No sample id. (`supportReference` is a platform prop.) Written so this
// file holds no sample id itself, which test:sample-removal looks for.
expect(text).not.toMatch(/REFERENCE_|ReferenceResource|reference-(?:feature|context)/u);
const ids = [
...text.matchAll(
/\b(?:schemaId|operationId|policyId|diagnosticsOperation|definitionId|chunkId|routeId|moduleId|loadingSurface|contributionId)\s*:\s*"([^"]+)"/gu,
),
...text.matchAll(/\bzodValidator\(\s*"([^"]+)"/gu),
...text.matchAll(/kind: "([a-z][^"]*\.[^"]*)"/gu),
...text.matchAll(/^\s+"((?:route\.)?[A-Za-z_.]+)": "/gmu),
].map((match) => match[1] ?? "");
expect(ids.length).toBeGreaterThan(50);
for (const id of ids) {
expect(id).toMatch(
/^(?:INVOICE_|Invoice|invoice[.-]|route\.INVOICE_(?:LIST|DETAIL|CREATE)\.|route-invoice-)/u,
);
}
expect([...created.files.keys()]).toEqual(
expect.arrayContaining([
"src/features/invoice-feature/presentation/invoice-detail-page.tsx",
"src/features/invoice-feature/presentation/invoice-create-page.tsx",
"src/features/invoice-feature/presentation/invoice-form.ts",
"src/features/invoice-feature/presentation/invoice-route-codecs.ts",
"src/features/invoice-feature/presentation/use-invoice-item.ts",
"src/features/invoice-feature/presentation/use-invoice-create.ts",
"tests/features/invoice-feature/invoice-create-page.test.tsx",
"artifacts/tests/a11y-manual/INVOICE_DETAIL.md",
"artifacts/tests/a11y-manual/INVOICE_CREATE.md",
]),
);
expect(created.routes).toEqual([
{ routeId: "INVOICE_LIST", path: "/invoice" },
{ routeId: "INVOICE_DETAIL", path: "/invoice/items/:invoiceId" },
{ routeId: "INVOICE_CREATE", path: "/invoice/new" },
]);
});
// 1103/16-01. Every generated operation declares the Envelope.
it("declares the Envelope on every operation it writes", () => {
const contribution = contributionOf(plan({ id: "invoice-feature", write: "NEVER" }).files);
expect(contribution.match(/operationId: "INVOICE_[A-Z_]+",/gu)).toHaveLength(3);
expect(contribution.match(/responseEnvelope: "ENVELOPE_V1" as const,/gu)).toHaveLength(3);
expect(contribution).toContain("pathTemplate: `${API_PATH}/{id}`,");
});
// 1103/03-07. new-feature.sh generates a NOT_IDEMPOTENT create: the backend
// ignores a key, so a same-key resend would create a second item.
it("matches the backend scaffold's NOT_IDEMPOTENT create with a NEVER command", () => {
const contribution = contributionOf(plan({ id: "invoice-feature", write: "NEVER" }).files);
expect(contribution).toContain('retrySemantics: "NEVER" as const,');
expect(contribution).toContain("retryBudget: 0 as const,");
expect(contribution).not.toContain("IDEMPOTENCY_REPLAY");
expect(contribution).toContain("acceptedStatuses: Object.freeze([201]),");
// 1103/03-01. The backend checks the name before its transaction.
expect(contribution).toContain('refusedBeforeWrite: Object.freeze(["INVOICE_INVALID"]),');
});
// 1103/16-07. A backend create made KEYED (IdempotencyExecutor) takes these.
it("writes the KEYED values for a backend create made KEYED", () => {
const { files } = plan({ id: "invoice-feature", write: "KEYED" });
const contribution = contributionOf(files);
expect(contribution).toContain('retrySemantics: "KEYED" as const,');
expect(contribution).toContain('mode: "IDEMPOTENCY_REPLAY" as const,');
expect(contribution).toContain('operationIdentityField: "idempotencyKey",');
expect(contribution).toContain("retryBudget: 1 as const,");
expect(
files.get("tests/features/invoice-feature/invoice-create-page.test.tsx"),
).toContain('posts[1]!.headers.get("idempotency-key")');
expect(
files.get("src/features/invoice-feature/presentation/use-invoice-create.ts"),
).toContain("...commandMutationIdentity(INVOICE_CREATE_ITEM_CONTRACT),");
});
it("refuses a slice route that collides with an installed one", () => {
expect(() =>
plan(
{ id: "invoice-feature", write: "NEVER" },
{
...INSTALLED,
routes: [
...INSTALLED.routes,
{ routeId: "LEGACY", path: "/invoice/new", chunkId: "route-legacy", navigationOrder: null },
],
},
),
).toThrow(/route INVOICE_CREATE .* collides with installed route LEGACY/u);
});
it("takes --with-create and --keyed, and --keyed only with --with-create", () => {
expect(parseRequest(["invoice-feature", "--with-create"])).toMatchObject({
write: "NEVER",
});
expect(parseRequest(["invoice-feature", "--with-create", "--keyed"])).toMatchObject({
write: "KEYED",
});
expect(parseRequest(["invoice-feature"]).write).toBeUndefined();
expect(() => parseRequest(["invoice-feature", "--keyed"])).toThrow(
/--keyed needs --with-create/u,
);
});
});
/**
* X1 (2026-11-04). The generated context declaration is executed, not only
* read as text: the generator's declaration source reads it from disk, and an
* app module built from its exported route root accepts every route the
* feature declares (the check the router relies on, 09-06).
*/
describe("create:feature context declaration", () => {
const roots: string[] = [];
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
});
async function appFor(
contextId: string,
routePath: string,
maxFeatures: number,
routes: readonly Readonly<{ routeId: string; path: string }>[],
) {
const { defineBoundedContextModule } = await import(
"../../src/contexts/bounded-context-module.ts"
);
const { defineDeployableAppModule } = await import("../../src/apps/deployable-app-module.ts");
return defineDeployableAppModule({
id: "template-app",
budget: { maxContexts: 20 },
contexts: [
defineBoundedContextModule({
id: contextId,
budget: { maxFeatures },
features: [
{
id: "invoice-feature",
contracts: {
routes: Object.fromEntries(routes.map((route) => [route.routeId, route])),
},
} as never,
],
route: { path: routePath, loadRoutes: async () => [] },
}),
],
});
}
it.each([undefined, "NEVER"] as const)(
"writes a context module the generator reads and whose root holds the routes (write %s)",
async (write) => {
const root = await mkdtemp(path.join(tmpdir(), "create-feature-context-"));
roots.push(root);
const created = plan({ id: "invoice-feature", write });
await mkdir(path.join(root, "src/apps/template-app"), { recursive: true });
await writeFile(
path.join(root, "src/apps/template-app/app-module.ts"),
'export const APP_MODULE_ID = "template-app";\nexport const APP_MAX_CONTEXTS = 20;\n',
);
await writeFeatureFiles(root, created.files);
const source = await createFileSystemDeclarationSource(root);
expect(source.contextsOf("template-app")).toEqual([
{ id: "invoice-context", appId: "template-app", routePath: "invoice/*", maxFeatures: 20 },
]);
expect(source.featuresOf("invoice-context").map((feature) => feature.id)).toEqual([
"invoice-feature",
]);
const declared = (await import(
pathToFileURL(path.join(root, "src/contexts/invoice-context/context-module.ts")).href
)) as Record<string, unknown>;
expect(declared).toMatchObject({
CONTEXT_MODULE_ID: "invoice-context",
CONTEXT_APP_ID: "template-app",
CONTEXT_ROUTE_PATH: "invoice/*",
});
const app = await appFor(
String(declared["CONTEXT_MODULE_ID"]),
String(declared["CONTEXT_ROUTE_PATH"]),
Number(declared["CONTEXT_MAX_FEATURES"]),
created.routes,
);
expect(app.contexts.map((context) => context.id)).toEqual(["invoice-context"]);
},
);
it("puts the routes under an existing context's root", async () => {
const created = plan({ id: "invoice-feature", context: "billing-context", write: "NEVER" });
expect(created.routes.map((route) => route.path)).toEqual([
"/billing/invoice",
"/billing/invoice/items/:invoiceId",
"/billing/invoice/new",
]);
await expect(appFor("billing-context", "billing/*", 20, created.routes)).resolves.toBeDefined();
});
});
describe("create:feature refusals", () => {
@@ -311,6 +311,67 @@ describe("declared pre-write refusals", () => {
});
});
// 1103/16-01. A contribution is one backend's package, so its operations read
// one wire frame. An operation added by hand without the `responseEnvelope`
// line used to pass every gate and the MSW scenarios, and failed only on the
// real backend.
describe("one wire frame per contribution (1103/16-01)", () => {
const [listRow, getRow, createRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
InstalledContractContribution["http"][number],
InstalledContractContribution["http"][number],
InstalledContractContribution["http"][number],
];
function framed(
row: InstalledContractContribution["http"][number],
responseEnvelope: "NONE" | "ENVELOPE_V1" | undefined,
): InstalledContractContribution["http"][number] {
const { responseEnvelope: _dropped, ...contract } = row.contract;
return {
...row,
contract:
responseEnvelope === undefined ? contract : { ...contract, responseEnvelope },
} as InstalledContractContribution["http"][number];
}
it("refuses an operation that forgot the Envelope its siblings read", () => {
const error = captureContributionError(() =>
composeContractContributions([
contribution("mixed-frames", [
framed(listRow, "ENVELOPE_V1"),
framed(getRow, undefined),
framed(createRow, "ENVELOPE_V1"),
]),
]),
);
expect(error.reason).toBe(
"test-feature/TEST_GET_ENTITY: responseEnvelope NONE, but TEST_LIST_ENTITIES in the same contribution reads ENVELOPE_V1; a contribution is one backend's package, so declare the same responseEnvelope on every operation or split the contribution per backend",
);
});
it("reads a missing value and NONE as the same frame", () => {
const composed = composeContractContributions([
contribution("bare-frames", [
framed(listRow, "NONE"),
framed(getRow, undefined),
framed(createRow, undefined),
]),
]);
expect(composed.httpByOperationId.size).toBe(3);
});
it("lets one feature read two backends through two contributions", () => {
const composed = composeContractContributions([
contribution("envelope-backend", [framed(listRow, "ENVELOPE_V1")]),
contribution("bare-backend", [framed(getRow, "NONE"), framed(createRow, undefined)]),
]);
expect(composed.contributions.map(({ http }) => http.length)).toEqual([1, 2]);
});
});
// The sample feature's own cases (its fixture composes, a second one does not)
// live in tests/features so they leave with the sample.
describe("template fixture provenance (07-04, §4.8)", () => {
+68
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import type { RuntimeValidator } from "../../src/contracts/external-contract-runtime.ts";
import type { SchemaDefinition } from "../../src/contracts/schema-registry.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import {
COMPOSED_CONTRACT_CONTRIBUTIONS,
SCHEMA_REGISTRY,
@@ -66,9 +68,59 @@ const slots = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.flatMap(
direction: "RESPONSE" as const,
validator: contract.outputValidator,
},
// 1103/16-04. The failure body is read as a response too.
{
operationId: contract.operationId,
direction: "RESPONSE" as const,
validator: contract.problemValidator,
},
]),
);
type Boundary = SchemaDefinition["boundary"];
/**
* 1103/16-04. Where each installed schema is used: an HTTP input, output or
* failure body, or a route's params or search. The row's `boundary` is
* derived from that set; a schema used in two places that no one boundary
* names (an output that is also an input) has no right answer and is listed.
*/
function usesBySchema(): ReadonlyMap<string, ReadonlySet<string>> {
const uses = new Map<string, Set<string>>();
const add = (schemaId: string | null, use: string) => {
if (schemaId === null) return;
const set = uses.get(schemaId) ?? new Set<string>();
set.add(use);
uses.set(schemaId, set);
};
for (const { http } of COMPOSED_CONTRACT_CONTRIBUTIONS.contributions) {
for (const { contract } of http) {
add(contract.inputValidator.schemaId, "http-input");
add(contract.outputValidator.schemaId, "http-output");
add(contract.problemValidator.schemaId, "http-problem");
}
}
for (const route of Object.values(ROUTE_REGISTRY)) {
add(route.paramsSchema, "route-params");
add(route.searchSchema, "route-search");
}
return uses;
}
function boundaryFor(uses: ReadonlySet<string>): Boundary | undefined {
const key = [...uses].sort().join("+");
const boundaries: Readonly<Record<string, Boundary>> = {
"http-input": "api-request",
"http-output": "api-response",
"http-problem": "api-problem",
"route-params": "route-params",
"http-input+route-params": "route-params",
"route-search": "route-search",
"http-input+route-search": "route-search-api-request",
};
return boundaries[key];
}
// With no installed feature (after the sample is removed) there is nothing to
// probe, and both cases pass empty.
describe("FE-REG-SCHEMA policy of the installed HTTP schemas (1103/07-03)", () => {
@@ -83,6 +135,22 @@ describe("FE-REG-SCHEMA policy of the installed HTTP schemas (1103/07-03)", () =
expect(wrong).toEqual([]);
});
it("gives every schema an operation or route uses a row at the boundary it is used", () => {
const wrong = [...usesBySchema()].flatMap(([schemaId, uses]) => {
const row = SCHEMA_REGISTRY[schemaId];
const expected = boundaryFor(uses);
if (row === undefined) return [`${schemaId}: no FE-REG-SCHEMA row`];
if (expected === undefined) {
return [`${schemaId}: used as ${[...uses].sort().join(" and ")}, which no boundary names`];
}
return row.boundary === expected
? []
: [`${schemaId}: row ${row.boundary}, used as ${expected}`];
});
expect(wrong).toEqual([]);
});
it("declares the unknown-field policy its validator applies", () => {
const wrong = slots.flatMap(({ operationId, validator }) => {
const declared = SCHEMA_REGISTRY[validator.schemaId]?.unknownFieldPolicy;
@@ -100,6 +100,8 @@ export const SECOND_API_SCHEMAS = Object.freeze({
SecondItemListQuery: schema("SecondItemListQuery", "route-search", "REQUEST"),
SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"),
SecondItemPayload: schema("SecondItemPayload", "api-response", "RESPONSE"),
// 1103/16-04. FE-REG-API's problemSchema references a row too.
SecondItemProblem: schema("SecondItemProblem", "api-problem", "RESPONSE"),
} as const);
export const SECOND_API_CONTRIBUTION: InstalledContractContribution = Object.freeze({