From 3f7e10c91a964841d725352e75fd52193f4baf6e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 22:56:52 +0900 Subject: [PATCH 1/9] =?UTF-8?q?fix(contracts):=20=ED=95=9C=20=EA=B3=84?= =?UTF-8?q?=EC=95=BD=20=EA=B8=B0=EC=97=AC=20=EC=95=88=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EC=9D=91=EB=8B=B5=20=EB=AA=A8=EC=96=91=EC=9D=B4=20=EB=8B=A4?= =?UTF-8?q?=EB=A5=B8=20operation=EC=9D=84=20=EA=B1=B0=EC=A0=88=ED=95=9C?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 responseEnvelope는 operation마다 적는 선택 칸이다. 생성 뼈대에 operation을 손으로 더하면서 이 줄을 빠뜨려도 check:types, check:registries, 라우터를 거치는 페이지 테스트가 모두 통과한다. MSW 시나리오 핸들러가 descriptor의 선언대로 답하기 때문이다. 짝 백엔드에 붙이면 그 화면만 SCHEMA_MISMATCH로 깨진다(리뷰 E-1). 고른 방법 계약 조립이 기여 하나 안의 operation이 같은 응답 모양을 읽는지 본다. 값이 없는 것과 "NONE"은 같은 모양이다. 기여 하나는 백엔드 하나의 패키지라서 그 안의 operation은 한 모양이다. 두 백엔드를 쓰는 기능은 기여를 나눈다. 거절 reason은 두 operation과 고칠 방법을 말한다. 앱을 조립하는 모든 테스트와 check:registries가 실패한다. 버린 대안 - responseEnvelope를 필수 칸으로: tsc가 잡는 가장 강한 통제지만 descriptor 약 25곳(참조, tests, 다운스트림 손 descriptor, 계약 패키지)을 깨는 공개 타입 변경이다. 같은 실수(일부만 빠뜨림)를 이 규칙이 잡으므로 작은 쪽을 골랐다. - 기여 단위 기본값: "기본값이 어디서 오나"라는 규칙이 하나 는다. 위험·한계 - 기여 안의 operation 모두에서 줄을 빼면 잡지 못한다. 생성된 gateway 테스트 (백엔드 본문을 손으로 적음)만 잡는다. 매뉴얼에 적었다. - 한 기여에 두 모양을 섞던 다운스트림 기여는 조립이 거부한다. 레포 안에서는 테스트 fixture 하나(api-operation-rows)가 그랬고 고쳤다. 검증 - RED: 새 테스트 3건 중 섞인 기여 거절 1건 실패. GREEN 뒤 통과. - tests/unit·integration·contract·component·features·runtime-schema·platform· architecture 297파일 3,718건: 섞인 fixture 1건만 실패 → 고친 뒤 통과. - check:types, lint 통과. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-01 --- docs/manual/01-add-a-feature.md | 19 +++--- docs/manual/reference/errors.md | 1 + src/contracts/external-contract-runtime.ts | 23 ++++++++ tests/unit/api-operation-rows.test.ts | 2 + tests/unit/external-contract-runtime.test.ts | 61 ++++++++++++++++++++ 5 files changed, 99 insertions(+), 7 deletions(-) diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 481909bf..ff81c9dd 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -193,7 +193,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(`-contract-contribution.ts`)의 한 줄 `responseEnvelope: "ENVELOPE_V1"`이다. 뼈대에 들어 있다. +- 이 모양을 읽게 하는 것은 V3 descriptor(`-contract-contribution.ts`)의 한 줄 `responseEnvelope: "ENVELOPE_V1"`이다. 생성된 operation에는 모두 들어 있다. + - operation을 손으로 더할 때마다 이 줄을 적는다. 이 값은 operation마다 따로다. + - 한 계약 기여 안에서 이 값이 다른 operation이 있으면 계약 조립이 거부한다(`/: responseEnvelope NONE, but in the same contribution reads ENVELOPE_V1; ...`). 기여 하나는 백엔드 하나의 패키지라서다. 그래서 줄을 빠뜨리면 앱을 조립하는 테스트와 `check:registries`가 실패한다. + - **못 잡음**: 기여 안의 operation 모두에서 이 줄을 빼는 것. 그때는 아래 MSW 줄의 손글씨 gateway 테스트만 잡는다. ```text 성공 status → Envelope 확인 → data를 outputValidator로 검증 → mapSuccess @@ -206,7 +209,7 @@ FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-ope - 업무 규칙 거절(`_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//-http-gateway.test.ts`는 백엔드 본문을 그대로 적어 검사한다. +- MSW: `createHttpScenarioHandler`는 descriptor의 `responseEnvelope`를 보고 Envelope로 답한다(`tests/mocks/handlers/http-scenarios.ts`). 그래서 시나리오 테스트는 선언이 틀려도 통과한다. 생성된 `tests/features//-http-gateway.test.ts`는 백엔드 본문을 그대로 적어 검사한다. operation을 더하면 이 파일에도 그 operation의 백엔드 본문 테스트를 더한다. - `http-contract.md`는 status·`code`의 **뜻**(예: 409 `IDEMPOTENT_IN_FLIGHT`)의 정본이다. 기능 코드에서 그 code는 problem의 `code`로 읽는다. **짝 백엔드가 아닌 백엔드** @@ -239,21 +242,23 @@ DTO와 problem details(`type`·`title`·`status`)를 감싸지 않고 보내는 - `api-request`: 요청 입력. - `api-response`: 응답 DTO. -예: 공지 기능의 검색값 GET과 경로 파라미터 GET. 입력에 관한 칸만 적었다. +예: 공지 기능의 검색값 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([]), diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index c484901d..1d987ccd 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -101,6 +101,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `/: is a read; its retrySemantics is SAFE or IDEMPOTENT, not <값>` | 읽기에 `KEYED`나 `NEVER`를 적었다 | V3 `retrySemantics`. 재시도를 막으려면 `frontend.retryBudget: 0` | | `/: command operations require a command effect descriptor` | 쓰기에 `commandEffect`가 없다 | V3 `commandEffect` | | `/: read operations carry no command descriptors` | GET에 `commandEffect`·`commandRecovery`를 적었다 | 둘 다 `null` | +| `/: responseEnvelope NONE, but in the same contribution reads ENVELOPE_V1; ...` | 한 계약 기여 안에서 operation 하나만 응답 모양이 다르다. 손으로 더한 operation에 `responseEnvelope` 줄을 빠뜨린 경우다 | 그 operation에 `responseEnvelope: "ENVELOPE_V1" as const`를 적는다. 정말 다른 백엔드면 기여를 나눈다 | | `: package version must be exact SemVer` | 버전 범위(`^1.2.0`)나 형식 오류 | `_CONTRACT_PACKAGE.version` | ### 라우트·context diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index 12b81f83..f89f2e18 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -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, + first: InstalledHttpContract | 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, 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}`); diff --git a/tests/unit/api-operation-rows.test.ts b/tests/unit/api-operation-rows.test.ts index 29c72e8c..59a103e7 100644 --- a/tests/unit/api-operation-rows.test.ts +++ b/tests/unit/api-operation-rows.test.ts @@ -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", diff --git a/tests/unit/external-contract-runtime.test.ts b/tests/unit/external-contract-runtime.test.ts index 44611d18..564be7e6 100644 --- a/tests/unit/external-contract-runtime.test.ts +++ b/tests/unit/external-contract-runtime.test.ts @@ -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)", () => { From f59a806429ec35f93f3c428add3360b937d6b1da Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 22:59:48 +0900 Subject: [PATCH 2/9] =?UTF-8?q?feat(server-state):=20=EB=AE=A4=ED=85=8C?= =?UTF-8?q?=EC=9D=B4=EC=85=98=20=EC=A0=95=EC=B1=85=EC=9D=B4=20operation=20?= =?UTF-8?q?ID=EC=99=80=20=ED=82=A4=20=EC=97=AC=EB=B6=80=EB=A5=BC=20descrip?= =?UTF-8?q?tor=EC=97=90=EC=84=9C=20=EB=B0=9B=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 BoundMutation의 operationId와 requiresIdempotencyKey는 기능이 손으로 다시 적는 자유 값이다. operationId에 오타가 있어도 check:types와 check:registries가 통과하고, 실행기는 intent의 operation ID가 descriptor와 다르다며 보내기 전에 거부한다(MISSING_IDEMPOTENCY_KEY 위반). 화면은 "요청을 처리할 수 없습니다"로 멈추고 원인을 말하지 않는다(리뷰 E-2). 1101/03-03이 같은 재기술을 적었다. 고른 방법 src/contracts/server-state.ts에 commandMutationIdentity(descriptor)를 둔다. descriptor의 operationId와 retrySemantics === "KEYED"를 돌려주고, 정책은 이것을 펼쳐 쓴다. 상수 이름 오타는 tsc가 잡는다. GET·HEAD descriptor를 넘기면 바인딩 때 throw한다. 참조 기능의 생성 정책이 이것을 쓴다. 버린 대안 - BoundMutation.operationId를 brand 타입으로: 자유 문자열도 막지만 테스트 약 27곳과 다운스트림 정책을 깨는 공개 타입 변경이다. - 실행기 위반 이름을 INTENT_OPERATION_MISMATCH로 나누기: http 어댑터의 닫힌 위반 어휘와 화면 매핑을 바꾼다. 값을 descriptor에서 받으면 그 경로에 닿지 않으므로 미뤘다. - 타입에서 method를 쓰기 method로 좁히기: InstalledHttpContract로 주석한 descriptor(method: HttpMethod)가 모두 타입 오류가 나서 실행 때 검사만 둔다. 위험·한계 - 정책에 operationId 문자열을 직접 적는 길은 남는다. 매뉴얼 7단계 "못 잡음"에 적었다. - 참조 기능 presentation이 계약 기여 파일을 import한다. 두 파일 모두 지연 청크라 초기 JS는 바뀌지 않는다(check:bundle은 다음 커밋들과 함께 잰다). 검증 - RED: tests/unit/command-mutation-identity.test.ts 4건이 함수 없음으로 실패. GREEN 뒤 통과. - tests/features/reference-feature, tests/component/application-query.test.tsx 125건 통과. - check:types, check:architecture, lint, verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-05 --- docs/manual/01-add-a-feature.md | 22 ++++++++-- docs/manual/02-decision-tables.md | 2 +- docs/manual/reference/errors.md | 1 + docs/manual/reference/patterns.md | 2 +- src/contracts/server-state.ts | 35 ++++++++++++++++ .../presentation/use-reference-feature.ts | 7 +++- tests/unit/command-mutation-identity.test.ts | 40 +++++++++++++++++++ 7 files changed, 102 insertions(+), 7 deletions(-) create mode 100644 tests/unit/command-mutation-identity.test.ts diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index ff81c9dd..e13b7b4e 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -441,15 +441,29 @@ 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]`을 쓴다. - - 예제: `src/features/reference-feature/presentation/use-reference-feature.ts`의 생성 뮤테이션 정책. +- 뮤테이션 정책의 operation ID와 `requiresIdempotencyKey`는 `commandMutationIdentity(_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`의 생성 뮤테이션 정책. ③ **잡는 검사 / 못 잡는 것** @@ -457,6 +471,8 @@ projectRequest: (input) => Object.freeze({ - topic 형식이 틀리면 `Query invalidation topic is invalid.`로 실패한다. - 등록되지 않은 profile은 실행 때 `Unregistered server-state profile: `로 실패한다. - topic·namespace·edge를 더하기만 하면 레지스트리 기준선은 바뀌지 않는다(additive). 9단계에서 할 일이 없다. +- 뮤테이션 정책의 operation ID를 `commandMutationIdentity`로 받으면 descriptor 상수 이름의 오타는 `check:types`가 막는다. 쓰기 descriptor 대신 GET descriptor를 넘기면 바인딩 때 `commandMutationIdentity: is a GET; a mutation binds a write operation`으로 throw한다. +- **못 잡음**: 뮤테이션 정책에 operation ID를 문자열로 직접 적은 것. 타입이 `string`이라 오타가 통과하고, 저장할 때 실행기가 보내기 전에 거부한다(`MISSING_IDEMPOTENCY_KEY` 위반). `commandMutationIdentity`를 쓴다. - **못 잡음**: `bindQuery`의 `operationId` 오타. 타입이 `string`이라 operation과 묶이지 않는다. - **못 잡음**: `definitionId` 중복. 유일성 검사가 없다. diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 63f21efb..1fed09ad 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -89,7 +89,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 | 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 | | 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다. 예외: 짝 백엔드가 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절)로 답하면 `retryBudget` 안에서 같은 키로 다시 보낸다 | 된다 | 하지 않는다 | | descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 참조 기능은 `retryBudget: 0` | — | `retryBudget: 0` 필수 | -| 뮤테이션 정책 | `requiresIdempotencyKey: true` | — | — | +| 뮤테이션 정책 | `...commandMutationIdentity(_CONTRACT)`가 `requiresIdempotencyKey: true`를 준다 | 같은 함수가 `false`를 준다 | 같은 함수가 `false`를 준다 | - 멱등 키: 서버가 "같은 쓰기 요청"을 알아보게 하는 값이다. - 결과를 모를 때 새 키로 다시 보내면 안 된다. 서버는 새 키를 다른 요청으로 보고 막지 못한다. diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 1d987ccd..aa3c68f1 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -124,6 +124,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `Query invalidation topic is invalid.` | topic 형식이 `qinv.` + 26자가 아니다 | `defineQueryInvalidationTopic` 값 | | `Orphan invalidation topic: ` | edge가 없는 topic | 계약 `invalidation.edges` | | `Unregistered server-state profile: ` | 없는 profile | 쿼리 바인딩의 `profileId` | +| `commandMutationIdentity: is a GET; a mutation binds a write operation` | 뮤테이션 정책에 읽기 descriptor를 넘겼다 | 정책의 `commandMutationIdentity(...)` 인자를 쓰기 descriptor로 | ### 조립 기여 diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index a584972c..99a34e4c 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -95,7 +95,7 @@ const search = (q: string) => |---|---|---|---| | 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use--items.ts` | profile ID (실행 때). `operationId`는 `string`이라 묶이지 않음 | | 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) | -| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책 | 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 기능 테스트 | +| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름), 기능 테스트 | | 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만 | | 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (참조 기능은 생성 명령만 있다) | — | | 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 | diff --git a/src/contracts/server-state.ts b/src/contracts/server-state.ts index d0da23fd..d5acfcc4 100644 --- a/src/contracts/server-state.ts +++ b/src/contracts/server-state.ts @@ -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 @@ -258,6 +259,40 @@ 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 = Readonly<{ definitionId: string; definitionVersion: number; diff --git a/src/features/reference-feature/presentation/use-reference-feature.ts b/src/features/reference-feature/presentation/use-reference-feature.ts index 8ab414a2..3a92f496 100644 --- a/src/features/reference-feature/presentation/use-reference-feature.ts +++ b/src/features/reference-feature/presentation/use-reference-feature.ts @@ -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,8 +55,9 @@ function measureResourceList( const REFERENCE_CREATE_MUTATION_POLICY = Object.freeze({ definitionId: "reference-resource-create-v1", definitionVersion: 1, - operationId: "CREATE_REFERENCE_RESOURCE", - requiresIdempotencyKey: true, + // 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), owner: REFERENCE_FEATURE_ID, duplicatePolicy: "REJECT_WHILE_ACTIVE" as const, invalidate: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]), diff --git a/tests/unit/command-mutation-identity.test.ts b/tests/unit/command-mutation-identity.test.ts new file mode 100644 index 00000000..bfa3d858 --- /dev/null +++ b/tests/unit/command-mutation-identity.test.ts @@ -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", + ); + }); +}); From 68f94f5e933daa917c96b93e82f3146ecf982945 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 23:02:44 +0900 Subject: [PATCH 3/9] =?UTF-8?q?refactor(server-state):=20=EC=95=84?= =?UTF-8?q?=EB=AC=B4=EB=8F=84=20=EC=9D=BD=EC=A7=80=20=EC=95=8A=EB=8A=94=20?= =?UTF-8?q?=EC=BF=BC=EB=A6=AC=C2=B7=EB=AE=A4=ED=85=8C=EC=9D=B4=EC=85=98=20?= =?UTF-8?q?=EC=A0=95=EC=9D=98=20=EC=B9=B8=EC=9D=84=20=EC=84=A0=ED=83=9D=20?= =?UTF-8?q?=EC=B9=B8=EC=9C=BC=EB=A1=9C=20=EB=91=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 QueryDefinition의 owner·operationId와 BoundMutation의 owner는 필수 칸이다. bindQuery가 돌려주는 객체에는 둘 다 없고, src 어디서도 읽지 않는다. 기능 작성자는 효과 없는 값을 매번 채우고, 매뉴얼은 그 오타를 "못 잡는 위험"으로 적어 오히려 신경 쓰게 한다(리뷰 16-06 ①②). 고른 방법 세 칸을 @deprecated 선택 칸으로 바꾼다. 참조 기능과 생성 뼈대는 더는 채우지 않는다. 요청 기록의 operation ID는 지금처럼 descriptor에서 온다. 매뉴얼 6·7단계와 patterns.md에 "적지 않는다"와, 라우트 계약 title· navigationLabel을 무엇이 읽는지(FE-REG-ROUTE, lab 측정)를 적었다. 버린 대안 - 칸을 바로 지우기: 객체 리터럴의 초과 속성 검사로 테스트 3파일과 다운스트림 정의가 컴파일 오류가 난다. 선택 칸으로 한 릴리스 두고 지운다. - 쿼리 operationId를 진단 이름표로 잇기: HTTP 실행 기록이 이미 descriptor의 operation ID를 싣는다. 같은 값을 두 번 싣는다. 위험·한계 - 라우트 계약의 title·navigationLabel(16-06 ③)은 그대로 둔다. 지우려면 FE-REG-ROUTE 기준선 행을 catalog에서 만들고, 플랫폼 라우트와 test-performance.ts를 함께 바꿔야 한다. 다른 작업(예제 화면 이동)과 같은 파일이라 이번에는 문서로만 적었다. 검증 - RED: application-query-scope-fence 새 테스트가 tsconfig.test에서 owner· operationId 누락으로 타입 오류. 선택 칸으로 바꾼 뒤 통과. - tests/features/reference-feature, tests/unit/create-feature.test.ts, scope-fence 129건 통과. check:types(app·node·test), lint 통과. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-06 --- docs/manual/01-add-a-feature.md | 5 +-- docs/manual/reference/patterns.md | 2 +- scripts/create-feature.ts | 4 +-- src/contracts/server-state.ts | 16 ++++++++-- .../presentation/use-reference-feature.ts | 5 --- .../application-query-scope-fence.test.tsx | 31 +++++++++++++++++++ 6 files changed, 49 insertions(+), 14 deletions(-) diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index e13b7b4e..c1353836 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -374,7 +374,8 @@ projectRequest: (input) => Object.freeze({ - `presentation/-feature-runtime.ts`: 지연 로드 페이지 표. `moduleId`는 계약과 같아야 한다. - `context-routes.ts`: context가 적재하는 라우트 목록. 생성된 판은 계약의 라우트를 그대로 옮긴다. - `presentation/-routes.ts`: 링크용 URL 함수. route ID를 받아 `buildRouteUrl`(`src/presentation/routes/route-codecs.ts`)로 경로를 채운다. -- 문구 `route..title`, `route..navigation` (ko-KR, en-US). +- 문구 `route..title`, `route..navigation` (ko-KR, en-US). 화면의 문서 제목과 메뉴 이름은 이 문구다. + - 계약 `routes`의 `title`·`navigationLabel`은 화면이 읽지 않는다. FE-REG-ROUTE 기준선 행과 lab 측정(`scripts/test-performance.ts`, 플랫폼 라우트만)이 읽는다. 생성 명령은 문구와 같은 값을 넣는다. 값을 바꾸면 `check:registries`가 behavior-change로 기록한다. - 기능 폴더 밖: `artifacts/tests/a11y-manual/.md`(pending 기록). 생성 명령이 만든다. ① **정할 것** @@ -473,7 +474,7 @@ projectRequest: (input) => Object.freeze({ - topic·namespace·edge를 더하기만 하면 레지스트리 기준선은 바뀌지 않는다(additive). 9단계에서 할 일이 없다. - 뮤테이션 정책의 operation ID를 `commandMutationIdentity`로 받으면 descriptor 상수 이름의 오타는 `check:types`가 막는다. 쓰기 descriptor 대신 GET descriptor를 넘기면 바인딩 때 `commandMutationIdentity: is a GET; a mutation binds a write operation`으로 throw한다. - **못 잡음**: 뮤테이션 정책에 operation ID를 문자열로 직접 적은 것. 타입이 `string`이라 오타가 통과하고, 저장할 때 실행기가 보내기 전에 거부한다(`MISSING_IDEMPOTENCY_KEY` 위반). `commandMutationIdentity`를 쓴다. -- **못 잡음**: `bindQuery`의 `operationId` 오타. 타입이 `string`이라 operation과 묶이지 않는다. +- `bindQuery`의 `owner`·`operationId`, 뮤테이션 정책의 `owner`는 적지 않는다. 읽는 곳이 없어 `@deprecated` 선택 칸이 됐고, 다음 릴리스에서 지운다. 요청 기록의 operation ID는 descriptor의 것이다. - **못 잡음**: `definitionId` 중복. 유일성 검사가 없다. ④ **쓸 스킬**: 정해 둔 스킬 없음. 이 절과 02 결정표로 판단한다. diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index 99a34e4c..96724a2c 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -93,7 +93,7 @@ const search = (q: string) => | 패턴 | 정의 | 예제 | 검사 | |---|---|---|---| -| 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use--items.ts` | profile ID (실행 때). `operationId`는 `string`이라 묶이지 않음 | +| 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use--items.ts` | profile ID (실행 때). `owner`·`operationId`는 읽는 곳이 없는 `@deprecated` 칸이라 적지 않는다 | | 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) | | 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름), 기능 테스트 | | 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만 | diff --git a/scripts/create-feature.ts b/scripts/create-feature.ts index b035bbf1..12a7f7e3 100644 --- a/scripts/create-feature.ts +++ b/scripts/create-feature.ts @@ -880,7 +880,7 @@ export function ${camel}RouteUrl( `; } -function renderUseItems({ names, operationId }: Shape): string { +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"; @@ -916,9 +916,7 @@ export function use${pascal}Items() { { definitionId: "${base}-item-list-v1", definitionVersion: 1, - owner: ${upper}_FEATURE_ID, namespace: ${upper}_ITEM_QUERY_NAMESPACE, - operationId: "${operationId}", profileId: "LIST_STANDARD", measureResult: measureItems, execute: (_input: typeof NO_INPUT, { signal }) => input.listItems({ signal }), diff --git a/src/contracts/server-state.ts b/src/contracts/server-state.ts index d5acfcc4..4ff400be 100644 --- a/src/contracts/server-state.ts +++ b/src/contracts/server-state.ts @@ -174,8 +174,14 @@ type QueryDefinitionNamespace = export type QueryDefinition = 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). @@ -298,7 +304,11 @@ export type BoundMutation = Readonly<{ 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( diff --git a/src/features/reference-feature/presentation/use-reference-feature.ts b/src/features/reference-feature/presentation/use-reference-feature.ts index 3a92f496..e455765b 100644 --- a/src/features/reference-feature/presentation/use-reference-feature.ts +++ b/src/features/reference-feature/presentation/use-reference-feature.ts @@ -58,7 +58,6 @@ const REFERENCE_CREATE_MUTATION_POLICY = Object.freeze({ // 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), - owner: REFERENCE_FEATURE_ID, duplicatePolicy: "REJECT_WHILE_ACTIVE" as const, invalidate: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]), }); @@ -89,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 }) => @@ -123,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 }) => diff --git a/tests/component/application-query-scope-fence.test.tsx b/tests/component/application-query-scope-fence.test.tsx index 6da1a06f..6a75ffee 100644 --- a/tests/component/application-query-scope-fence.test.tsx +++ b/tests/component/application-query-scope-fence.test.tsx @@ -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(); From 3b40f736381c9c68c214e1f0b88b2da3b195baf7 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 23:06:52 +0900 Subject: [PATCH 4/9] =?UTF-8?q?fix(contracts)!:=20=EC=8A=A4=ED=82=A4?= =?UTF-8?q?=EB=A7=88=20=EB=A9=94=ED=83=80=EC=9D=98=20boundary=EB=A5=BC=20?= =?UTF-8?q?=EC=93=B0=EC=9E=84=EA=B3=BC=20=EB=8C=80=EC=A1=B0=ED=95=98?= =?UTF-8?q?=EA=B3=A0=20=EC=8B=A4=ED=8C=A8=20=EB=B3=B8=EB=AC=B8=20=ED=96=89?= =?UTF-8?q?=EC=9D=84=20=EB=91=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 -schema-metadata.ts의 boundary는 손으로 적고, check:registries는 값이 목록 안인지만 본다. 응답 스키마에 boundary "api-request"를 적어도 타입· 레지스트리·기능 테스트가 모두 통과한다(리뷰 E-4 세 번째 변이). direction과 unknownFieldPolicy는 07-03 수정(5bee9ab)이 검증기와 대조한다. 또 FE-REG-API의 problemSchema는 breaking 칸이지만 FE-REG-SCHEMA를 참조하지 않고, 참조 기능과 생성 뼈대에 실패 본문 스키마 행이 없다(07-01 (d)). 고른 방법 - schema-metadata-policy.test.ts에 boundary 대조를 더한다. 설치된 descriptor의 입력·응답·실패 검증기와 라우트 paramsSchema·searchSchema에서 스키마마다 쓰인 자리를 모으고, 그 조합에서 boundary를 정해 행과 비교한다. 쓰이는데 행이 없는 스키마도 실패한다. direction·unknownFieldPolicy 검사는 실패 검증기까지 넓힌다. - boundary에 "api-problem"을 더한다(SchemaDefinition, governance allowedValues). FE-REG-API problemSchema → FE-REG-SCHEMA.schemaId 참조를 governance에 더한다. - 참조 기능 ReferenceProblem, 생성 뼈대 Problem, second-api fixture에 실패 본문 행을 더한다. 버린 대안 - 메타 행을 descriptor·라우트에서 투영(16-04 권고 (b)): 메타 파일이 거의 사라지지만 생성 뼈대·참조 기능·레지스트리 원본을 함께 바꾼다. 리뷰가 "빠르게 막으려면 (c) 먼저"라고 적은 대조 테스트를 골랐다. - owner를 기능 ID에서 검사: 정한 규칙이 없다(참조 기능 owner는 "...-vertical-slice"). 그대로 둔다. 위험·한계 - governance 참조 추가는 FE-REG-API 계약 변경이라 기준선을 다시 찍었다 (REGISTRY_BASELINE_REASON에 1103/16-04). 다른 브랜치 변경(FE-REG-TELEMETRY optionalAttributes)도 같은 스냅샷에 들어갔다. 오케스트레이터가 통합 뒤 다시 찍는다. - 다운스트림 기능은 실패 본문 행이 없으면 check:registries가 실패한다. CHANGELOG에 이행 안내가 필요하다. - 대조 테스트는 설치된 기능만 본다. 기능을 더한 상태에서 test:unit을 돌릴 때 잡힌다. 검증 - RED: 새 boundary 테스트가 "ReferenceProblem: no FE-REG-SCHEMA row"로 실패. 행을 더한 뒤 통과. - 변이: ReferenceResourcePayload boundary를 api-request로 바꾸면 "row api-request, used as api-response"로 실패. 되돌림. - check:registries 실패(FE-REG-API references 변경) → 기준선 갱신 뒤 PASS compatibility=none. - second-api-feature-registries, registry-governance, release-artifacts, create-feature 테스트 통과. check:types, lint, verify:documentation 통과. BREAKING CHANGE: FE-REG-API problemSchema가 FE-REG-SCHEMA.schemaId를 참조한다. 설치된 기능의 problemValidator 스키마마다 -schema-metadata.ts에 boundary "api-problem", direction "RESPONSE" 행이 없으면 check:registries가 "FE-REG-API..problemSchema references unknown FE-REG-SCHEMA"로 실패한다. 행을 더하고 레지스트리 기준선을 다시 찍는다. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-04 Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-01 --- .../contracts/registry-baseline.approval.json | 6 +- config/contracts/registry-baseline.json | 20 +++++- config/contracts/registry-governance.json | 8 ++- docs/manual/01-add-a-feature.md | 13 +++- docs/manual/reference/errors.md | 3 +- scripts/create-feature.ts | 14 +++- src/contracts/schema-registry.ts | 4 +- .../contracts/reference-schema-metadata.ts | 10 +++ tests/unit/schema-metadata-policy.test.ts | 68 +++++++++++++++++++ .../second-api-feature-registries.test.ts | 2 + 10 files changed, 137 insertions(+), 11 deletions(-) diff --git a/config/contracts/registry-baseline.approval.json b/config/contracts/registry-baseline.approval.json index 38b05eee..74247c76 100644 --- a/config/contracts/registry-baseline.approval.json +++ b/config/contracts/registry-baseline.approval.json @@ -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" } diff --git a/config/contracts/registry-baseline.json b/config/contracts/registry-baseline.json index da86f4cd..6a56a3ef 100644 --- a/config/contracts/registry-baseline.json +++ b/config/contracts/registry-baseline.json @@ -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": [ diff --git a/config/contracts/registry-governance.json b/config/contracts/registry-governance.json index dce422f5..a7755371 100644 --- a/config/contracts/registry-governance.json +++ b/config/contracts/registry-governance.json @@ -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"] }, diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index c1353836..d9d30b06 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -241,6 +241,14 @@ 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`가 이 행을 가리킨다. + +스키마 메타데이터의 `boundary`·`direction`·`unknownFieldPolicy`는 손으로 적지만 `tests/unit/schema-metadata-policy.test.ts`(`test:unit`)가 실제 쓰임과 대조한다. + +- `boundary`: descriptor의 입력·응답·실패 검증기와 라우트의 `paramsSchema`·`searchSchema`에서 쓰인 자리로 정해진다. 다르면 `: row <적은 값>, used as <맞는 값>`으로 실패한다. 쓰이는데 행이 없으면 `: no FE-REG-SCHEMA row`. +- `direction`: 입력은 `REQUEST`, 응답·실패는 `RESPONSE`. +- `unknownFieldPolicy`: zod가 모르는 키를 거부하면(`.strict()`) `REJECT_UNKNOWN`, 버리면(`.strip()`) `STRIP_UNKNOWN`. +- 이 테스트는 설치된 기능을 읽는다. 기능을 더한 상태에서 `test:unit`을 돌릴 때 잡힌다. 예: 공지 기능의 검색값 GET과 경로 파라미터 GET. 입력에 관한 칸과 응답 모양 줄만 적었다. @@ -268,8 +276,9 @@ projectRequest: (input) => Object.freeze({ ③ **잡는 검사 / 못 잡는 것** -- descriptor의 입력·응답 스키마 ID가 스키마 메타데이터에 없으면 `check:registries`가 실패한다. - - 메시지: `FE-REG-API..requestSchema references unknown FE-REG-SCHEMA.schemaId=` (`responseSchema`도 같다) +- descriptor의 입력·응답·실패 스키마 ID가 스키마 메타데이터에 없으면 `check:registries`가 실패한다. + - 메시지: `FE-REG-API..requestSchema references unknown FE-REG-SCHEMA.schemaId=` (`responseSchema`, `problemSchema`도 같다) +- 스키마 메타데이터의 `boundary`·`direction`·`unknownFieldPolicy`가 실제 쓰임과 다르면 `test:unit`의 `tests/unit/schema-metadata-policy.test.ts`가 실패한다(위 "입력과 스키마 메타데이터"). - 인증 프로필 이름이 틀리면 계약 조립이 거부해 operation을 적재하는 모든 게이트가 실패한다. - 오류의 `reason`: `/: unknown authProfileId ` - 스키마 ID나 operation ID가 겹치면 적재 때 그 ID를 말하며 실패한다. diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index aa3c68f1..c41a802c 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -82,7 +82,8 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 |---|---|---| | `Invalid or duplicate schema definition: ` | 스키마 ID 중복 또는 메타 형식 | `contracts/-schema-metadata.ts`. 접두어를 붙인다 | | `duplicate operation: ` (계약 조립 오류의 `reason`) | operation ID 중복 | `contracts/-contract-contribution.ts`. 접두어를 붙인다 | -| `FE-REG-API..requestSchema references unknown FE-REG-SCHEMA.schemaId=` | descriptor의 입력 스키마 ID가 스키마 메타데이터에 없다 (`responseSchema`도 같은 꼴) | `contracts/-schema-metadata.ts` | +| `FE-REG-API..requestSchema references unknown FE-REG-SCHEMA.schemaId=` | descriptor의 입력 스키마 ID가 스키마 메타데이터에 없다 (`responseSchema`, `problemSchema`도 같은 꼴. 실패 본문 행은 `boundary: "api-problem"`) | `contracts/-schema-metadata.ts` | +| `: row , used as ` (`tests/unit/schema-metadata-policy.test.ts`) | 스키마 메타 행의 `boundary`가 그 스키마가 쓰인 자리와 다르다. `no FE-REG-SCHEMA row`는 쓰이는데 행이 없다 | `contracts/-schema-metadata.ts` | | `Unregistered route codec: ` | URL 함수가 기능 codec을 `buildRouteUrl`에 넘기지 않았다 | `presentation/-routes.ts` | | `contract package is declared, but no loaded contribution pins it` | 계약 `contractPackages`에 적은 패키지를 계약 기여가 쓰지 않는다 | `contracts/-contract-contribution.ts`의 `source` | | ` contributes contract package , which no installed feature declares in contracts.contractPackages` | 계약 기여의 신원과 계약 선언의 신원이 다르다 | 둘 다 `_CONTRACT_PACKAGE` 하나를 쓰게 한다 | diff --git a/scripts/create-feature.ts b/scripts/create-feature.ts index 12a7f7e3..c1e565d6 100644 --- a/scripts/create-feature.ts +++ b/scripts/create-feature.ts @@ -602,7 +602,10 @@ function renderSchemaMetadata({ names, owner }: Shape): string { * 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. + * \`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({ @@ -623,6 +626,15 @@ export const ${upper}_SCHEMA_METADATA = Object.freeze({ 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", + }), } as const); `; } diff --git a/src/contracts/schema-registry.ts b/src/contracts/schema-registry.ts index ace442c1..8667fa8f 100644 --- a/src/contracts/schema-registry.ts +++ b/src/contracts/schema-registry.ts @@ -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; diff --git a/src/features/reference-feature/contracts/reference-schema-metadata.ts b/src/features/reference-feature/contracts/reference-schema-metadata.ts index 6975658f..f31003ba 100644 --- a/src/features/reference-feature/contracts/reference-schema-metadata.ts +++ b/src/features/reference-feature/contracts/reference-schema-metadata.ts @@ -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", + }), }); diff --git a/tests/unit/schema-metadata-policy.test.ts b/tests/unit/schema-metadata-policy.test.ts index 16923671..287271f6 100644 --- a/tests/unit/schema-metadata-policy.test.ts +++ b/tests/unit/schema-metadata-policy.test.ts @@ -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> { + const uses = new Map>(); + const add = (schemaId: string | null, use: string) => { + if (schemaId === null) return; + const set = uses.get(schemaId) ?? new Set(); + 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): Boundary | undefined { + const key = [...uses].sort().join("+"); + const boundaries: Readonly> = { + "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; diff --git a/tests/unit/second-api-feature-registries.test.ts b/tests/unit/second-api-feature-registries.test.ts index a579b9c3..2dc6ba0d 100644 --- a/tests/unit/second-api-feature-registries.test.ts +++ b/tests/unit/second-api-feature-registries.test.ts @@ -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({ From 2ec9d56008991da257de9c86dd8cc9b9fa2cac5b Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 23:28:12 +0900 Subject: [PATCH 5/9] =?UTF-8?q?feat(scaffold):=20create:feature=20--with-c?= =?UTF-8?q?reate=EA=B0=80=20=EC=A7=9D=20=EB=B0=B1=EC=97=94=EB=93=9C=20?= =?UTF-8?q?=EC=83=9D=EC=84=B1=EA=B8=B0=EC=99=80=20=EA=B0=99=EC=9D=80=20sli?= =?UTF-8?q?ce=EB=A5=BC=20=EB=A7=8C=EB=93=A0=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 - 프론트 create:feature는 GET /api/-items 목록 하나를 만든다. 짝 백엔드 new-feature.sh는 POST /(201, NOT_IDEMPOTENT)과 GET //{id}를 만든다. 경로 규칙도, operation 쌍도 맞지 않는다(03-07). - 짝 백엔드 모양(Envelope)의 상세 GET·작성 POST·폼·결과 불명 화면 예제는 참조 기능뿐이고, 참조 기능은 problem details 모양이라 옮기면 짝 백엔드에서 쓰이지 않는 분기와 값(400·422 분류, retryBudget 0, Envelope 줄 없음)을 함께 옮긴다(09-06, 16 5.3절). - 생성된 목록의 "총 N개"는 배열 길이다. 백엔드 meta.page.total을 쓰지 않는다(03-02 수정이 남긴 일). 고른 방법 - 경로: 백엔드 new-feature.sh와 같은 복수형 규칙(backendPathSegment)으로 API_PATH 상수 하나를 둔다. 백엔드 api-base-path는 API_BASE_URL에 붙인다. - 목록: mapper가 { items, total }을 내고 total은 page?.total ?? 길이다. 빈 목록은 EmptySurface로 같은 빈 상태를 그린다. - --with-create: 상세 GET, 작성 POST, 상세·작성 라우트와 페이지, 폼 스키마 (이름 100자 = 백엔드 NAME_MAX_LENGTH), 뮤테이션 정책(commandMutationIdentity), 작성 폼 테스트를 만든다. 작성은 백엔드 기본에 맞춰 NEVER(retryBudget 0, 키 없음)다. --keyed는 백엔드 create를 IdempotencyExecutor 뒤에 둔 경우의 KEYED 값(IDEMPOTENCY_REPLAY, retryBudget 1)을 쓴다. - 작성 descriptor: acceptedStatuses [201], refusedBeforeWrite ["_INVALID"], classifyStatus는 401·403·429를 NOT_APPLIED(백엔드 보안 필터·@RequiresPermission 프록시·rate-limit interceptor가 use case 전에 거절한다). mapProblem이 _INVALID를 이름 칸 오류로 바꾼다. - 생성 테스트: gateway 테스트가 세 operation의 백엔드 본문(201 Envelope, 404 _NOT_FOUND, 400 _INVALID → NOT_APPLIED, 응답 유실 → MAYBE_APPLIED, NEVER는 키 없음·KEYED는 503 IDEMPOTENCY_UNAVAILABLE 뒤 같은 키 1회 재전송)을 손으로 적는다. 하네스 재시도 상한은 앱 기본값 2다(16-07 (3)). 작성 폼 테스트는 라우터를 거쳐 201 저장 뒤 상세 열기, 400 거절을 이름 칸에 보이고 저장 버튼이 켜진 채 다시 저장, 응답 유실 뒤 결과 불명(NEVER는 다시 보내기 없음, KEYED는 같은 Idempotency-Key로 다시 보내기)을 본다. - 페이지 테스트의 앱 조립은 -test-app.tsx 하나로 모은다. - slice 템플릿은 scripts/create-feature-write-slice.ts에 둔다. 리뷰 5.3절 재검토 조건(템플릿 2,000줄)을 넘지 않게 하고, create-feature.ts의 수정을 필요한 자리로 좁힌다. - X1: 생성한 context 선언을 임시 폴더에 써서 생성기 선언 읽기로 읽고, 그 모듈을 import해 앱 모듈 조립(라우트 루트 검사)이 기능 라우트를 받는지 보는 단위 테스트를 더한다. 버린 대안 - 작성을 기본 KEYED로: 백엔드 생성 create는 키를 읽지 않아, 같은 키 재전송이 새 항목을 만든다. 안전해 보이는 거짓 보장이다. - 참조 기능을 Envelope로 옮기기(09-06 (2)): 참조 테스트와 MSW fixture를 다수 바꾸고 problem details 예제가 사라진다. - 목록 값을 배열로 두고 total을 배열 속성으로 싣기: TanStack 구조 공유가 배열 속성을 버린다. 위험·한계 - 백엔드 생성기는 목록 엔드포인트를 만들지 않는다. 백엔드에 GET 페이지 목록을 더하기 전에는 생성 목록이 405를 받는다. descriptor 주석과 매뉴얼에 적었다. - 생성 기능의 초기 JS: 기본 +647 B, --with-create +964 B(이 브랜치 기준선 203,702 B에서 잰 값, 기능당 1 KiB 안). 기준선의 남은 여유는 1,098 B라 --with-create 기능 하나를 넣으면 134 B가 남는다. - 두 생성기를 실제로 띄워 붙여 보지는 않았다. 백엔드 템플릿의 응답 본문과 경로를 읽어 생성 테스트에 옮겼다. 검증 - RED: tests/unit/create-feature.test.ts 새 17건 실패 → GREEN 43건 통과. - 기본·--with-create·--with-create --keyed·--context reference-context --with-create 네 기능을 만든 상태에서: check:types(app·test·node), lint, check:registries(additive), check:i18n, check:architecture, check:design-system, check:diagnostics, verify:documentation 통과. 생성 기능 테스트 77건 통과. 빠른 계층 313파일 3,818건 중 참조 라우팅 테스트 1건만 실패(X1, 다음 커밋). - 변이: refusedBeforeWrite 삭제 → gateway·폼 테스트 2건 실패. 상세 GET의 responseEnvelope 삭제 → 조립 거절로 테스트와 check:registries 실패. KEYED retryBudget 0 → 503 재전송 테스트 실패. 정책의 descriptor 상수 오타 → tsc 실패. - flock 아래 build, check:bundle: 기준 203,702, 기본 기능 204,349, --with-create 기능 204,666 / 204,800 B PASS. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-06 Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-07 Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-01 --- docs/manual/01-add-a-feature.md | 18 +- docs/manual/reference/create-feature.md | 38 +- docs/manual/reference/errors.md | 1 + docs/manual/reference/patterns.md | 12 +- scripts/create-feature-write-slice.ts | 1031 +++++++++++++++++++++++ scripts/create-feature.ts | 633 ++++++++++---- tests/unit/create-feature.test.ts | 248 ++++++ 7 files changed, 1807 insertions(+), 174 deletions(-) create mode 100644 scripts/create-feature-write-slice.ts diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index d9d30b06..b8a6a1d4 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -29,10 +29,17 @@ 1단계의 생성 명령이 3~8단계와 10단계의 가장 작은 판을 한 번에 만든다. - 라우트 1개 (파라미터 없는 목록) -- GET 1개 (`SAFE`, `EXTERNAL_BEARER`) +- GET 1개 (`SAFE`, `EXTERNAL_BEARER`). 경로는 짝 백엔드 `new-feature.sh`와 같은 `/`이다 - 쿼리 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 테스트, `-test-app.tsx`) + +`--with-create`를 주면 짝 백엔드 `new-feature.sh`가 만드는 나머지 두 엔드포인트를 함께 만든다. + +- 상세 GET(`GET //{id}`)과 `DetailPage` 상세 페이지 +- 작성 POST(`POST /`, 201)와 `FormPage` 작성 폼, 결과 불명 화면 +- 작성 폼 테스트: 201 저장 뒤 상세 열기, 400 `_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 `: 0단계에서 기존 context를 골랐을 때만 준다. +- `--with-create`: 상세와 작성까지 만든다. 짝 백엔드에서 `scripts/new-feature.sh `을 같은 이름으로 돌렸을 때 준다(예: 프론트 `invoice-feature`, 백엔드 `Invoice` → 둘 다 `/invoices`). +- `--keyed`: `--with-create`와 함께만. 백엔드 create를 멱등성 executor 뒤에 두었을 때(KEYED) 준다. - `--package @scope/name@x.y.z --digest sha256:<64 hex> --revision `: 계약 패키지가 이미 배포됐을 때 준다. 셋은 함께 준다. - 둘 다 없으면 새 context와 자리표시자 계약 신원으로 만든다. - 자리표시자 신원: 패키지가 아직 없을 때 쓰는 가짜 신원이다. 로컬·개발 빌드는 되고, staging·production 승인은 거절한다. @@ -181,6 +190,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한다. +- 경로는 짝 백엔드 컨트롤러의 매핑과 같은 `/`이다. 생성된 descriptor는 `API_PATH` 상수 하나를 쓴다. 백엔드에 `--path`를 줬으면 이 상수를 같은 값으로 바꾼다. + - 백엔드의 `api-base-path`(기본 `/v1`, 로컬 `/api`)는 descriptor에 적지 않는다. `config/runtime/.json`의 `API_BASE_URL`에 붙이고 끝을 `/`로 둔다(예: `https://api.example.com/v1/`). 끝 `/`가 없으면 실행기가 `URL_ORIGIN_ESCAPED`로 보내지 않는다. + - 백엔드 생성기는 목록 엔드포인트를 만들지 않는다. 백엔드에 `GET /` 페이지 목록(`PageParams`)을 더하기 전에는 생성된 목록이 405를 받는다. - 계약 패키지(`@org-contracts/*`)는 `contracts/-contract-contribution.ts` 이름의 파일에서만 import한다. - 패키지 신원 네 필드(`packageId`, `version`, `digest`, `sourceRevision`)는 `-feature-contract.ts`의 상수 하나에 있다. 바꿀 때는 넷을 함께 바꾼다. - 근거: `scale-architecture.md` §13(재시도), §20~§22(검증 경계와 예산). diff --git a/docs/manual/reference/create-feature.md b/docs/manual/reference/create-feature.md index 326292b0..3a7d2302 100644 --- a/docs/manual/reference/create-feature.md +++ b/docs/manual/reference/create-feature.md @@ -1,23 +1,26 @@ # create:feature 참조 -모든 merge 게이트를 통과하는 가장 작은 기능을 만드는 명령이다. 정본은 `scripts/create-feature.ts`다. -템플릿 문자열이 그 파일 안에 있고, 참조 기능을 import하지 않는다. 그래서 참조 기능을 지운 프로젝트에서도 동작한다. +모든 merge 게이트를 통과하는 가장 작은 기능을 만드는 명령이다. 정본은 `scripts/create-feature.ts`이고, `--with-create`가 더하는 부분은 `scripts/create-feature-write-slice.ts`다. +템플릿 문자열이 두 파일 안에 있고, 참조 기능을 import하지 않는다. 그래서 참조 기능을 지운 프로젝트에서도 동작한다. ## 사용법 ```bash -corepack pnpm create:feature [--context ] [--package @scope/name@x.y.z --digest sha256:<64 hex> --revision ] +corepack pnpm create:feature [--context ] [--with-create [--keyed]] [--package @scope/name@x.y.z --digest sha256:<64 hex> --revision ] ``` | 인자 | 규칙 | |---|---| | `` | 케밥 표기, 40자 이하. 기존 기능·context ID와 겹치면 거부 | | `--context` | 기존 context ID. 없으면 `-context`를 새로 만든다 | +| `--with-create` | 짝 백엔드 `new-feature.sh`의 작성(`POST /`)·상세(`GET //{id}`)와 그 페이지를 더한다. 작성은 `NEVER` | +| `--keyed` | `--with-create`와 함께만. 작성을 `KEYED`로 만든다. 백엔드 create를 멱등성 executor 뒤에 둔 뒤에 쓴다 | | `--package` | `@scope/name@<정확한 버전>`. `--digest`, `--revision`과 함께만 | | `--digest` | `sha256:` + 소문자 hex 64자리 | | `--revision` | 소스 리비전. 소문자 hex 7~64자리 | - ``: ID에서 끝의 `-feature`를 뗀 것이다. `invoice-feature`면 `invoice`. 모든 전역 ID의 접두어가 된다. +- API 경로: 짝 백엔드 `new-feature.sh`와 같은 규칙이다. ``의 camel 표기 뒤에 s, x, ch, sh로 끝나면 `es`, 자음+y로 끝나면 y를 `ies`로, 그 밖에는 `s`를 붙인다. `invoice` → `/invoices`, `purchase-order` → `/purchaseOrders`, `company` → `/companies`. 백엔드의 `api-base-path`는 `API_BASE_URL`에 붙인다. - 패키지 인자가 없으면 자리표시자 신원을 쓰고 표준 오류로 경고한다. - 패키지 인자가 있으면 계약 조립기와 같은 신원 검사(`composeContractContributions`)로 형식을 확인한다. @@ -53,24 +56,41 @@ corepack pnpm create:feature [--context ] [--package @scope/nam - `presentation/-feature-runtime.ts`: 지연 로드 페이지 표 - `presentation/-routes.ts`: route ID → URL 함수(`buildRouteUrl`) - `presentation/use--items.ts`: 쿼리 바인딩 -- `presentation/-list-page.tsx`: `CollectionPage` 목록 페이지 +- `presentation/-list-page.tsx`: `CollectionPage` 목록 페이지. 결과 수는 `meta.page.total` + +`--with-create`가 더하는 파일: + +- `presentation/-route-codecs.ts`: 상세 라우트 params codec +- `presentation/use--item.ts`: 상세 쿼리 +- `presentation/use--create.ts`: 작성 뮤테이션 정책(`commandMutationIdentity`) +- `presentation/-form.ts`: 폼 스키마. 이름 길이는 요청 스키마의 상수(`_NAME_MAX_LENGTH` = 백엔드 `NAME_MAX_LENGTH` 100)를 쓴다 +- `presentation/-detail-page.tsx`: `DetailPage` +- `presentation/-create-page.tsx`: `FormPage`. 저장하면 상세를 연다. 결과 불명이면 `AsyncSurface`를 보인다 `domain/`은 만들지 않는다. 업무 규칙이 생기면 사람이 만든다. 기능 테스트 폴더 `tests/features//`: -- `-feature-input.test.ts`: input과 mapper 단위 테스트 -- `-list-page.test.tsx`: 라우터를 거치는 페이지 테스트(목록, 빈 목록, 실패 후 다시 시도) +- `-test-app.tsx`: 앱 전체를 조립해 로그인하고 URL로 들어가는 도우미. 페이지 테스트가 같이 쓴다 +- `-feature-input.test.ts`: input 단위 테스트 +- `-list-page.test.tsx`: 라우터를 거치는 페이지 테스트(목록, `meta.page.total`, 빈 목록, 실패 후 다시 시도) +- `-http-gateway.test.ts`: 짝 백엔드 본문을 손으로 적은 gateway 테스트. 하네스의 재시도 상한은 앱 기본값 2다 +- `-create-page.test.tsx`(`--with-create`): 201 저장 뒤 상세, 400 `_INVALID` 필드 오류와 다시 저장, 응답을 잃은 저장(`NEVER`는 다시 보내기 없음, `KEYED`는 같은 키로 다시 보내기) 기능 폴더 밖: - `src/contexts/-context/context-module.ts`: 새 context일 때만 -- `artifacts/tests/a11y-manual/.md`: pending 기록 +- `artifacts/tests/a11y-manual/.md`: 라우트마다 pending 기록 ## 뼈대 모양 - 라우트 1개: 파라미터·검색값 없는 목록, `session-required`, `feature-boundary`. -- GET 1개: `SAFE`, `EXTERNAL_BEARER`, 응답은 항목 배열. +- GET 1개: `SAFE`, `EXTERNAL_BEARER`, 응답은 Envelope 안의 항목 배열. 목록 값은 `{ items, total }`이다. +- `--with-create`: 라우트 `_DETAIL`(`<목록>/items/:Id`)·`_CREATE`(`<목록>/new`), operation `_GET_ITEM`·`_CREATE_ITEM`. + - 작성 `NEVER`: `retryBudget: 0`, 멱등 키 없음. 응답을 잃으면 결과 불명이고 다시 보내기 버튼이 없다. + - 작성 `KEYED`(`--keyed`): `commandRecovery` `IDEMPOTENCY_REPLAY`, `retryBudget: 1`(503 `IDEMPOTENCY_UNAVAILABLE` 뒤 같은 키로 한 번). + - 둘 다 `acceptedStatuses: [201]`, `refusedBeforeWrite: ["_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`가 모든 API에 `[]`를 답하기 때문이다. @@ -126,6 +146,8 @@ 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) - 저장소 복사본에 기능 하나를 만들고 커밋한 뒤 게이트를 돈다. - 타입, lint, 아키텍처, 레지스트리, i18n, 디자인 시스템, 진단, 문서, unit, component, integration, 기능 테스트, 커버리지, CI 계약, 빌드. diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index c41a802c..4f91086b 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -42,6 +42,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `contract package @ is not a pinned identity: ` | 패키지 신원 형식. `` 예: `: package version must be exact SemVer`, `: package digest`, `: package sourceRevision`, `: packageId` | `--package`, `--digest`, `--revision` | | `--package, --digest and --revision go together. ...` | 셋 중 일부만 줬다 | 셋을 함께 준다 | | `--package must be @scope/name@. ...` | 버전 없는 패키지 이름 | `@scope/name@1.2.3` 꼴 | +| `--keyed needs --with-create. ...` | `--keyed`만 줬다 | `--with-create --keyed` | | `refusing to overwrite: ` | 쓸 파일이나 기능 폴더가 이미 있다 | 그 경로를 확인하고 지우거나 다른 ID | | `the feature index generator rejected the feature, nothing was kept:` | 생성기가 거부했다. 만든 파일은 모두 지웠다 | 뒤따르는 생성기 메시지(아래 절) | diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index 96724a2c..16bd84de 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -3,7 +3,7 @@ 기능을 만들 때 쓰는 패턴과, 그 패턴의 정의와 예제가 어디 있는지 적는다. - **정의**: 플랫폼(기능 밖)에서 패턴을 제공하는 파일. -- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `참조 기능`은 `src/features/reference-feature/`다. +- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `참조 기능`은 `src/features/reference-feature/`다(Envelope가 아닌 problem details 모양). - 예제가 없는 패턴은 **없음**이라고 적었다. 그 패턴은 정의를 읽고 직접 쓴다. 참조 기능은 예제일 뿐이다. 복사해 이름을 바꾸지 않는다. 모양을 보고 생성 뼈대에 옮긴다. @@ -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/-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/-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/-mapper.ts` | 타입 검사 | | gateway port + HTTP 어댑터 | `src/adapters/http/index.ts`의 `createFeatureHttpBinding`, `defineFeatureHttpOperationForRoutes` | 생성 뼈대 `adapters/-http-gateway.ts` | 음성 타입 fixture (operation ID, route ID, 입력) | -| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 | +| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 쓰기 slice `adapters/-http-gateway.ts`(400 `_INVALID` → 이름 칸), 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 | | 결과와 실패 | `src/contracts/result.ts`, `src/contracts/errors.ts` | 생성 뼈대 `application/-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` | @@ -95,8 +95,8 @@ const search = (q: string) => |---|---|---|---| | 쿼리 바인딩 | `src/contracts/server-state.ts`의 `bindQuery`, `src/presentation/adapters/query/application-query.ts` | 생성 뼈대 `presentation/use--items.ts` | profile ID (실행 때). `owner`·`operationId`는 읽는 곳이 없는 `@deprecated` 칸이라 적지 않는다 | | 무효화 topic | `src/contracts/query-invalidation.ts` | 생성 뼈대 계약 `invalidation` | 조립(중복, 고아 topic) | -| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(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/-contract-contribution.ts`, `presentation/use--create.ts`), 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름), 기능 테스트 | +| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/-create-page.tsx`, 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만(쓰기 slice는 `-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/-form.ts`와 `-create-page.tsx`, 참조 기능 `presentation/reference-resource-form.ts`와 폼 페이지 | 페이지 테스트(서버 필드 오류, 이탈 확인) | | 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/-message-catalog.ts` | `lint`(문구 literal), `check:i18n`(ko-KR·en-US 키) | | 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 참조 기능 403 화면 테스트 | 가드 테스트. 역할·권한 힌트 예제는 없음 | diff --git a/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts new file mode 100644 index 00000000..95abc0ab --- /dev/null +++ b/scripts/create-feature-write-slice.ts @@ -0,0 +1,1031 @@ +/** + * 1103/09-06, 03-07. The `--with-create` slice of `pnpm create:feature`: the + * paired backend scaffold's other two endpoints + * (clean-architecture-backend-template scripts/new-feature.sh, + * `__Feature__Controller.java.tmpl`): `POST /` answers 201 with the + * new item in the Envelope, `GET //{id}` reads one. With them come a + * detail page, a create form with the unknown-result handling, and tests that + * answer with the backend's own bodies. The base templates in + * `create-feature.ts` call into this file where the slice adds to one of + * their files; the files only the slice has are rendered here whole. + * + * The backend generates a NOT_IDEMPOTENT create, which reads no + * Idempotency-Key, so the default command is NEVER: no key, no resend. + * `--keyed` is for a backend create made KEYED with its IdempotencyExecutor + * (its docs/manual/05-idempotency.md). Like the rest of the command, nothing + * here imports a sample feature. + */ + +export type WriteSemantics = "NEVER" | "KEYED"; + +export type SliceRoute = Readonly<{ + routeId: string; + path: string; + chunkId: string; + moduleId: string; + loadingSurface: string; +}>; + +export type WriteSlice = Readonly<{ + semantics: WriteSemantics; + /** The detail route's path parameter. */ + idParam: string; + detail: SliceRoute; + create: SliceRoute; + getOperationId: string; + createOperationId: string; + /** The backend scaffold's `__FEATURE___INVALID` (400) and `_NOT_FOUND` (404). */ + invalidCode: string; + notFoundCode: string; +}>; + +type SliceNames = Readonly<{ + id: string; + base: string; + upper: string; + pascal: string; + camel: string; + title: string; +}>; + +type SliceShape = Readonly<{ + names: SliceNames; + routeId: string; + apiPath: string; + write: WriteSlice; +}>; + +/** The backend aggregate's `NAME_MAX_LENGTH`; its create refuses a longer name. */ +const BACKEND_NAME_MAX_LENGTH = 100; + +export function planWriteSlice( + names: SliceNames, + listPath: string, + semantics: WriteSemantics, +): WriteSlice { + const { base, camel, upper } = names; + const route = (suffix: string, path: string): SliceRoute => + Object.freeze({ + routeId: `${upper}_${suffix.toUpperCase()}`, + path, + chunkId: `route-${base}-${suffix}`, + moduleId: `${base}-${suffix}-page`, + loadingSurface: `${base}-${suffix}`, + }); + return Object.freeze({ + semantics, + idParam: `${camel}Id`, + // `items/` keeps the detail apart from the static `new` (01 6단계). + detail: route("detail", `${listPath}/items/:${camel}Id`), + create: route("create", `${listPath}/new`), + getOperationId: `${upper}_GET_ITEM`, + createOperationId: `${upper}_CREATE_ITEM`, + invalidCode: `${upper}_INVALID`, + notFoundCode: `${upper}_NOT_FOUND`, + }); +} + +export function writeSliceMessageKeys(names: SliceNames, slice: WriteSlice): string[] { + const { camel } = names; + return [ + ...[slice.detail.routeId, slice.create.routeId].flatMap((routeId) => [ + `route.${routeId}.navigation`, + `route.${routeId}.title`, + ]), + `${camel}.list.create`, + `${camel}.detail.titlePending`, + `${camel}.detail.itemId`, + `${camel}.form.title`, + `${camel}.form.name`, + `${camel}.form.save`, + `${camel}.form.saving`, + ]; +} + +/** Route titles, ko-KR then en-US. The contract's `title` repeats ko-KR. */ +export function writeSliceRouteTitles(names: SliceNames) { + const { title } = names; + return Object.freeze({ + detail: Object.freeze({ ko: `${title} 상세`, en: `${title} detail` }), + create: Object.freeze({ ko: `${title} 만들기`, en: `New ${title}` }), + }); +} + +// --------------------------------------------------------------------------- +// Fragments the base templates insert. + +export function renderWriteRoutes({ names, write }: SliceShape): string { + const titles = writeSliceRouteTitles(names); + const entry = (route: SliceRoute, paramsSchema: string, title: string) => ` ${route.routeId}: Object.freeze({ + routeId: "${route.routeId}", + path: "${route.path}", + paramsSchema: ${paramsSchema}, + searchSchema: null, + access: "session-required", + loadingSurface: "${route.loadingSurface}", + errorSurface: "feature-boundary", + chunkId: "${route.chunkId}", + title: "${title}", + navigationLabel: null, + navigationOrder: null, + }), +`; + return ( + entry(write.detail, `"${names.pascal}Params"`, titles.detail.ko) + + entry(write.create, "null", titles.create.ko) + ); +} + +export function renderWriteRouteRuntimeContracts({ names, write }: SliceShape): string { + const entry = (route: SliceRoute, paramsCodec: string) => ` ${route.routeId}: Object.freeze({ + routeId: "${route.routeId}", + moduleId: "${route.moduleId}", + paramsCodec: "${paramsCodec}", + searchCodec: "none", + }), +`; + return entry(write.detail, `${names.pascal}Params`) + entry(write.create, "none"); +} + +export function renderWriteSchemas({ names, write }: SliceShape): string { + const { camel, pascal, upper } = names; + return ` +/** The backend aggregate's \`NAME_MAX_LENGTH\`. The request and the form share it. */ +export const ${upper}_NAME_MAX_LENGTH = ${BACKEND_NAME_MAX_LENGTH}; + +/** + * The detail route's params and the GET's input. The backend reads the id as + * a canonical UUID and answers another text with 400 BAD_PARAMETER. + */ +export const ${camel}ParamsSchema = z + .object({ + ${write.idParam}: z.string().trim().min(1).max(120), + }) + .strict(); + +export type ${pascal}Params = z.output; + +/** + * The backend's \`Create__Feature__HttpRequest\`. It has no bean validation: + * the aggregate refuses a blank or longer name with 400 ${write.invalidCode}. + */ +export const ${camel}CreateCommandSchema = z + .object({ + name: z.string().min(1).max(${upper}_NAME_MAX_LENGTH), + }) + .strict(); + +export type ${pascal}CreateRequest = z.output; +`; +} + +export function renderWriteValidators({ names }: SliceShape): string { + const { camel, pascal } = names; + return ` ${pascal}Params: zodValidator("${pascal}Params", ${camel}ParamsSchema), + ${pascal}ItemPayload: zodValidator("${pascal}ItemPayload", ${camel}ItemDtoSchema), + ${pascal}CreateCommand: zodValidator("${pascal}CreateCommand", ${camel}CreateCommandSchema), +`; +} + +export function renderWriteMapper({ names }: SliceShape): string { + const { pascal } = names; + return ` +export function map${pascal}Item( + dto: ${pascal}ItemDto, +): BoundaryMappingResult<${pascal}ItemView> { + return mappingSuccess(toView(dto)); +} +`; +} + +export function renderWriteSchemaRows({ names }: SliceShape): string { + const { pascal } = names; + const row = ( + schemaId: string, + boundary: string, + direction: string, + unknownFieldPolicy: string, + ) => ` ${schemaId}: Object.freeze({ + schemaId: "${schemaId}", + boundary: "${boundary}", + owner: OWNER, + runtime: "zod", + schemaVersion: 1, + direction: "${direction}", + unknownFieldPolicy: "${unknownFieldPolicy}", + }), +`; + return ( + row(`${pascal}Params`, "route-params", "REQUEST", "REJECT_UNKNOWN") + + row(`${pascal}ItemPayload`, "api-response", "RESPONSE", "STRIP_UNKNOWN") + + row(`${pascal}CreateCommand`, "api-request", "REQUEST", "REJECT_UNKNOWN") + ); +} + +export function renderWriteDescriptors({ names, write }: SliceShape): string { + const { base, pascal, upper } = names; + const keyed = write.semantics === "KEYED"; + const semantics = keyed + ? ` // The backend create runs behind its IdempotencyExecutor + // (http-contract.md §2): the same key replays, never applies twice. + retrySemantics: "KEYED" as const,` + : ` // new-feature.sh generates a NOT_IDEMPOTENT create: the backend reads no + // Idempotency-Key and a second request creates a second item. Make the + // backend create KEYED (its docs/manual/05-idempotency.md) before this. + retrySemantics: "NEVER" as const,`; + const recovery = keyed + ? ` // The intent's key, which the executor sends as Idempotency-Key. Recorded + // in FE-REG-API; the executor does not read it. + commandRecovery: Object.freeze({ + mode: "IDEMPOTENCY_REPLAY" as const, + operationIdentityField: "idempotencyKey", + }),` + : ` commandRecovery: null,`; + const budget = keyed + ? ` // One automatic resend, with the same key, after 503 + // IDEMPOTENCY_UNAVAILABLE (refused before the work ran). The app's + // MAX_RETRY_ATTEMPTS caps it too. A lost response is never resent on its + // own: the form offers the same-key resend. + retryBudget: 1 as const,` + : ` retryBudget: 0 as const,`; + return ` +/** + * The paired backend's \`GET //{id}\`: the item in the Envelope, or + * 404 ${write.notFoundCode}. + */ +export const ${write.getOperationId}_CONTRACT = Object.freeze({ + contract: Object.freeze({ + operationId: "${write.getOperationId}", + method: "GET" as const, + pathTemplate: \`\${API_PATH}/{id}\`, + inputValidator: ${upper}_VALIDATORS.${pascal}Params, + outputValidator: ${upper}_VALIDATORS.${pascal}ItemPayload, + 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, + responseEnvelope: "ENVELOPE_V1" as const, + commandRecovery: null, + commandEffect: null, + projectRequest(input: ${pascal}Params) { + return Object.freeze({ + pathValues: Object.freeze({ id: input.${write.idParam} }), + queryEntries: Object.freeze([]), + body: null, + }); + }, + }), + frontend: Object.freeze({ + policyId: "${upper}_GET_V1", + requestByteLimit: 0, + responseByteLimit: 32_768, + totalDeadlineMs: 10_000, + retryBudget: 2 as const, + authProfileId: "EXTERNAL_BEARER", + diagnosticsOperation: "${base}.detail", + }), +}) satisfies InstalledHttpContract<${pascal}Params, ${pascal}ItemDto, ${pascal}Problem>; + +/** + * 1103/03-01. Whether a failed create applied. The executor's backend table + * decides 400, 409, 422 and the backend's own 5xx answers; \`classifyProblem\` + * gets every other status. + */ +const ${upper}_CREATE_EFFECT: CommandEffectDescriptor<${pascal}Problem> = Object.freeze({ + successEffect: "APPLIED_CONFIRMED" as const, + classifyProblem: () => "MAYBE_APPLIED" as const, + // The backend refuses these before the use case runs: 401 in the security + // filter chain, 403 at the use case's @RequiresPermission proxy, 429 in the + // rate-limit interceptor. Recheck if the use case asks AuthorizationPort + // after it writes. + classifyStatus: () => "NOT_APPLIED" as const, + // CreateUseCase checks the name before its transaction. List a + // code here only when the endpoint raises it before any write. + refusedBeforeWrite: Object.freeze(["${write.invalidCode}"]), +}); + +/** The paired backend's \`POST /\`: 201 with the new item in the Envelope. */ +export const ${write.createOperationId}_CONTRACT = Object.freeze({ + contract: Object.freeze({ + operationId: "${write.createOperationId}", + method: "POST" as const, + pathTemplate: API_PATH, + inputValidator: ${upper}_VALIDATORS.${pascal}CreateCommand, + outputValidator: ${upper}_VALIDATORS.${pascal}ItemPayload, + problemValidator: ${upper}_VALIDATORS.${pascal}Problem, + acceptedStatuses: Object.freeze([201]), + emptyBodyStatuses: Object.freeze([]), +${semantics} + requestBody: "JSON" as const, + responseBody: "REQUIRED_JSON" as const, + responseEnvelope: "ENVELOPE_V1" as const, +${recovery} + commandEffect: ${upper}_CREATE_EFFECT, + projectRequest(input: ${pascal}CreateRequest) { + return Object.freeze({ + pathValues: Object.freeze({}), + queryEntries: Object.freeze([]), + body: Object.freeze({ name: input.name }), + }); + }, + }), + frontend: Object.freeze({ + policyId: "${upper}_CREATE_V1", + requestByteLimit: 4_096, + responseByteLimit: 32_768, + totalDeadlineMs: 10_000, +${budget} + authProfileId: "EXTERNAL_BEARER", + diagnosticsOperation: "${base}.create", + }), +}) satisfies InstalledHttpContract<${pascal}CreateRequest, ${pascal}ItemDto, ${pascal}Problem>; +`; +} + +export function renderWriteMessages({ names, write }: SliceShape, locale: "ko" | "en"): string { + const { camel } = names; + const titles = writeSliceRouteTitles(names); + const copy = + locale === "ko" + ? { + create: "새 항목 만들기", + titlePending: `${names.title} 항목`, + itemId: "ID", + formTitle: titles.create.ko, + name: "이름", + save: "저장", + saving: "저장 중…", + } + : { + create: "Create item", + titlePending: `${names.title} item`, + itemId: "ID", + formTitle: titles.create.en, + name: "Name", + save: "Save", + saving: "Saving…", + }; + return ` "route.${write.detail.routeId}.navigation": "${titles.detail[locale]}", + "route.${write.detail.routeId}.title": "${titles.detail[locale]}", + "route.${write.create.routeId}.navigation": "${titles.create[locale]}", + "route.${write.create.routeId}.title": "${titles.create[locale]}", + "${camel}.list.create": "${copy.create}", + "${camel}.detail.titlePending": "${copy.titlePending}", + "${camel}.detail.itemId": "${copy.itemId}", + "${camel}.form.title": "${copy.formTitle}", + "${camel}.form.name": "${copy.name}", + "${camel}.form.save": "${copy.save}", + "${camel}.form.saving": "${copy.saving}", +`; +} + +export function renderWriteGatewayOperations({ names, write }: SliceShape): string { + const { pascal } = names; + return ` ${write.getOperationId}: define${pascal}HttpOperation({ + contract: ${write.getOperationId}_CONTRACT, + routeId: "${write.detail.routeId}", + mapSuccess: map${pascal}Item, + }), + ${write.createOperationId}: define${pascal}HttpOperation({ + contract: ${write.createOperationId}_CONTRACT, + routeId: "${write.create.routeId}", + mapSuccess: map${pascal}Item, + // The scaffold aggregate has one rule, on the name: show the backend's + // refusal on that field. Map each field the aggregate grows. + mapProblem: (problem) => + problem.code === "${write.invalidCode}" + ? Object.freeze({ + kind: "VALIDATION_REJECTED" as const, + code: problem.code, + validationIssues: Object.freeze([Object.freeze({ path: "name", code: "INVALID" })]), + }) + : undefined, + }), +`; +} + +export function renderWriteGatewayMethods({ write }: SliceShape): string { + return ` get(${write.idParam}, context) { + return http.execute("${write.getOperationId}", Object.freeze({ ${write.idParam} }), context); + }, + create(command, context) { + return http.execute("${write.createOperationId}", command, context); + }, +`; +} + +// --------------------------------------------------------------------------- +// Files only the slice has. + +export function renderRouteCodecs({ names }: SliceShape): string { + const { base, camel, pascal, upper } = names; + return `import { ${camel}ParamsSchema } from "../contracts/${base}-schemas.ts"; + +/** + * The route codecs, keyed by the codec ids \`routeRuntimeContracts\` names. + * They load with the context routes (\`context-routes.ts\` puts them on each + * handle), not with the declaration in the initial chunk. + */ +export const ${upper}_ROUTE_CODECS = { + ${pascal}Params: ${camel}ParamsSchema, +} as const; +`; +} + +export function renderUseItem({ names }: SliceShape): string { + const { base, pascal, upper } = names; + return `import { bindQuery, type QueryResultMeasure } from "../../../contracts/server-state.ts"; +import { useApplicationQuery } from "../../../presentation/adapters/query/application-query.ts"; +import { useServerStateScope } from "../../../presentation/adapters/query/server-state-scope-provider.tsx"; +import { useApplicationFeature } from "../../../presentation/providers/application-provider.tsx"; +import { + ${upper}_FEATURE_ID, + ${upper}_ITEM_QUERY_NAMESPACE, +} from "../contracts/${base}-feature-contract.ts"; +import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; + +const UTF8 = new TextEncoder(); + +function measureItem(item: ${pascal}ItemView): QueryResultMeasure { + return { + itemCount: 1, + estimatedBytes: UTF8.encode(item.itemId).byteLength + UTF8.encode(item.name).byteLength + 16, + }; +} + +/** One item. A save of this feature invalidates its namespace, so a new item shows. */ +export function use${pascal}Item(itemId: string) { + const input = useApplicationFeature(${upper}_FEATURE_ID); + const scope = useServerStateScope(); + return useApplicationQuery( + bindQuery( + { + definitionId: "${base}-item-detail-v1", + definitionVersion: 1, + namespace: ${upper}_ITEM_QUERY_NAMESPACE, + profileId: "DETAIL_STANDARD", + measureResult: measureItem, + execute: (selected: string, { signal }) => input.getItem(selected, { signal }), + }, + itemId, + scope, + ), + ); +} +`; +} + +export function renderUseCreate({ names, write }: SliceShape): string { + const { base, pascal, upper } = names; + return `import { + commandMutationIdentity, + type BoundMutation, +} from "../../../contracts/server-state.ts"; +import { useApplicationMutation } 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 type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts"; +import { ${write.createOperationId}_CONTRACT } from "../contracts/${base}-contract-contribution.ts"; +import { + ${upper}_FEATURE_ID, + ${upper}_ITEM_INVALIDATION_TOPIC, +} from "../contracts/${base}-feature-contract.ts"; +import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; + +/** + * 1103/16-05. The operation id and whether the intent carries an + * idempotency key are the descriptor's. A second save while one runs is + * refused, and a saved item invalidates the list and the detail. + */ +const ${upper}_CREATE_MUTATION_POLICY = Object.freeze({ + definitionId: "${base}-create-v1", + definitionVersion: 1, + ...commandMutationIdentity(${write.createOperationId}_CONTRACT), + duplicatePolicy: "REJECT_WHILE_ACTIVE" as const, + invalidate: Object.freeze([${upper}_ITEM_INVALIDATION_TOPIC]), +}); + +export function use${pascal}Create() { + const input = useApplicationFeature(${upper}_FEATURE_ID); + const scope = useServerStateScope(); + const mutation: BoundMutation<${pascal}CreateCommand, ${pascal}ItemView> = Object.freeze({ + ...${upper}_CREATE_MUTATION_POLICY, + scope, + execute: input.createItem, + }); + return useApplicationMutation(mutation); +} +`; +} + +export function renderForm({ names }: SliceShape): string { + const { base, camel, pascal, upper } = names; + return `import { z } from "../../../contracts/zod.ts"; +import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts"; +import { ${upper}_NAME_MAX_LENGTH } from "../contracts/${base}-schemas.ts"; + +/** What the user types. The length comes from the request schema's constant. */ +export const ${camel}FormSchema = z + .object({ + name: z.string().trim().min(1).max(${upper}_NAME_MAX_LENGTH), + }) + .strict(); + +export type ${pascal}FormValues = z.infer; + +export const ${upper}_FORM_DEFAULTS: ${pascal}FormValues = Object.freeze({ name: "" }); + +export function to${pascal}CreateCommand(values: ${pascal}FormValues): ${pascal}CreateCommand { + return Object.freeze({ name: values.name }); +} +`; +} + +export function renderDetailPage({ names, routeId }: SliceShape): string { + const { base, camel, pascal } = names; + return `import { Link } from "react-router-dom"; + +import { + AsyncSurface, + DetailPage, +} from "../../../presentation/design-system/index.ts"; +import { useLocale } from "../../../presentation/i18n/index.ts"; +import { ${camel}RouteUrl, use${pascal}ItemId } from "./${base}-routes.ts"; +import { use${pascal}Item } from "./use-${base}-item.ts"; + +/** The heading stays while the item loads or fails, so the page always has an h1. */ +export default function ${pascal}DetailPage() { + const { message } = useLocale(); + const itemId = use${pascal}ItemId(); + const query = use${pascal}Item(itemId); + const item = query.data; + return ( + {message("${camel}.list.title")}} + heading={{ title: item?.name ?? message("${camel}.detail.titlePending") }} + metadata={ + item ? ( +
+
{message("${camel}.detail.itemId")}
+
{item.itemId}
+
+ ) : null + } + feedback={} + /> + ); +} +`; +} + +export function renderCreatePage({ names, routeId, write }: SliceShape): string { + const { base, camel, pascal, upper } = names; + return `import { useCallback } from "react"; +import { Link, useNavigate } from "react-router-dom"; + +import type { Result } from "../../../contracts/result.ts"; +import { + AsyncSurface, + Button, + DirtyNavigationDialog, + ErrorSummary, + Form, + FormActions, + FormFailureStatus, + FormField, + FormPage, + useAppForm, + useDirtyNavigationGuard, +} from "../../../presentation/design-system/index.ts"; +import { useLocale } from "../../../presentation/i18n/index.ts"; +import type { ${pascal}CreateCommand } from "../application/${base}-feature-api.ts"; +import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; +import { + ${upper}_FORM_DEFAULTS, + ${camel}FormSchema, + to${pascal}CreateCommand, + type ${pascal}FormValues, +} from "./${base}-form.ts"; +import { ${camel}RouteUrl } from "./${base}-routes.ts"; +import { use${pascal}Create } from "./use-${base}-create.ts"; + +/** + * The create form. A saved item opens its detail page. The backend's refusal + * of the name (400 ${write.invalidCode}, refused before the write) shows on + * the field and the form saves again. A save whose result is unknown (the + * response was lost) keeps the form: the user checks, or, for a KEYED + * command, resends the same request with the same key. + */ +export default function ${pascal}CreatePage() { + const navigate = useNavigate(); + const { message } = useLocale(); + const fieldLabels = { + name: message("${camel}.form.name"), + } satisfies Record; + const mutation = use${pascal}Create(); + const openSaved = useCallback( + (outcome: Result<${pascal}ItemView> | null) => { + if (outcome?.ok) { + void navigate( + ${camel}RouteUrl("${write.detail.routeId}", { + params: { ${write.idParam}: outcome.value.itemId }, + }), + ); + } + return outcome; + }, + [navigate], + ); + const submit = useCallback( + async (command: ${pascal}CreateCommand) => { + const outcome = await mutation.submit(command); + openSaved(outcome); + return outcome; + }, + [mutation, openSaved], + ); + const form = useAppForm({ + schema: ${camel}FormSchema, + defaultValues: ${upper}_FORM_DEFAULTS, + allowedServerFields: ["name"], + mapToCommand: to${pascal}CreateCommand, + submit, + }); + const effectUnknown = mutation.state.indicator === "mutation-effect-unknown"; + const blocked = effectUnknown || mutation.state.indicator === "mutation-pending"; + const guard = useDirtyNavigationGuard(form.dirty && !form.pending); + + return ( +
{ + if (blocked) { + event.preventDefault(); + return; + } + void form.submitForm(event); + }} + > + {message("${camel}.list.title")}} + heading={{ title: message("${camel}.form.title") }} + errorSummary={ + + } + fields={ + + } + formActions={ + + {/* Busy, not disabled, while saving: a disabled button drops + keyboard focus (1103/08-02). */} + + + } + feedback={ + form.failure ? ( + void form.submitForm() : undefined} + /> + ) : effectUnknown ? ( + { + void mutation.reconcileUnknownEffect(resolution).then(form.settleApplied); + }} + // Drawn only for a request with a key (a KEYED command). + onResendUnknownEffect={() => { + void form.resendUnknown(async () => openSaved(await mutation.resendUnknownEffect())); + }} + /> + ) : null + } + guard={} + /> + + ); +} +`; +} + +export function renderCreatePageTest({ names, apiPath, write }: SliceShape): string { + const { base, camel, upper } = names; + const keyed = write.semantics === "KEYED"; + const unknownTest = keyed + ? ` // KEYED: the key is kept, and the resend carries it, so the backend's + // IdempotencyExecutor replays the first request instead of applying twice. + it("resends a create whose response was lost with the same key", async () => { + const posts = answerCreate(() => HttpResponse.error()); + const user = await openForm(); + await user.type(await nameField(), "First item"); + await user.click(saveButton()); + expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible(); + expect(saveButton()).toBeDisabled(); + + answerCreate(() => created(), posts); + answerItem(); + await user.click(screen.getByRole("button", { name: KO_MESSAGES["action.resendMutation"] })); + + expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible(); + expect(posts).toHaveLength(2); + expect(posts[0]!.headers.get("idempotency-key")).toMatch(/^[\\x21-\\x7e]+$/u); + expect(posts[1]!.headers.get("idempotency-key")).toBe(posts[0]!.headers.get("idempotency-key")); + });` + : ` // NEVER: the backend scaffold's create reads no key, so a resend would be a + // second, unprotected create. The form keeps the unknown result and offers + // no resend; the user checks the list. + it("keeps a create whose response was lost unknown and offers no resend", async () => { + const posts = answerCreate(() => HttpResponse.error()); + const user = await openForm(); + await user.type(await nameField(), "First item"); + await user.click(saveButton()); + + expect(await screen.findByText(KO_MESSAGES["async.mutationEffectUnknown"])).toBeVisible(); + expect( + screen.queryByRole("button", { name: KO_MESSAGES["action.resendMutation"] }), + ).toBeNull(); + expect(saveButton()).toBeDisabled(); + expect(posts).toHaveLength(1); + expect(posts[0]!.headers.get("idempotency-key")).toBeNull(); + });`; + return `// @vitest-environment jsdom + +import { screen } from "@testing-library/react"; +import { http, HttpResponse, type JsonBodyType } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; + +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 { API, openSignedIn } from "./${base}-test-app.tsx"; + +const MESSAGES = ${upper}_MESSAGE_CATALOGS["ko-KR"]; +const ITEM_ID = "0b6f2c1e-5d4a-4f3b-9c2d-1a2b3c4d5e6f"; +const META = { requestId: "req-1", traceId: "0af7651916cd43dd8448eb211c80319c" }; + +const api = setupServer(); +beforeAll(() => api.listen({ onUnhandledRequest: "error" })); +afterEach(() => api.resetHandlers()); +afterAll(() => api.close()); + +/** + * The paired backend's answers, written out (new-feature.sh's controller and + * http-contract.md §1), not taken from the shared scenarios: a descriptor + * that stops reading this wire fails here. + */ +function created() { + return HttpResponse.json( + { success: true, data: { id: ITEM_ID, name: "First item" }, meta: META }, + { status: 201, headers: { Location: \`\${API}${apiPath}/\${ITEM_ID}\` } }, + ); +} + +function refusedName() { + return HttpResponse.json( + { + success: false, + error: { + code: "${write.invalidCode}", + category: "VALIDATION", + message: "backend message", + retryable: false, + }, + meta: META, + }, + { status: 400 }, + ); +} + +/** Answers POST ${apiPath} and keeps a copy of each request it receives. */ +function answerCreate(respond: () => Response, posts: Request[] = []) { + api.use( + http.post(\`\${API}${apiPath}\`, ({ request }) => { + posts.push(request.clone()); + return respond(); + }), + ); + return posts; +} + +function answerItem(body: JsonBodyType = { id: ITEM_ID, name: "First item" }) { + api.use( + http.get(\`\${API}${apiPath}/:id\`, () => + HttpResponse.json({ success: true, data: body, meta: META }), + ), + ); +} + +async function openForm() { + const user = await openSignedIn(${camel}RouteUrl("${write.create.routeId}")); + expect( + await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.form.title"] }), + ).toBeVisible(); + return user; +} + +// The label also holds the required mark, so the name is matched, not equal. +const nameField = () => + screen.findByRole("textbox", { name: new RegExp(MESSAGES["${camel}.form.name"], "u") }); +const saveButton = () => screen.getByRole("button", { name: MESSAGES["${camel}.form.save"] }); + +describe("${names.id} create form on the paired backend", () => { + it("saves a new item and opens it", async () => { + const posts = answerCreate(created); + answerItem(); + const user = await openForm(); + await user.type(await nameField(), " First item "); + await user.click(saveButton()); + + expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible(); + expect(await posts[0]!.json()).toEqual({ name: "First item" }); + }); + + // 1103/03-01. refusedBeforeWrite makes this NOT_APPLIED, so the form takes + // the next save instead of holding an unknown result. + it("shows the backend's refusal of the name on the field and saves again", async () => { + const posts = answerCreate(refusedName); + const user = await openForm(); + await user.type(await nameField(), "Refused name"); + await user.click(saveButton()); + + expect(await screen.findAllByText(KO_MESSAGES["form.validation.invalid"])).not.toHaveLength(0); + expect(await nameField()).toHaveAttribute("aria-invalid", "true"); + expect(saveButton()).toBeEnabled(); + + answerCreate(created, posts); + answerItem(); + await user.clear(await nameField()); + await user.type(await nameField(), "First item"); + await user.click(saveButton()); + + expect(await screen.findByRole("heading", { level: 1, name: "First item" })).toBeVisible(); + expect(posts).toHaveLength(2); + }); + +${unknownTest} +}); +`; +} + +/** The gateway test cases of the slice, inside the base gateway test's describe. */ +export function renderWriteGatewayTests({ names, apiPath, write }: SliceShape): string { + const keyed = write.semantics === "KEYED"; + const keyCases = keyed + ? ` + // http-contract.md §2: refused before the work ran, to be resent with the + // same key. The only answer the executor resends on its own (retryBudget 1). + it("sends the intent's key, and resends once with it after 503 IDEMPOTENCY_UNAVAILABLE", async () => { + const keys = answerCreate(201, CREATED_BODY); + // Registered last, so it answers first, once. + answerCreate(503, failure("IDEMPOTENCY_UNAVAILABLE", undefined, "TRANSIENT_DEPENDENCY"), keys, true); + + await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toEqual({ + ok: true, + value: { itemId: ITEM_ID, name: "First item" }, + }); + expect(keys).toEqual(["key-1", "key-1"]); + }); + + it("refuses a create without the intent's key before sending", async () => { + const keys = answerCreate(201, CREATED_BODY); + + await expect(gateway().create({ name: "First item" }, {} as never)).resolves.toMatchObject({ + ok: false, + }); + expect(keys).toEqual([]); + });` + : ` + it("sends no idempotency key: the backend scaffold's create reads none", async () => { + const keys = answerCreate(201, CREATED_BODY); + + await gateway().create({ name: "First item" }, { intent: INTENT }); + expect(keys).toEqual([null]); + });`; + return ` + it("reads one item, and the backend's not-found code", async () => { + api.use( + http.get(\`\${API}${apiPath}/\${ITEM_ID}\`, () => + HttpResponse.json({ success: true, data: { id: ITEM_ID, name: "First item" }, meta: META }), + ), + ); + await expect(gateway().get(ITEM_ID)).resolves.toEqual({ + ok: true, + value: { itemId: ITEM_ID, name: "First item" }, + }); + + api.use( + http.get(\`\${API}${apiPath}/\${ITEM_ID}\`, () => + HttpResponse.json(failure("${write.notFoundCode}", undefined, "NOT_FOUND"), { status: 404 }), + ), + ); + await expect(gateway().get(ITEM_ID)).resolves.toMatchObject({ + ok: false, + error: { kind: "NOT_FOUND", code: "${write.notFoundCode}", httpStatus: 404 }, + }); + }); + + it("reads the 201 Envelope of a create", async () => { + answerCreate(201, CREATED_BODY); + + await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toEqual({ + ok: true, + value: { itemId: ITEM_ID, name: "First item" }, + }); + }); + + // 1103/03-01. Declared in refusedBeforeWrite: not applied, shown on the field. + it("reads 400 ${write.invalidCode} as not applied, on the name field", async () => { + answerCreate(400, failure("${write.invalidCode}")); + + await expect(gateway().create({ name: "Refused" }, { intent: INTENT })).resolves.toMatchObject({ + ok: false, + error: { + kind: "VALIDATION_REJECTED", + code: "${write.invalidCode}", + effect: "NOT_APPLIED", + validationIssues: [{ path: "name", code: "INVALID" }], + }, + }); + }); + + it("leaves a create whose response was lost maybe applied, and does not resend it", async () => { + const keys: (string | null)[] = []; + api.use( + http.post(\`\${API}${apiPath}\`, ({ request }) => { + keys.push(request.headers.get("idempotency-key")); + return HttpResponse.error(); + }), + ); + + await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toMatchObject({ + ok: false, + error: { effect: "MAYBE_APPLIED" }, + }); + expect(keys).toHaveLength(1); + }); +${keyCases} +`; +} + +/** The slice's helpers for the gateway test, after its own. */ +export function renderWriteGatewayHelpers({ apiPath, write }: SliceShape): string { + const key = + write.semantics === "KEYED" + ? ` + idempotencyKey: "key-1",` + : ""; + return ` +const ITEM_ID = "0b6f2c1e-5d4a-4f3b-9c2d-1a2b3c4d5e6f"; +const CREATED_BODY = { success: true, data: { id: ITEM_ID, name: "First item" }, meta: META }; +const INTENT = defineMutationIntent({ + intentId: "intent-1", + operationId: "${write.createOperationId}", + canonicalInputIdentity: "create-1",${key} + createdAtMonotonicMs: 0, +}); + +/** + * Answers POST ${apiPath} and records the Idempotency-Key each request + * carried (\`null\` when none). The handler registered last answers first. + */ +function answerCreate( + status: number, + body: JsonBodyType, + keys: (string | null)[] = [], + once = false, +) { + api.use( + http.post( + \`\${API}${apiPath}\`, + ({ request }) => { + keys.push(request.headers.get("idempotency-key")); + return HttpResponse.json(body, { status }); + }, + { once }, + ), + ); + return keys; +} +`; +} diff --git a/scripts/create-feature.ts b/scripts/create-feature.ts index c1e565d6..a929fdc6 100644 --- a/scripts/create-feature.ts +++ b/scripts/create-feature.ts @@ -10,15 +10,44 @@ 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 ` writes the smallest feature that passes every * merge gate: one list route without params, one GET (SAFE, EXTERNAL_BEARER), * one query, one invalidation topic, one CollectionPage with ko-KR and en-US - * copy, and a router page test plus an input test. The templates live in this - * file and import nothing from a sample feature, so the command keeps working - * after a product deletes the sample (test:sample-removal runs it there). + * 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 + * (`/`, 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. @@ -54,6 +83,8 @@ 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<{ @@ -65,6 +96,8 @@ export type FeaturePlan = Readonly<{ 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; }>; @@ -86,6 +119,17 @@ export function randomTopicSuffix(): string { .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) @@ -210,11 +254,23 @@ export function planFeature( const routePath = existing ? `/${contextRoot}/${names.base}` : `/${contextRoot}`; const routeId = `${names.upper}_LIST`; const chunkId = `route-${names.base}-list`; - for (const route of installed.routes) { - if (route.routeId === routeId || route.path === routePath || route.chunkId === chunkId) { - fail( - `route ${routeId} (${routePath}, ${chunkId}) collides with installed route ${route.routeId} (${route.path}, ${route.chunkId})`, - ); + const 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 = [ @@ -224,6 +280,7 @@ export function planFeature( `${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) { @@ -255,9 +312,10 @@ export function planFeature( navigationOrder, topic, operationId: `${names.upper}_LIST_ITEMS`, - apiPath: `/api/${names.base}-items`, + apiPath: `/${backendPathSegment(names.camel)}`, owner: `feature-frontend-${id}`, contractPackage: request.contractPackage ?? null, + write, }); const feature = `src/features/${id}`; @@ -290,10 +348,32 @@ export function planFeature( [`${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)], - [`artifacts/tests/a11y-manual/${routeId}.md`, renderA11yRecord(routeId)], + ...(write + ? ([ + [ + `tests/features/${id}/${base}-create-page.test.tsx`, + renderCreatePageTest({ ...shape, write }), + ], + ] as const) + : []), + ...planned.map( + (route) => + [`artifacts/tests/a11y-manual/${route.routeId}.md`, renderA11yRecord(route.routeId)] as const, + ), ]); return Object.freeze({ id, @@ -303,6 +383,9 @@ export function planFeature( routePath, topic, placeholder: request.contractPackage === undefined, + routes: Object.freeze( + planned.map((route) => Object.freeze({ routeId: route.routeId, path: route.path })), + ), files, }); } @@ -319,6 +402,8 @@ type Shape = Readonly<{ 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`."; @@ -386,13 +471,13 @@ export const FEATURE_RUNTIME = defineFeatureRuntime({ `; } -function renderContextRoutes({ names }: Shape): string { +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\`). @@ -404,7 +489,9 @@ export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze( path: definition.path, handle: Object.freeze({ routeId: definition.routeId, - runtime: ${upper}_ROUTE_RUNTIME[definition.routeId], + runtime: ${upper}_ROUTE_RUNTIME[definition.routeId],${ + write ? `\n codecs: ${upper}_ROUTE_CODECS,` : "" + } }), }), ), @@ -493,7 +580,7 @@ export const ${upper}_FEATURE_CONTRACT = Object.freeze({ navigationLabel: "${names.title}", navigationOrder: ${shape.navigationOrder}, }), - }), +${shape.write ? renderWriteRoutes({ ...shape, write: shape.write }) : ""} }), routeRuntimeContracts: Object.freeze({ ${routeId}: Object.freeze({ routeId: "${routeId}", @@ -501,7 +588,7 @@ export const ${upper}_FEATURE_CONTRACT = Object.freeze({ 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]), @@ -520,7 +607,8 @@ export const ${upper}_FEATURE_CONTRACT = Object.freeze({ `; } -function renderSchemas({ names }: Shape): string { +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"; @@ -554,7 +642,7 @@ export const ${camel}ProblemSchema = z .strip(); export type ${pascal}Problem = z.output; - +${write ? renderWriteSchemas({ ...shape, write }) : ""} export const ${upper}_VALIDATORS = Object.freeze({ ${pascal}NoRequest: zodValidator("${pascal}NoRequest", ${camel}NoRequestSchema), ${pascal}ItemListPayload: zodValidator( @@ -562,11 +650,12 @@ export const ${upper}_VALIDATORS = Object.freeze({ ${camel}ItemListPayloadSchema, ), ${pascal}Problem: zodValidator("${pascal}Problem", ${camel}ProblemSchema), -}); +${write ? renderWriteValidators({ ...shape, write }) : ""}}); `; } -function renderMapper({ names }: Shape): string { +function renderMapper(shape: Shape): string { + const { names, write } = shape; const { base, pascal } = names; return `import { mappingSuccess, @@ -577,6 +666,21 @@ 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 @@ -584,17 +688,16 @@ export type ${pascal}ItemView = Readonly<{ itemId: string; name: string }>; */ export function map${pascal}ItemList( payload: readonly ${pascal}ItemDto[], -): BoundaryMappingResult { - return mappingSuccess( - Object.freeze( - payload.map((dto) => Object.freeze({ itemId: dto.id, name: dto.name })), - ), - ); + { 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({ names, owner }: Shape): string { +function renderSchemaMetadata(shape: Shape): string { + const { names, owner, write } = shape; const { pascal, upper } = names; return `const OWNER = "${owner}"; @@ -635,14 +738,15 @@ export const ${upper}_SCHEMA_METADATA = Object.freeze({ direction: "RESPONSE", unknownFieldPolicy: "STRIP_UNKNOWN", }), -} as const); +${write ? renderWriteSchemaRows({ ...shape, write }) : ""}} as const); `; } -function renderContractContribution({ names, operationId, apiPath }: Shape): string { +function renderContractContribution(shape: Shape): string { + const { names, operationId, apiPath, write } = shape; const { base, pascal, upper } = names; return `import type { - InstalledContractContribution, + ${write ? "CommandEffectDescriptor,\n " : ""}InstalledContractContribution, InstalledHttpContract, } from "../../../contracts/external-contract-runtime.ts"; import { @@ -651,10 +755,20 @@ import { } from "./${base}-feature-contract.ts"; import { ${upper}_VALIDATORS, - type ${pascal}ItemDto, + 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 @@ -666,7 +780,7 @@ export const ${operationId}_CONTRACT = Object.freeze({ contract: Object.freeze({ operationId: "${operationId}", method: "GET" as const, - pathTemplate: "${apiPath}", + pathTemplate: API_PATH, inputValidator: ${upper}_VALIDATORS.${pascal}NoRequest, outputValidator: ${upper}_VALIDATORS.${pascal}ItemListPayload, problemValidator: ${upper}_VALIDATORS.${pascal}Problem, @@ -675,8 +789,10 @@ export const ${operationId}_CONTRACT = Object.freeze({ retrySemantics: "SAFE" as const, requestBody: "NONE" as const, responseBody: "REQUIRED_JSON" as const, - // The paired backend wraps every JSON body (http-contract.md §1). Drop - // this line for a backend that sends the DTO and problem details bare. + // 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). Drop the line from all of them for a backend that + // sends the DTO and problem details bare. responseEnvelope: "ENVELOPE_V1" as const, commandRecovery: null, commandEffect: null, @@ -702,7 +818,7 @@ export const ${operationId}_CONTRACT = Object.freeze({ readonly ${pascal}ItemDto[], ${pascal}Problem >; - +${write ? renderWriteDescriptors({ ...shape, write }) : ""} export const ${upper}_CONTRACT_CONTRIBUTION: InstalledContractContribution = Object.freeze({ contributionId: "${names.id}-http-v1", @@ -712,14 +828,19 @@ export const ${upper}_CONTRACT_CONTRIBUTION: InstalledContractContribution = package: ${upper}_CONTRACT_PACKAGE, }), http: Object.freeze([ - ${operationId}_CONTRACT, + ${operationId}_CONTRACT,${ + write + ? `\n ${write.getOperationId}_CONTRACT,\n ${write.createOperationId}_CONTRACT,` + : "" + } ]) as readonly InstalledHttpContract[], events: Object.freeze([]), }); `; } -function renderMessageCatalog({ names, routeId }: Shape): string { +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({ @@ -730,7 +851,7 @@ export const ${upper}_MESSAGE_CATALOGS = Object.freeze({ "${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}", @@ -738,28 +859,52 @@ export const ${upper}_MESSAGE_CATALOGS = Object.freeze({ "${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({ names }: Shape): string { +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"; -import type { Result } from "../../../contracts/result.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}ItemView } from "../contracts/${base}-mapper.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>; + listItems(context?: ${pascal}CallContext): Promise>;${ + write + ? ` + getItem(itemId: string, context?: ${pascal}CallContext): Promise>; + createItem( + command: ${pascal}CreateCommand, + context: ${pascal}CommandContext, + ): Promise>;` + : "" + } }>; declare module "../../../application/ports/in/application-api.ts" { @@ -770,7 +915,16 @@ declare module "../../../application/ports/in/application-api.ts" { /** The port the feature's HTTP adapter implements. */ export type ${pascal}Gateway = Readonly<{ - list(context?: ${pascal}CallContext): Promise>; + list(context?: ${pascal}CallContext): Promise>;${ + write + ? ` + get(${write.idParam}: string, context?: ${pascal}CallContext): Promise>; + create( + command: ${pascal}CreateCommand, + context: ${pascal}CommandContext, + ): Promise>;` + : "" + } }>; export function create${pascal}FeatureInput( @@ -779,34 +933,57 @@ export function create${pascal}FeatureInput( ): ${pascal}FeatureInput { // scale-architecture.md §24, §26: telemetry is best-effort and never changes the result. const events = failOpenTelemetryPort(telemetry); + function reported(kind: string, result: Result): Result { + 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) { - const result = await gateway.list(context); - if (!result.ok && result.error.kind !== "REQUEST_ABORTED") { - void events.emit({ - kind: "${base}.list.failed", - severity: "warning", - featureId: ${upper}_FEATURE_ID, - payload: Object.freeze({ reason: result.error.kind }), - }); - } - return result; + 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({ names, operationId, routeId }: Shape): string { +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 } from "../contracts/${base}-contract-contribution.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 { map${pascal}ItemList } from "../contracts/${base}-mapper.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 @@ -816,9 +993,10 @@ 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, }), -} as const); +${write ? renderWriteGatewayOperations({ ...shape, write }) : ""}} as const); export function create${pascal}HttpGateway( http: FeatureHttpBinding, @@ -827,7 +1005,7 @@ export function create${pascal}HttpGateway( list(context) { return http.execute("${operationId}", Object.freeze({}), context); }, - }); +${write ? renderWriteGatewayMethods({ ...shape, write }) : ""} }); } `; } @@ -859,23 +1037,30 @@ export const ${upper}_FEATURE_ADAPTER_CONTRIBUTION = defineFeatureAdapterContrib `; } -function renderRouteRuntime({ names, routeId }: Shape): string { +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 = { - ${routeId}: Object.freeze({ - moduleId: "${base}-list-page", - Component: lazy(() => import("./${base}-list-page.tsx")), - }), -} as const; +${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 }: Shape): string { - const { base, camel, upper } = names; - return `import { buildRouteUrl } from "../../../presentation/routes/route-codecs.ts"; +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"; /** @@ -889,6 +1074,29 @@ export function ${camel}RouteUrl( ): 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[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}; +} `; } @@ -902,7 +1110,7 @@ import { ${upper}_FEATURE_ID, ${upper}_ITEM_QUERY_NAMESPACE, } from "../contracts/${base}-feature-contract.ts"; -import type { ${pascal}ItemView } from "../contracts/${base}-mapper.ts"; +import type { ${pascal}ItemList } from "../contracts/${base}-mapper.ts"; const UTF8 = new TextEncoder(); const NO_INPUT = Object.freeze({}); @@ -911,13 +1119,13 @@ const NO_INPUT = Object.freeze({}); * §10.4. Bounded estimate of the mapped value: string bytes plus a fixed * per-item overhead, never \`JSON.stringify\`. */ -function measureItems(items: readonly ${pascal}ItemView[]): QueryResultMeasure { - let estimatedBytes = 16; - for (const item of items) { +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: items.length, estimatedBytes }; + return { itemCount: list.items.length, estimatedBytes }; } export function use${pascal}Items() { @@ -941,16 +1149,32 @@ export function use${pascal}Items() { `; } -function renderListPage({ names }: Shape): string { +function renderListPage({ names, write }: Shape): string { const { base, camel, pascal } = names; - return `import { + const item = write + ? `
  • + + {item.name} + +
  • ` + : `
  • {item.name}
  • `; + 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"; -import { use${pascal}Items } from "./use-${base}-items.ts"; +${write ? `import { ${camel}RouteUrl } from "./${base}-routes.ts";\n` : ""}import { use${pascal}Items } from "./use-${base}-items.ts"; -/** An empty list renders the shared empty state under the page heading. */ +/** + * 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(); @@ -959,19 +1183,33 @@ export default function ${pascal}ListPage() { 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.state.base === "success" || query.state.base === "empty" - ? message("${camel}.list.resultCount", { count: query.data?.length ?? 0 }) - : null + query.data ? message("${camel}.list.resultCount", { count: query.data.total }) : null } > -
      - {(query.data ?? []).map((item) => ( -
    • {item.name}
    • - ))} -
    + {query.data?.items.length ? ( +
      + {query.data.items.map((item) => ( + ${item} + ))} +
    + ) : ( + + )}
    ); @@ -987,13 +1225,21 @@ import { createFailure } from "../../../src/contracts/errors.ts"; import { create${pascal}FeatureInput } from "../../../src/features/${names.id}/application/${base}-feature-api.ts"; import type { TelemetryPort } from "../../../src/platform/telemetry/telemetry-port.ts"; -const ITEMS = Object.freeze([Object.freeze({ itemId: "item-1", name: "First item" })]); +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) { + return { list } as unknown as Parameters[0]; +} describe("${names.id} application input", () => { it("returns the gateway's items without telemetry", async () => { const emit = vi.fn(); const input = create${pascal}FeatureInput( - { list: async () => ({ ok: true, value: ITEMS }) }, + gatewayListing(async () => ({ ok: true, value: ITEMS })), { telemetry: { emit } }, ); @@ -1005,7 +1251,7 @@ describe("${names.id} application input", () => { const failure = createFailure("REQUEST_TIMEOUT", "${operationId}", 0); const emit = vi.fn(); const input = create${pascal}FeatureInput( - { list: async () => ({ ok: false, error: failure }) }, + gatewayListing(async () => ({ ok: false, error: failure })), { telemetry: { emit } }, ); @@ -1020,69 +1266,36 @@ describe("${names.id} application input", () => { it("does not report a load its caller aborted", async () => { const failure = createFailure("REQUEST_ABORTED", "${operationId}", 0); - const input = create${pascal}FeatureInput({ - list: async () => ({ ok: false, error: failure }), - }); + const emit = vi.fn(); + 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 }: Shape): string { +function renderPageTest({ names, operationId, routeId, apiPath }: Shape): string { const { base, camel, upper } = names; return `// @vitest-environment jsdom -import { render, screen } from "@testing-library/react"; -import userEvent from "@testing-library/user-event"; +import { 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 { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts"; -import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx"; import { ${operationId}_CONTRACT } from "../../../src/features/${names.id}/contracts/${base}-contract-contribution.ts"; import { ${upper}_MESSAGE_CATALOGS } from "../../../src/features/${names.id}/contracts/${base}-message-catalog.ts"; import { ${camel}RouteUrl } from "../../../src/features/${names.id}/presentation/${base}-routes.ts"; import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts"; import { createHttpScenarioHandler } from "../../mocks/handlers/http-scenarios.ts"; +import { API, openSignedIn } from "./${base}-test-app.tsx"; const MESSAGES = ${upper}_MESSAGE_CATALOGS["ko-KR"]; -const RUNTIME_CONFIG = { - APP_ENV: "local", - API_BASE_URL: "https://api.test", - REQUEST_TIMEOUT_MS: 10_000, - MAX_RETRY_ATTEMPTS: 0, - TELEMETRY_ENABLED: false, - AUTH_MODE: "demo", - CONFIG_SCHEMA_VERSION: "1", - API_CONTRACT_VERSION: "1", - RELEASE_MANIFEST_URL: "/release-manifest.json", - BUILD_ID: "local-build", - RELEASE_ID: "local-release", -}; -const RELEASE_MANIFEST = { - schemaVersion: 1, - appVersion: "0.0.0", - buildId: "local-build", - commitSha: "local", - configSchemaVersion: "1", - apiContractVersion: "1", - assetManifestHash: "test-hash", - releaseId: "local-release", - builtAt: "2026-01-01T00:00:00.000Z", - routeChunks: { "route-home": "assets/home.js" }, -}; - -/** The boot documents come from here; every API call goes to MSW. */ -const fetcher: typeof fetch = (input, init) => { - const url = new URL(input instanceof Request ? input.url : String(input), "http://app.test"); - if (url.pathname === "/config.json") return Promise.resolve(Response.json(RUNTIME_CONFIG)); - if (url.pathname === "/release-manifest.json") { - return Promise.resolve(Response.json(RELEASE_MANIFEST)); - } - return fetch(input instanceof Request ? input : url, init); -}; const api = setupServer(); beforeAll(() => api.listen({ onUnhandledRequest: "error" })); @@ -1091,14 +1304,7 @@ afterAll(() => api.close()); /** Enters the list through the router, as a signed-in user. */ async function openList() { - const user = userEvent.setup(); - window.history.pushState({}, "", ${camel}RouteUrl("${routeId}")); - render( - , - ); - await user.click(await screen.findByRole("button", { name: KO_MESSAGES["action.signIn"] })); + const user = await openSignedIn(${camel}RouteUrl("${routeId}")); expect( await screen.findByRole("heading", { level: 1, name: MESSAGES["${camel}.list.title"] }), ).toBeVisible(); @@ -1117,6 +1323,22 @@ describe("${names.id} list page through the router", () => { 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: [] })); @@ -1147,7 +1369,73 @@ describe("${names.id} list page through the router", () => { `; } -function renderGatewayTest({ names, apiPath }: Shape): string { +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( + , + ); + 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"; @@ -1158,7 +1446,7 @@ import { createFeatureHttpBinding, type InstalledHttpOperationExecutor, } from "../../../src/adapters/http/index.ts"; -import { +${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"; @@ -1167,8 +1455,8 @@ import { * The paired backend's wire (clean-architecture-backend-template * docs/web/http-contract.md §1): every JSON body is an Envelope, and a null * field is dropped with its key. The bodies are written out here rather than - * taken from the shared scenarios, so this fails if the contract stops - * reading that wire. + * 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" }; @@ -1182,12 +1470,12 @@ function answer(status: number, body: JsonBodyType) { api.use(http.get(\`\${API}${apiPath}\`, () => HttpResponse.json(body, { status }))); } -function failure(code: string, details?: JsonBodyType) { +function failure(code: string, details?: JsonBodyType, category = "VALIDATION") { return { success: false, error: { code, - category: "VALIDATION", + category, message: "backend message", retryable: false, ...(details === undefined ? {} : { details }), @@ -1195,11 +1483,16 @@ function failure(code: string, details?: JsonBodyType) { 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: 0, + maxRetryAttempts: 2, + random: () => 0, attachCredentials: () => ({ kind: "READY" as const, headers: { authorization: "Bearer test-token" }, @@ -1209,6 +1502,7 @@ function gateway() { 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", @@ -1227,15 +1521,29 @@ describe("${names.id} HTTP gateway on the paired backend's Envelope", () => { await expect(gateway().list()).resolves.toEqual({ ok: true, - value: [{ itemId: "item-1", name: "First item" }], + 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: [] }); + await expect(gateway().list()).resolves.toEqual({ + ok: true, + value: { items: [], total: 0 }, + }); }); it("reads the failure Envelope's code and drops its message", async () => { @@ -1273,7 +1581,7 @@ describe("${names.id} HTTP gateway on the paired backend's Envelope", () => { error: { kind: "ENVELOPE_MISMATCH" }, }); }); -}); +${write ? renderWriteGatewayTests({ ...shape, write }) : ""}}); `; } @@ -1381,10 +1689,10 @@ async function readInstalledFacts(root: string): Promise { } const USAGE = - "Usage: pnpm create:feature [--context ] " + + "Usage: pnpm create:feature [--context ] [--with-create [--keyed]] " + "[--package @scope/name@x.y.z --digest sha256:<64 hex> --revision ]"; -function parseRequest(argv: readonly string[]): FeatureRequest { +export function parseRequest(argv: readonly string[]): FeatureRequest { const args = argv[0] === "--" ? argv.slice(1) : [...argv]; const { values, positionals } = parseArgs({ args, @@ -1394,6 +1702,8 @@ function parseRequest(argv: readonly string[]): FeatureRequest { package: { type: "string" }, digest: { type: "string" }, revision: { type: "string" }, + "with-create": { type: "boolean" }, + keyed: { type: "boolean" }, }, }); const [id, ...extra] = positionals; @@ -1415,16 +1725,25 @@ function parseRequest(argv: readonly string[]): FeatureRequest { sourceRevision: values.revision ?? "", }); } - return Object.freeze({ id, context: values.context, contractPackage }); + 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)" : ""}, route ${plan.routeId} at ${plan.routePath}`, + `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 artifacts/tests/a11y-manual/${plan.routeId}.md (FE-GATE-028). The merge gates check only its format.`, + ` 1. Before a release, have a person review and sign ${plan.routes + .map((route) => `artifacts/tests/a11y-manual/${route.routeId}.md`) + .join(", ")} (FE-GATE-028). The merge gates check only their format.`, " 2. Run the merge gates: corepack pnpm check:types, lint, check:architecture, check:registries, check:i18n, check:design-system, check:diagnostics, verify:documentation, test:unit, test:component, test:integration, test:coverage, check:ci, build.", ` The feature's own tests: node scripts/run-vitest.ts run tests/features/${plan.id} (test:coverage runs them in CI)`, " The registry baseline does not change: new routes, operations, schemas and invalidation topics are additive.", diff --git a/tests/unit/create-feature.test.ts b/tests/unit/create-feature.test.ts index 9c819f18..d28042fe 100644 --- a/tests/unit/create-feature.test.ts +++ b/tests/unit/create-feature.test.ts @@ -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 / (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 /, GET //{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) => + 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; + 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", () => { From e8c4197e0bf8ad693fed90467a993d9a326afc9c Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 23:29:54 +0900 Subject: [PATCH 6/9] =?UTF-8?q?test(reference):=20=EC=B0=B8=EC=A1=B0=20con?= =?UTF-8?q?text=20=EB=9D=BC=EC=9A=B0=ED=8C=85=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=EA=B0=80=20=EC=B0=B8=EC=A1=B0=20=EA=B8=B0=EB=8A=A5?= =?UTF-8?q?=EC=9D=98=20=EB=9D=BC=EC=9A=B0=ED=8A=B8=EB=A7=8C=20=EB=B3=B8?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 `create:feature --context reference-context`로 기능을 참조 context에 넣으면 tests/features/reference-feature/installed-context-routing.test.ts가 실패한다. 그 테스트가 참조 context가 적재하는 라우트 전체를 정확히 비교하기 때문이다. 매뉴얼은 이것을 "못 잡음"으로 두고 참조 context에 넣지 말라고만 적었다(메인 세션 X1). 고른 방법 비교 대상을 참조 기능 계약의 route ID로 거른다. 테스트의 의도(참조 기능 라우트가 공개 URL 그대로 지연 적재된다)는 그대로다. 매뉴얼 01 1단계와 reference/create-feature.md의 한계 문장을 고쳤다. 생성한 context 선언을 실행하는 테스트는 앞 커밋(tests/unit/create-feature.test.ts)에 있다. 버린 대안 - 생성 명령이 reference-context를 거부: 생성기가 샘플 이름을 알게 되고, 테스트 가정 하나를 지키려고 정상 입력을 막는다. 위험·한계 - 참조 context에 넣은 기능은 경로가 /examples/reference-resources/다. 참조 기능을 지우면 context가 남아 제거 드릴 잔여 검사에 걸린다고 매뉴얼에 적었다. 이 경로의 드릴은 돌리지 않았다(추론). 검증 - RED: refx-feature --context reference-context --with-create를 만든 상태에서 이 테스트가 XONE/REFX 라우트를 받아 실패(앞 커밋 검증 기록). 고친 뒤 같은 상태에서 tests/features 124건 통과, tests/component·architecture와 create-feature·schema-metadata-policy 49파일 374건 통과. 생성 기능은 지웠다. - lint, check:types(test), verify:documentation 통과. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 1101/16-02 --- docs/manual/01-add-a-feature.md | 4 +++- docs/manual/reference/create-feature.md | 2 +- .../installed-context-routing.test.ts | 11 ++++++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index b8a6a1d4..daae252f 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -126,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/`가 된다. 참조 기능을 지우면 context가 그 기능 때문에 남고, 그 경로 문자열이 제거 드릴(`test:sample-removal`)의 잔여 검사(`reference-resource`)에 걸린다(추론, 실행하지 않음). 남길 기능은 제품 context에 둔다. ④ **쓸 스킬**: `clean-architecture`, `codebase-design` diff --git a/docs/manual/reference/create-feature.md b/docs/manual/reference/create-feature.md index 3a7d2302..ec1cc915 100644 --- a/docs/manual/reference/create-feature.md +++ b/docs/manual/reference/create-feature.md @@ -156,6 +156,6 @@ corepack pnpm generate:feature-index ## 알려진 한계 -- `--context reference-context`로 참조 context에 넣으면 `tests/features/reference-feature/installed-context-routing.test.ts`가 깨진다. 그 테스트는 참조 context의 라우트 수를 정확히 비교한다. +- `--context reference-context`로 참조 context에 넣은 기능은 경로가 `/examples/reference-resources/`다. 참조 기능을 지우면 context가 남고 그 경로가 제거 드릴의 잔여 검사에 걸린다. 남길 기능은 제품 context에 둔다. - 드릴은 `check:bundle`(FE-GATE-012), 브라우저 테스트(`test:a11y`, `test:e2e`)를 돌리지 않는다. - 새 context는 앱이 하나일 때만 만든다. 앱이 여럿이면 `--context`로 기존 context를 고른다. diff --git a/tests/features/reference-feature/installed-context-routing.test.ts b/tests/features/reference-feature/installed-context-routing.test.ts index 00cd6118..49a1661c 100644 --- a/tests/features/reference-feature/installed-context-routing.test.ts +++ b/tests/features/reference-feature/installed-context-routing.test.ts @@ -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 --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 = 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"], From 1404f57b3b06387afaf077d14367d6d36204a2ce Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 23:31:19 +0900 Subject: [PATCH 7/9] =?UTF-8?q?docs(manual):=20=EC=A7=9D=20=EB=B0=B1?= =?UTF-8?q?=EC=97=94=EB=93=9C=20=EC=83=9D=EC=84=B1=20=EA=B8=B0=EB=8A=A5?= =?UTF-8?q?=EC=9D=98=20=EC=93=B0=EA=B8=B0=20=EA=B0=92=20=EB=84=B7=EC=9D=84?= =?UTF-8?q?=20=EA=B2=B0=EC=A0=95=ED=91=9C=EC=97=90=20=EC=A0=81=EB=8A=94?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 짝 백엔드에 쓰기를 붙일 때 기능 작성자가 정하는 값 넷(호출 문맥 intent, retryBudget, classifyStatus, operationIdentityField)을 매뉴얼이 정해 주지 않는다. 02 3절은 "retryBudget 안에서 같은 키로 재전송"과 "참조 기능은 0"을 함께 적어 부딪히고, 401·403·429를 짝 백엔드가 쓰기 전에 거절하는지는 어느 문서에도 없다. 실험에서 실행기 코드를 읽고 값을 정했다(리뷰 B1~B4). 또 백엔드 생성 create가 NOT_IDEMPOTENT라는 사실과 프론트 retrySemantics의 관계가 적혀 있지 않다(03-07). 고른 방법 - 02 3절에 "짝 백엔드의 생성 기능에 붙일 때" 표를 둔다. 백엔드 create를 그대로 두면 NEVER, IdempotencyExecutor 뒤로 옮기면 KEYED. 두 경우의 retrySemantics, retryBudget(0 / 1과 실제 상한 계산), commandRecovery와 operationIdentityField의 뜻(실행기는 읽지 않음), intent 전달, classifyStatus(401 보안 필터, 403 @RequiresPermission 프록시, 429 rate-limit interceptor preHandle — 백엔드 코드에서 확인), refusedBeforeWrite, acceptedStatuses, 결과 불명 화면, 생성 테스트를 적는다. - 01 4단계에 쓰기 메서드의 호출 문맥(intent), 8단계에 NEVER는 다시 보내기 버튼이 없다는 것과 생성 예제 위치를 적는다. - 표의 값은 create:feature --with-create(--keyed)가 만드는 값과 같다. 버린 대안 - classifyStatus를 "백엔드 확인 전에는 생략"으로 두기(리뷰 권고 (1)의 잠정안): 백엔드 코드를 확인해 생성 create에서는 셋 다 use case 전이라 NOT_APPLIED로 적었다. use case가 AuthorizationPort를 쓰기 뒤에 부르면 지우라고 조건을 붙였다. 위험·한계 - classifyStatus 판정은 백엔드 c508b1ba의 생성 템플릿과 web 어댑터 기준이다. 백엔드가 바뀌면 다시 본다. 검증 - verify:documentation PASS_SCOPED. Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-07 Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-07 --- docs/manual/01-add-a-feature.md | 5 +++-- docs/manual/02-decision-tables.md | 32 ++++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index daae252f..9bc5358d 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -323,6 +323,7 @@ projectRequest: (input) => Object.freeze({ - input 메서드 이름. 사용자가 하는 일로 짓는다(`listItems`, `createInvoice`). - 반환 타입. `Result`(`src/contracts/result.ts`)를 쓴다. +- 쓰기 메서드의 호출 문맥. 쓰기는 뮤테이션의 `intent`를 받아 gateway까지 넘긴다(`Readonly<{ signal?: AbortSignal; intent: MutationIntent }>`). `KEYED` 쓰기의 멱등 키가 intent에 있다. `--with-create`의 `CommandContext`가 이 모양이다. - 실패 telemetry의 `kind`. `.<동작>.failed` 꼴로 접두어를 붙인다. ② **기준** @@ -511,14 +512,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 --with-create`의 `presentation/-create-page.tsx`(짝 백엔드 Envelope), `src/features/reference-feature/presentation/reference-resource-form-page.tsx`(problem details) ③ **잡는 검사 / 못 잡는 것** diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 1fed09ad..2db25794 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -88,7 +88,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 |---|---|---|---| | 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 | | 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다. 예외: 짝 백엔드가 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절)로 답하면 `retryBudget` 안에서 같은 키로 다시 보낸다 | 된다 | 하지 않는다 | -| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 참조 기능은 `retryBudget: 0` | — | `retryBudget: 0` 필수 | +| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 짝 백엔드는 `retryBudget: 1`(아래 표), 참조 기능은 `0` | — | `retryBudget: 0` 필수 | | 뮤테이션 정책 | `...commandMutationIdentity(_CONTRACT)`가 `requiresIdempotencyKey: true`를 준다 | 같은 함수가 `false`를 준다 | 같은 함수가 `false`를 준다 | - 멱등 키: 서버가 "같은 쓰기 요청"을 알아보게 하는 값이다. @@ -96,6 +96,36 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 **기준**: 원칙 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 --with-create + └─ IdempotencyExecutor 뒤로 옮김 (KEYED, 백엔드 docs/manual/05-idempotency.md "KEYED로 만드는 순서") + → 프론트 KEYED ← create:feature --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 → 바인딩까지 그대로 넘긴다(생성된 `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` | `["_INVALID"]` | 같다 | 이름 규칙을 트랜잭션 전에 검사한다(4절) | +| `acceptedStatuses` | `[201]` | `[201]` | `ResponseEntity.created`. 같은 키 재생도 첫 요청과 같은 201이다 | +| 결과 불명 화면 | 확인만. 다시 보내기 버튼 없음 | "같은 요청으로 다시 보내기"가 같은 키로 보낸다 | 키 없는 재전송은 서버가 새 요청으로 본다 | +| 생성 테스트 | 응답 유실 → 결과 불명, 다시 보내기 없음, 키 헤더 없음 | 응답 유실 → 같은 키로 다시 보내기. 503 `IDEMPOTENCY_UNAVAILABLE` → 같은 키로 1회 자동 재전송 | `tests/features//-create-page.test.tsx`, `-http-gateway.test.ts` | + +- 테스트 하네스의 재시도 상한: 생성된 gateway 테스트는 앱 기본값(`maxRetryAttempts: 2`)으로 돈다. 그래야 `retryBudget: 1`의 재전송이 보인다. 페이지 테스트(`-test-app.tsx`)는 실패를 바로 보이려고 `MAX_RETRY_ATTEMPTS: 0`이다. + **정본**: 백엔드가 멱등 키 요청에 어떻게 답하는지는 `clean-architecture-backend-template/docs/web/http-contract.md` §2(멱등성 응답)다. 여기에 표를 옮기지 않는다. **어디에 적나**: `contracts/-contract-contribution.ts`의 `retrySemantics`, `commandRecovery`, `frontend.retryBudget`. 다른 파일에 다시 적지 않는다. From 7411d4a4048519d424bacef2ce99a79ca39c91a9 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 23:35:16 +0900 Subject: [PATCH 8/9] =?UTF-8?q?test(scaffold):=20=EC=83=9D=EC=84=B1=20?= =?UTF-8?q?=EB=93=9C=EB=A6=B4=EC=9D=B4=20--with-create=20=EC=93=B0?= =?UTF-8?q?=EA=B8=B0=20slice=EB=8F=84=20=EB=A7=8C=EB=93=A4=EA=B3=A0=20?= =?UTF-8?q?=EA=B2=8C=EC=9D=B4=ED=8A=B8=EB=A5=BC=20=EB=8F=88=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 --with-create(NEVER)와 --with-create --keyed(KEYED)가 만드는 코드는 단위 테스트가 텍스트로만 본다. FE-GATE-020의 두 드릴(test:feature-scaffold, test:sample-removal)은 기본 기능 하나만 만들어 게이트를 돈다. 그래서 쓰기 slice의 타입·lint·테스트·빌드가 머지 게이트에서 깨져도 모른다(16 5.3절의 "생성 결과를 매번 게이트로 돌린다"는 전제). 고른 방법 - scripts/test-feature-scaffold.ts: 기본 기능(scaffold-feature) 옆에 scaffold-write-feature를 --with-create --keyed로 하나 더 만들고, 둘 다 만들어졌을 때 같은 게이트를 한 번 돈다. 바꾼 것은 WRITE_FEATURE_ID 상수, create-feature-write 검사 한 개, 게이트 조건(created && createdWrite), 머리 주석이다. - scripts/test-sample-removal.ts: 참조 기능을 지운 복사본의 create:feature 인자에 --with-create 한 개를 더했다. 쓰기 slice도 샘플에 기대지 않는다는 증거다. - 세 변형(기본, NEVER, KEYED)이 모두 드릴의 게이트를 지난다. - reference/create-feature.md의 드릴 설명을 맞췄다. 버린 대안 - 드릴 기능 하나를 --with-create로 바꾸기: 기본 변형이 게이트에서 빠진다. 위험·한계 - test:feature-scaffold는 기능 하나만큼(create:feature 한 번과 그 기능의 테스트) 길어진다. 게이트는 한 번만 돈다. - 다른 작업(게이트 담당)이 같은 두 파일의 명령 목록을 고칠 수 있다. 내 수정은 위 줄로 좁혔다. 검증 - flock 아래 CHOKIDAR_USEPOLLING=1 corepack pnpm test:feature-scaffold: rc=0, "feature scaffold: PASS (17 checks)" (생성 2 + 게이트 15), 162초. - 같은 조건 corepack pnpm test:sample-removal: rc=0, "reference-feature removal: PASS (23 checks, no fixture IDs)". 참조 기능을 지운 복사본에서 --with-create 기능을 만든 뒤 scaffold-* 게이트 9개가 모두 통과했다. 첫 실행은 tests/unit/create-feature.test.ts에 샘플 ID 문자열이 있어 fixture-id-residue로 실패했고, 그 테스트를 앞 커밋에서 고친 뒤 통과했다. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-06 Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-01 --- docs/manual/reference/create-feature.md | 4 ++-- scripts/test-feature-scaffold.ts | 14 +++++++++++--- scripts/test-sample-removal.ts | 3 +++ 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/docs/manual/reference/create-feature.md b/docs/manual/reference/create-feature.md index ec1cc915..da64e4d8 100644 --- a/docs/manual/reference/create-feature.md +++ b/docs/manual/reference/create-feature.md @@ -149,10 +149,10 @@ corepack pnpm generate:feature-index - 백엔드 경로 규칙, `--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가 참조 기능에 기대지 않는다는 증거다. ## 알려진 한계 diff --git a/scripts/test-feature-scaffold.ts b/scripts/test-feature-scaffold.ts index 61654558..495c5f1a 100644 --- a/scripts/test-feature-scaffold.ts +++ b/scripts/test-feature-scaffold.ts @@ -14,11 +14,14 @@ 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 gates. + * included, gets a default feature and a `--with-create --keyed` one, then + * runs the gates. * test:sample-removal repeats the generation after deleting the sample * (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"); @@ -37,8 +40,13 @@ try { "docs", ]); 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); diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index 81bec4c0..c28604fb 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -450,8 +450,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) { From c7b15f994d50cad419530600854cf5817d3a48ae Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Wed, 4 Nov 2026 23:35:17 +0900 Subject: [PATCH 9/9] =?UTF-8?q?test(scaffold):=20=EC=83=9D=EC=84=B1=20KEYE?= =?UTF-8?q?D=20=EC=9E=91=EC=84=B1=EC=9D=B4=20409=20IDEMPOTENT=5FIN=5FFLIGH?= =?UTF-8?q?T=EB=A5=BC=20=EA=B2=B0=EA=B3=BC=20=EB=B6=88=EB=AA=85=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=82=A8=EA=B8=B0=EB=8A=94=EC=A7=80=20=EB=B3=B8?= =?UTF-8?q?=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 09-06의 완료 기준은 짝 백엔드 wire의 KEYED 생성, 400 필드 오류와 함께 409 IDEMPOTENT_IN_FLIGHT를 실행하는 기능 예제다. --with-create --keyed가 만드는 gateway 테스트는 503 IDEMPOTENCY_UNAVAILABLE 재전송만 보고 409 처리 중은 보지 않는다. 고른 방법 KEYED 생성 gateway 테스트에 409 IDEMPOTENT_IN_FLIGHT 사례를 더한다. 결과는 MAYBE_APPLIED이고 code가 그대로이며, 실행기는 스스로 다시 보내지 않는다(같은 키 재전송은 폼이 한다, http-contract.md §2). NEVER 생성은 키가 없어 이 답을 받지 않으므로 더하지 않는다. 위험·한계 - Retry-After 대기는 뮤테이션 조정자 쪽이라 이 gateway 테스트는 보지 않는다. 검증 - keyx-feature --with-create --keyed를 만들어 gateway 테스트 13건 통과, eslint 통과. 생성 기능은 지웠다. tests/unit/create-feature.test.ts 43건 통과. Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-06 --- scripts/create-feature-write-slice.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/scripts/create-feature-write-slice.ts b/scripts/create-feature-write-slice.ts index 95abc0ab..558967c5 100644 --- a/scripts/create-feature-write-slice.ts +++ b/scripts/create-feature-write-slice.ts @@ -907,6 +907,19 @@ export function renderWriteGatewayTests({ names, apiPath, write }: SliceShape): expect(keys).toEqual(["key-1", "key-1"]); }); + // http-contract.md §2: the first request with this key still runs. The + // result is unknown; the form resends it later with the same key, the + // executor never does on its own. + it("leaves 409 IDEMPOTENT_IN_FLIGHT maybe applied and does not resend it", async () => { + const keys = answerCreate(409, failure("IDEMPOTENT_IN_FLIGHT", undefined, "CONFLICT")); + + await expect(gateway().create({ name: "First item" }, { intent: INTENT })).resolves.toMatchObject({ + ok: false, + error: { code: "IDEMPOTENT_IN_FLIGHT", effect: "MAYBE_APPLIED" }, + }); + expect(keys).toEqual(["key-1"]); + }); + it("refuses a create without the intent's key before sending", async () => { const keys = answerCreate(201, CREATED_BODY);