diff --git a/docs/manual/01-add-a-feature.md b/docs/manual/01-add-a-feature.md index 34d9bff8..7b33b12d 100644 --- a/docs/manual/01-add-a-feature.md +++ b/docs/manual/01-add-a-feature.md @@ -5,9 +5,12 @@ - 뼈대는 손으로 만들지 않는다. `corepack pnpm create:feature `로 만든다. - 뼈대를 실제 기능으로 바꾸는 순서가 아래 0~11단계다. -참조 기능(`src/features/reference-feature/`)을 복사해 이름을 바꾸는 방법은 쓰지 않는다. -그 방법은 접두어 없는 전역 ID, 참조 전용 계약 출처, 기능 밖 테스트 의존 때문에 여러 번 막힌다. +다른 기능 폴더를 복사해 이름을 바꾸는 방법은 쓰지 않는다. +그 방법은 접두어 없는 전역 ID, 복사된 계약 출처, 기능 밖 테스트 의존 때문에 여러 번 막힌다. 생성 명령은 이 문제를 미리 피한 파일을 쓴다. +템플릿에는 복사해 볼 기능 샘플이 없다. 생성 뼈대에 없는 모양은 이 매뉴얼 안의 코드 조각으로 보인다. +코드 조각 위의 `manual-code-block` 표식이 그 조각을 둘 자리다. 조각은 `create:feature invoice-feature --with-create`로 만든 기능을 기준으로 쓴다. +`tests/unit/manual-code-blocks.test.ts`가 그 기능을 저장소 사본에 만들고 조각을 그 자리에 그대로 넣어 타입 검사와 동작 시험을 돌린다. ## 전체 흐름 @@ -107,7 +110,7 @@ corepack pnpm create:feature invoice-feature → 만든 파일과 다음 할 일 출력 ``` -- 기능과 함께 커밋할 추적 파일은 둘이다. dev server manifest와, 참조 기능이 있는 동안의 초기 JS 기록이다. 기능 브랜치 둘이 같은 줄에서 충돌하면 명령을 다시 돌린다. 표와 명령은 [03 문서 A](03-outside-feature-folder.md#a-생성-명령이-만든다)에 있다. +- 기능과 함께 커밋할 추적 파일은 둘이다. dev server manifest와 초기 JS 기록이다. 기능 브랜치 둘이 같은 줄에서 충돌하면 명령을 다시 돌린다. 표와 명령은 [03 문서 A](03-outside-feature-folder.md#a-생성-명령이-만든다)에 있다. ① **정할 것** @@ -130,8 +133,6 @@ corepack pnpm create:feature invoice-feature - 생성기가 거부한다. 선언 헤더가 리터럴이 아님, 없는 context, 예산 초과. - 이때 명령은 만든 파일을 모두 지우고 `the feature index generator rejected the feature, nothing was kept:`로 끝난다. - 생성한 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` @@ -150,12 +151,34 @@ corepack pnpm create:feature invoice-feature - 업무 규칙이 없으면 만들지 않는다. mapper가 DTO를 화면 값으로 바꾸는 것으로 충분하다. - 있으면 `domain/.ts`에 둔다. - 생성 함수에서 불변식을 검사하고 `Object.freeze`로 고정한다. - - 이름은 와이어 필드가 아니라 업무 이름으로 짓는다(참조 기능은 `name`을 `displayName`으로 바꾼다). -- 예제(참조 기능): `src/features/reference-feature/domain/` + - 이름은 와이어 필드가 아니라 업무 이름으로 짓는다(예: 와이어 `name`을 화면 값 `displayName`으로). +- 예: 청구서는 발행일 뒤에만 마감된다. `domain/.ts` 한 파일이다. + + +```ts +export type Invoice = Readonly<{ + invoiceId: string; + /** Calendar dates, YYYY-MM-DD. */ + issuedOn: string; + dueOn: string; +}>; + +/** An invoice falls due on or after the day it is issued. */ +export function createInvoice(input: Invoice): Invoice { + if (!/^\d{4}-\d{2}-\d{2}$/u.test(input.issuedOn) || !/^\d{4}-\d{2}-\d{2}$/u.test(input.dueOn)) { + throw new RangeError("Invoice dates are calendar dates (YYYY-MM-DD)."); + } + if (input.dueOn < input.issuedOn) { + throw new RangeError("An invoice falls due on or after the day it is issued."); + } + return Object.freeze({ ...input }); +} +``` + - 길이 제한(예: 제목 100자)은 domain이 아니라 경계 검증에 둔다. - 경계 검증: 값이 앱에 들어오거나 나가는 자리(요청·응답 스키마, 폼 스키마)에서 하는 검사다. - 서버가 정한 제한이면 `contracts/-schemas.ts`에 상수로 두고 요청 스키마와 폼 스키마가 같은 상수를 쓴다. 숫자가 두 곳에서 갈라지지 않는다. - - 참조 기능도 이름 길이를 스키마(`reference-schemas.ts`)와 폼(`reference-resource-form.ts`)에만 둔다. `domain/`에는 없다. + - 생성 판(`--with-create`)도 이름 길이 상수(`_NAME_MAX_LENGTH`)를 스키마(`contracts/-schemas.ts`)와 폼(`presentation/-form.ts`)에만 둔다. `domain/`에는 없다. - domain에는 서버 제한이 바뀌어도 그대로인 업무 규칙만 둔다(예: "마감일은 시작일 뒤"). ③ **잡는 검사 / 못 잡는 것** @@ -241,7 +264,7 @@ DTO와 problem details(`type`·`title`·`status`)를 감싸지 않고 보내는 2. problem 스키마를 problem details 모양으로 바꾼다. 3. `classifyProblem`이 모든 판정을 정한다. 실행기가 먼저 정하는 판정은 없다. -참조 기능(`src/features/reference-feature/`)이 이 모양이다. 참조 기능의 MSW 본문도 DTO와 problem details다. +problem 스키마, 작성의 `commandEffect`, `mapProblem`의 예는 [02 결정표 4절](02-decision-tables.md#4-결과-불명)의 「problem details 백엔드의 예」에 있다. 그 기능의 MSW 본문도 DTO와 problem details로 손으로 적는다. **입력과 스키마 메타데이터** @@ -305,8 +328,8 @@ projectRequest: (input) => Object.freeze({ - 오류의 `reason`: `/: unknown authProfileId ` - 스키마 ID나 operation ID가 겹치면 적재 때 그 ID를 말하며 실패한다. - 예: `Invalid or duplicate schema definition: `, 계약 조립 `duplicate operation: ` -- `TEMPLATE_FIXTURE` 출처를 참조 기능 밖에서 쓰면 계약 조립이 거부한다. - - 오류의 `reason`: `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to reference-feature only; pin an EXTERNAL_PACKAGE` +- `TEMPLATE_FIXTURE` 출처를 제품 기능에 쓰면 계약 조립이 거부한다. + - 오류의 `reason`: `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to only; pin an EXTERNAL_PACKAGE` - zod를 직접 import하면 `check:architecture`가 `zod-is-reached-through-contracts-zod`로 막는다. - 계약 패키지를 다른 파일에서 import하면 `external-contract-package-single-import-path`로 막는다. - 자리표시자 신원은 staging·production 승인(`check:release-admission`, FE-GATE-027)이 거절한다. @@ -376,10 +399,9 @@ projectRequest: (input) => Object.freeze({ - 읽기: 데이터를 그리는 화면. 목록 GET은 목록 route, 상세 GET은 상세 route. - 쓰기: 저장 버튼이 있는 화면. 작성 폼 route가 따로 있으면 그 route. - 여러 화면에서 부르면 주로 부르는 화면 하나를 고른다. 이름표는 하나뿐이다. - - 참조 기능은 생성 operation에 목록 route(`REFERENCE_RESOURCE_LIST`)를 적었다. 실제로 보내는 화면은 폼 route다. 동작은 같고 기록의 이름표만 다르다. 새 기능은 위 기준을 따른다. - `needs`에는 실제로 쓰는 것만 적는다. - 템플릿이 만들지 않는 capability(예: `indexedDb`)는 `src/bootstrap/product-composition.ts`에서 만든다. 제품이 새로 만드는 capability의 타입은 `src/features/product-capabilities.ts`에 적는다. [03 문서](03-outside-feature-folder.md)를 본다. -- 문제 응답 매핑 예제(참조 기능): `src/features/reference-feature/adapters/reference-http-gateway.ts` +- 문제 응답 매핑 예제: 짝 백엔드는 `create:feature --with-create`의 `adapters/-http-gateway.ts`(400 `_INVALID` → 이름 칸). problem details 백엔드는 [02 결정표 4절](02-decision-tables.md#4-결과-불명)의 조각 2. ③ **잡는 검사 / 못 잡는 것** @@ -423,11 +445,49 @@ projectRequest: (input) => Object.freeze({ ② **기준** - 경로는 계약에만 적는다. 페이지와 링크는 route ID와 `buildRouteUrl`로 URL을 만든다. 경로 문자열을 페이지에 다시 적지 않는다. -- 파라미터나 검색값이 있는 라우트는 `context-routes.ts`의 handle에 `codecs`를 싣는다. 예제(참조 기능): `src/features/reference-feature/context-routes.ts`. - - 링크용 URL 함수도 같은 codec을 `buildRouteUrl`의 세 번째 인자로 넘긴다. 기본 생성 판의 목록 라우트는 파라미터가 없어서 넘기지 않는다. `--with-create` 판의 상세 라우트는 codec을 넘긴다. 안 넘기면 `Unregistered route codec: `로 throw한다. codec ID는 계약 `routeRuntimeContracts`의 `paramsCodec`·`searchCodec` 값이다. 예제(참조 기능): `src/features/reference-feature/presentation/reference-routes.ts`. +- 파라미터나 검색값이 있는 라우트는 `context-routes.ts`의 handle에 `codecs`를 싣는다. 예제: `create:feature --with-create`의 `context-routes.ts`(상세 라우트의 params codec). + - 링크용 URL 함수도 같은 codec을 `buildRouteUrl`의 세 번째 인자로 넘긴다. 기본 생성 판의 목록 라우트는 파라미터가 없어서 넘기지 않는다. `--with-create` 판의 상세 라우트는 codec을 넘긴다. 안 넘기면 `Unregistered route codec: `로 throw한다. codec ID는 계약 `routeRuntimeContracts`의 `paramsCodec`·`searchCodec` 값이다. 예제: `--with-create` 판의 `presentation/-routes.ts`. +- 검색값(`?status=open`)을 읽는 목록은 아래 두 조각을 더한다. 생성 뼈대의 목록 라우트에는 검색값이 없다. + - 조각 1(`contracts/-list-search.ts`)이 검색값 스키마다. 그 스키마를 `presentation/-route-codecs.ts`의 `_ROUTE_CODECS`에 `ListSearch`라는 codec ID로 싣는다. + - 계약의 목록 라우트 `searchSchema`와 `routeRuntimeContracts`의 `searchCodec`을 그 codec ID로 바꾼다. 기본 판처럼 `context-routes.ts` handle에 `codecs`가 없으면 `--with-create` 판처럼 싣는다. + - 라우터는 페이지를 그리기 전에 그 codec으로 검색값을 해석한다. 틀린 값이면 페이지 대신 잘못된 경로 화면을 그린다. + - 조각 2(`presentation/use--list-filters.ts`)가 페이지에서 그 값을 타입대로 읽는 hook이다. 같은 codec으로 다시 읽으므로 cast가 없다. + + +```ts +import { z } from "../../../contracts/zod.ts"; + +/** The list route's search values (`?status=open`). Absent means every invoice. */ +export const invoiceListSearchSchema = z + .object({ status: z.enum(["open", "paid"]).optional() }) + .strict(); + +export type InvoiceListSearch = z.output; +``` + + +```ts +import { useMemo } from "react"; + +import { useRouteInput } from "../../../presentation/routes/route-input.tsx"; +import { + invoiceListSearchSchema, + type InvoiceListSearch, +} from "../contracts/invoice-list-search.ts"; + +/** + * The router parsed the search with this codec before the page rendered. + * Reading it back through the same codec gives its type without a cast. + */ +export function useInvoiceListFilters(): InvoiceListSearch { + const { search } = useRouteInput(); + return useMemo(() => invoiceListSearchSchema.parse(search), [search]); +} +``` + - 상세 경로는 목록 경로 뒤에 `/items/:`을 붙인다. 예: `/notice/items/:noticeId`. `/notice/:noticeId`로 두지 않는다. - 라우터(React Router)는 같은 자리에서 정적 경로를 먼저 고른다. 작성 폼 `/notice/new`가 있으면 id가 `new`인 공지는 `/notice/:noticeId`로 열 수 없다. - - `items/`를 끼우면 정적 경로와 겹치지 않는다. 참조 기능도 이렇게 한다(`/examples/reference-resources/items/:resourceId`). + - `items/`를 끼우면 정적 경로와 겹치지 않는다. 생성 판(`--with-create`)의 상세 라우트도 이렇게 한다(`<목록 경로>/items/:Id`). - `tests/e2e/accessibility.spec.ts`는 기능마다 고치지 않는다(1103/16-03). - 이 spec은 등록된 모든 라우트를 열어 axe로 검사한다. 경로 파라미터는 이름과 상관없이 모두 `a11y-1`로 바꾼다. 파라미터 스키마가 이 값을 거부하면 기능 페이지 대신 잘못된 경로 화면을 검사하므로, id 스키마는 짧은 영문·숫자 문자열을 받게 둔다. - API 요청은 설치된 descriptor에서 method와 `pathTemplate`으로 찾아 답한다. 목록 조회에는 빈 목록을 그 operation의 모양(`responseEnvelope: "ENVELOPE_V1"`이면 Envelope)으로 답한다. 그 뒤 경고 상자(`role="alert"`)가 없는지 본다. 그래서 목록 페이지는 빈 상태로 검사된다. @@ -492,7 +552,7 @@ projectRequest: (input) => Object.freeze({ }); ``` - - 예제(참조 기능): `src/features/reference-feature/presentation/use-reference-feature.ts`의 생성 뮤테이션 정책. + - 예제: `create:feature --with-create`의 `presentation/use--create.ts`. ③ **잡는 검사 / 못 잡는 것** @@ -524,7 +584,40 @@ projectRequest: (input) => Object.freeze({ - 화면 문구는 모두 catalog에서 가져온다(`message(key)`). - 링크는 6단계의 URL 함수로 만든다. -- 결과 불명 화면 예제: `create:feature --with-create`의 `presentation/-create-page.tsx`(짝 백엔드 Envelope), 참조 기능의 `src/features/reference-feature/presentation/reference-resource-form-page.tsx`(problem details) +- 결과 불명 화면 예제: `create:feature --with-create`의 `presentation/-create-page.tsx`. problem details 백엔드도 화면은 같다. 다른 것은 `commandEffect`와 `mapProblem`뿐이다([02 결정표 4절](02-decision-tables.md#4-결과-불명)). +- 다시 시도가 아닌 실패 행동(다시 로그인, 안전한 화면으로 이동)의 버튼은 페이지가 handler를 넘길 때만 그려진다. 생성된 목록 페이지는 `onRetry`만 넘긴다. + - 실패의 `action`(`src/contracts/errors.ts`의 `ERROR_REGISTRY`)이 `reauth`(401)·`navigate`(403·404)일 때 쓸 hook이다. `AsyncSurface`에 `onAction={useInvoiceFailureAction(query.state.failure)}`로 넘긴다. + - `retry`는 쿼리(`onRetry`)가, `reload-once`는 청크 복구 경계가 맡는다. 이 hook은 `undefined`를 돌려준다. + + +```ts +import { useCallback } from "react"; +import { useLocation, useNavigate } from "react-router-dom"; + +import type { AppFailure } from "../../../contracts/errors.ts"; +import { useSession } from "../../../presentation/providers/session-provider.tsx"; + +/** Sign in again and come back here, or leave for the home screen. */ +export function useInvoiceFailureAction( + failure: AppFailure | undefined, +): (() => void) | undefined { + const location = useLocation(); + const navigate = useNavigate(); + const { beginSignIn } = useSession(); + const action = failure?.action; + const handleAction = useCallback(() => { + if (action === "reauth") { + const returnTo = `${location.pathname}${location.search}${location.hash}`; + void beginSignIn(returnTo).catch(() => { + void navigate("/"); + }); + return; + } + if (action === "navigate") void navigate("/"); + }, [action, beginSignIn, location.hash, location.pathname, location.search, navigate]); + return action === "reauth" || action === "navigate" ? handleAction : undefined; +} +``` ③ **잡는 검사 / 못 잡는 것** @@ -621,7 +714,38 @@ projectRequest: (input) => Object.freeze({ expect(await posts[0]!.json()).toEqual({ title: "새 공지", body: "본문입니다." }); ``` - - 핸들러를 직접 써서 요청을 모으는 방법도 있다. 예제(참조 기능): `tests/features/reference-feature/reference-production-vertical.test.tsx`의 504 재전송 테스트. + - 핸들러를 직접 써서 요청을 모으는 방법도 있다. 예제: `create:feature --with-create --keyed`의 `tests/features//-create-page.test.tsx`(POST를 받을 때마다 사본을 모으고 같은 키 재전송을 본다). +- 서버 권한 거절(403)은 라우터를 거치는 페이지 테스트로 본다. 생성된 페이지 테스트와 같은 도우미(`-test-app.tsx`)를 쓴다. + - 403은 본문 없이 답한다. 실행기는 401·403의 본문을 읽지 않고 닫는다. 페이지 테스트 환경(jsdom + MSW)에서 본문이 있는 403(공유 시나리오 `forbidden-403`)은 그 닫기가 끝나지 않아 화면이 로딩에 머물렀다(2026-11-08 확인). + + +```tsx +// @vitest-environment jsdom + +import { screen, within } from "@testing-library/react"; +import { http, HttpResponse } from "msw"; +import { setupServer } from "msw/node"; +import { afterAll, afterEach, beforeAll, expect, it } from "vitest"; + +import { invoiceRouteUrl } from "../../../src/features/invoice-feature/presentation/invoice-routes.ts"; +import { KO_MESSAGES } from "../../../src/presentation/i18n/catalog.ts"; +import { API, openSignedIn } from "./invoice-test-app.tsx"; + +const api = setupServer(); +beforeAll(() => api.listen({ onUnhandledRequest: "error" })); +afterEach(() => api.resetHandlers()); +afterAll(() => api.close()); + +it("shows the forbidden state when the backend refuses the list", async () => { + api.use(http.get(`${API}/invoices`, () => new HttpResponse(null, { status: 403 }))); + await openSignedIn(invoiceRouteUrl("INVOICE_LIST")); + + const alert = await screen.findByRole("alert"); + expect( + within(alert).getByRole("heading", { name: KO_MESSAGES["access.forbidden.title"] }), + ).toBeVisible(); +}); +``` - 빠르게 돌리기: `node scripts/run-vitest.ts run tests/features/` - CI에서는 `test:coverage`(FE-GATE-005)가 `tests/features`를 돈다. `test:unit`은 `tests/unit`만 돈다. @@ -683,7 +807,7 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature - 지연 페이지가 셸과 같은 구성요소(`Button`, `SearchField` 등)를 쓰면 그 구성요소가 공유 청크로 떨어져 초기 파일 수도 하나 늘 수 있다. 파일 수 상한(`initialJsFiles`)은 여유가 있다. - 예산은 `config/performance/budgets.json`에 있다. 넘었을 때 고르는 법은 `docs/operations/performance-evidence.md`에 있다. 넘으면 예산을 올리기 전에 팀이 정한다. - 생성 명령의 드릴(`test:feature-scaffold`)도 merge 단계 명령으로 이 검사를 돈다. -- 참조 기능이 설치돼 있으면 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 기능과 함께 바뀐다. `test:unit`이 빌드와 대조한다. 생성 명령 출력 `Next:` 3번의 명령으로 다시 쓰고 같은 커밋에 넣는다. 기능 제거 드릴(`test:sample-removal -- --feature=`)은 지운 뒤 기록을 다시 쓰고 검사한다. +- 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 기능과 함께 바뀐다. `test:unit`이 빌드와 대조한다. 생성 명령 출력 `Next:` 3번의 명령으로 다시 쓰고 같은 커밋에 넣는다. 기능 제거 드릴(`test:sample-removal -- --feature=`)은 지운 뒤 기록을 다시 쓰고 검사한다. - 로컬에서 FE-GATE-013을 돌리려면 `VITE_COMMIT_SHA=$(git rev-parse HEAD)`를 준다. 없으면 release candidate가 `source.revision`을 거절한다. 실패한 게이트의 로그는 `artifacts/quality/gates/FE-GATE-.txt`에 있다. - workflow와 같은 조건으로 돌리려면 README 로컬 merge 게이트 반복문 아래의 env 블록대로 `CI=true`와 CI 빌드 식별값(`VITE_COMMIT_SHA`, `VITE_BUILD_ID`, `RELEASE_ID`, `CI_RUNNER_IMAGE` digest)을 주고 깨끗한 clone에서 돌린다. 이 값 없이 통과해도 CI에서 떨어질 수 있다(1103/11-07, 11-08). - 게이트는 한 checkout에서 하나씩 돌린다. 게이트와 증거 검사는 `dist`와 `artifacts/`의 고정 경로를 읽는다. diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index 10e5d217..991025b1 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -50,9 +50,9 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 | | 배포된 계약 패키지 | 자리표시자 신원 | `TEMPLATE_FIXTURE` | |---|---|---|---| -| 언제 | 백엔드가 `@org-contracts/` 패키지를 배포했다 | 패키지가 아직 없다 | 쓰지 않는다. 참조 기능 전용이다 | +| 언제 | 백엔드가 `@org-contracts/` 패키지를 배포했다 | 패키지가 아직 없다 | 쓰지 않는다. 템플릿이 예전 참조 샘플에 쓰던 출처다 | | 만드는 법 | `create:feature`에 `--package`, `--digest`, `--revision`을 준다 | `create:feature`에 패키지 인자를 주지 않는다 | — | -| 로컬·개발 빌드 | 된다 | 된다 | 참조 기능 밖에서는 계약 조립이 거부한다 | +| 로컬·개발 빌드 | 된다 | 된다 | 제품 기능에 쓰면 계약 조립이 거부한다 | | staging·production 승인 | 된다 | `check:release-admission`(FE-GATE-027)이 거절한다 | — | 자리표시자 값은 `src/contracts/deployment-admission.ts`의 세 상수다. @@ -88,7 +88,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 |---|---|---|---| | 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 | | 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다. 예외: 짝 백엔드가 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거절)로 답하면 `retryBudget` 안에서 같은 키로 다시 보낸다 | 된다 | 하지 않는다 | -| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 짝 백엔드는 `retryBudget: 1`(아래 표), 참조 기능은 `0` | — | `retryBudget: 0` 필수 | +| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 짝 백엔드는 `retryBudget: 1`(아래 표). 503 같은 키 재전송 규칙이 없는 백엔드는 `0` | — | `retryBudget: 0` 필수 | | 뮤테이션 정책 | `...commandMutationIdentity(_CONTRACT)`가 `requiresIdempotencyKey: true`, `resendSafe: true`를 준다 | 같은 함수가 `requiresIdempotencyKey: false`, `resendSafe: true`를 준다 | 같은 함수가 둘 다 `false`로 준다 | | 결과 불명 뒤 | "같은 요청으로 다시 보내기"와 같은 입력 저장이 같은 키로 간다 | 다시 보내기와 같은 입력 저장이 키 없이 간다(1106/03-03) | 확인만 남는다. 같은 입력 저장은 보내지 않는다 | @@ -198,8 +198,8 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 → V3 실행기 ├─ responseEnvelope: "ENVELOPE_V1" (생성한 기능) → 실행기가 MAYBE_APPLIED로 정한다 │ KEYED이고 retryBudget > 0이면 먼저 같은 키로 다시 보낸다(3절). 예산을 다 쓰면 결과 불명 - └─ Envelope 없음 (참조 기능) → 기능의 classifyProblem이 정한다 - 참조 기능: 400·422와 정해 둔 409 code만 NOT_APPLIED → 503은 MAYBE_APPLIED + └─ Envelope 없음 (problem details 백엔드) → 기능의 classifyProblem이 정한다 + 아래 예: 400·422와 정해 둔 409 code만 NOT_APPLIED → 503은 MAYBE_APPLIED → 결과 불명 화면 → "같은 요청으로 다시 보내기"가 같은 키로 보낸다 ``` @@ -210,7 +210,123 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 **정본**: 어떤 status·code가 "적용 안 됨"인지는 `clean-architecture-backend-template/docs/web/http-contract.md` §2다. -**어디에 적나**: `contracts/-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 예제(참조 기능): `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`의 `CREATE_EFFECT`. +**어디에 적나**: `contracts/-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 짝 백엔드 예제는 `create:feature --with-create`가 만든 그 파일이다. Envelope가 없는 백엔드의 예는 아래에 있다. + +**problem details 백엔드의 예** + +짝 백엔드가 아닌 백엔드는 DTO와 problem details(RFC 9457의 `type`·`title`·`status`)를 감싸지 않고 보낸다. 그 백엔드의 작성 operation이 쓰는 두 조각이다. 기능 이름은 `invoice-feature`(`create:feature invoice-feature --with-create`로 만든 기능)로 두었다. 자기 기능의 이름으로 바꿔 쓴다. + +- 조각 1은 `contracts/-problem-details.ts`다. problem 스키마와 검증기, 작성의 `commandEffect`를 둔다. + - descriptor마다 `responseEnvelope: "NONE" as const`, `problemValidator: _PROBLEM_VALIDATOR`를 적는다. 작성 descriptor의 `commandEffect`는 `_CREATE_EFFECT`다. Envelope operation 전용인 `refusedBeforeWrite`는 적지 않는다. + - 스키마 ID(`InvoiceProblem`)도 다른 스키마처럼 스키마 메타데이터(`contracts/-schema-metadata.ts`)에 적는다. 없으면 `check:registries`가 실패한다. +- 조각 2는 `adapters/-problem-mapping.ts`다. HTTP 바인딩의 `mapProblem`이 되는 함수다. + - `adapters/-http-gateway.ts`의 작성 operation 정의에 `mapProblem: mapCreateProblem`으로 넘긴다. + - 정하지 않은 status는 `undefined`를 돌려준다. 그러면 실행기가 status로 실패 종류를 정한다. + + +```ts +import { z } from "../../../contracts/zod.ts"; + +import type { CommandEffectDescriptor } from "../../../contracts/external-contract-runtime.ts"; +import { zodValidator } from "../../../contracts/zod-validator.ts"; + +export const invoiceProblemSchema = z + .object({ + type: z.string().min(1).max(512), + title: z.string().min(1).max(240), + status: z.int().min(100).max(599), + code: z.string().min(1).max(120).optional(), + // 422 field issues. The backend's messages are not kept. + issues: z + .array( + z + .object({ + path: z.string().min(1).max(120), + code: z.string().min(1).max(80), + }) + .strip(), + ) + .max(50) + .optional(), + }) + .strip(); + +export type InvoiceProblem = z.output; + +export const INVOICE_PROBLEM_VALIDATOR = zodValidator( + "InvoiceProblem", + invoiceProblemSchema, +); + +/** + * A 409 is not by itself "refused": a resend with the same key can meet the + * first attempt still running. Only the conflict codes the backend sends + * before it writes are NOT_APPLIED; any other 409 stays MAYBE_APPLIED, so the + * next send reuses the key. + */ +const NOT_APPLIED_CONFLICT_CODES: ReadonlySet = new Set(["CONFLICT"]); + +export const INVOICE_CREATE_EFFECT: CommandEffectDescriptor = + Object.freeze({ + successEffect: "APPLIED_CONFIRMED" as const, + classifyProblem({ + status, + problem, + }: Readonly<{ status: number; problem: InvoiceProblem }>) { + if (status === 400 || status === 422) return "NOT_APPLIED"; + if ( + status === 409 && + problem.code !== undefined && + NOT_APPLIED_CONFLICT_CODES.has(problem.code) + ) { + return "NOT_APPLIED"; + } + return "MAYBE_APPLIED"; + }, + // The backend refuses an unauthenticated, forbidden or rate-limited + // create before it touches state. Delete this line if it does not. + classifyStatus: () => "NOT_APPLIED" as const, + }); +``` + + +```ts +import type { + FeatureHttpProblemMapping, + SafeResponseMetadata, +} from "../../../adapters/http/index.ts"; +import type { InvoiceProblem } from "../contracts/invoice-problem-details.ts"; + +export function mapInvoiceCreateProblem( + problem: InvoiceProblem, + metadata: SafeResponseMetadata, +): FeatureHttpProblemMapping | undefined { + if (metadata.status === 409) { + return Object.freeze({ + kind: "CONFLICT" as const, + code: problem.code ?? "INVOICE_CONFLICT", + }); + } + // The executor checked the key before it sent, so this names a key rule + // the two sides disagree on: keep the code for diagnostics. + if (metadata.status === 400 && problem.code === "IDEMPOTENCY_KEY_INVALID") { + return Object.freeze({ + kind: "UNKNOWN_CLIENT_FAILURE" as const, + code: problem.code, + }); + } + if (metadata.status === 422) { + return Object.freeze({ + kind: "VALIDATION_REJECTED" as const, + code: problem.code ?? "INVOICE_REJECTED", + validationIssues: problem.issues ?? [], + }); + } + return undefined; +} +``` + +- 이 두 조각은 `tests/unit/manual-code-blocks.test.ts`가 시험한다. 저장소 사본에 `create:feature invoice-feature --with-create`로 기능을 만들고, 조각을 위 경로에 그대로 넣어 타입 검사를 하고, 분류와 매핑이 위 설명대로인지 돌려 본다(`tests/fixtures/manual-code-blocks/`). **틀리면** diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 69058b8c..d96aeef6 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -38,7 +38,7 @@ | 파일 | 누가 쓰나 | 다시 쓰는 명령 | 안 넣으면 | |---|---|---|---| | `public/release-manifest.json` (dev server의 manifest) | `create:feature`가 생성 뒤 바로 쓴다. 설치된 계약 패키지 목록(`packages`)과 그 다이제스트(`setDigest`) | `node scripts/write-dev-release-manifest.ts` | `test:unit`(`tests/unit/dev-release-manifest.test.ts`)이 다시 쓰는 명령을 말하며 실패한다. dev server가 `CONTRACT_SET_PACKAGE_MISSING`으로 부팅하지 못한다 | -| `config/scale/feature-shape-ceilings.json`의 `initialJavascript` (초기 JS 기록) | 사람이 명령으로 쓴다. 참조 기능이 설치돼 있는 동안만 있다(참조 기능과 함께 지워진다) | `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write` | `test:unit`이 빌드와 대조해 실패한다 | +| `config/scale/feature-shape-ceilings.json`의 `initialJavascript` (초기 JS 기록) | 사람이 명령으로 쓴다. 기능을 더하거나 뺄 때마다 바뀐다 | `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write` | `test:unit`이 빌드와 대조해 실패한다 | - **브랜치 둘이 충돌한다.** `setDigest`는 설치된 패키지 전체의 해시 한 줄이고, `initialJavascript`는 빌드 전체의 합계다. 기능을 하나씩 더한 두 브랜치는 같은 줄을 다른 값으로 바꾼다. 둘째 브랜치를 합칠 때 텍스트 충돌이 난다. - **충돌하면 손으로 값을 합치지 않는다.** 아무 쪽이나 고른 뒤 위 명령을 다시 돌려 그 결과를 커밋한다. 두 기능이 다 들어간 상태의 값이 나온다. 손으로 합친 값이 틀리면 `test:unit`이 같은 명령을 말하며 실패한다. @@ -212,7 +212,7 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE) - `config/testing/risk-coverage.json`에서 그 기능을 가리키는 행 - 그 기능만 쓰던 제품 capability, 제품 인증 프로필, 계약 패키지 의존성 -그다음 dev manifest(`public/release-manifest.json`)의 계약 패키지를 `node scripts/write-dev-release-manifest.ts`로 다시 쓰고, 참조 기능이 설치돼 있으면 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`로 다시 쓴다(위 A의 표). 그리고 레지스트리 기준선을 다시 찍는다. 행을 빼는 것은 breaking 변경이다. +그다음 dev manifest(`public/release-manifest.json`)의 계약 패키지를 `node scripts/write-dev-release-manifest.ts`로 다시 쓰고, 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`로 다시 쓴다(위 A의 표). 그리고 레지스트리 기준선을 다시 찍는다. 행을 빼는 것은 breaking 변경이다. ```bash REGISTRY_BASELINE_OWNER=<담당> REGISTRY_BASELINE_REASON=" removed" corepack pnpm update:registry-baseline diff --git a/docs/manual/README.md b/docs/manual/README.md index 3b515366..1f1cf753 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -75,8 +75,8 @@ README (이 문서) - `docs/architecture/starter-experience.md`의 예전 "폴더 밖 수정" 4행 표와 "governance는 바뀌지 않는다" 문장(2026-11-01 리뷰 시점 판). - 그 판은 실제로 고쳐야 하는 파일을 다 적지 않았다. - 지금 판의 "Adding a feature" 절 표가 정본이다. 03 문서가 이 표를 링크한다. -- 참조 기능 페이지의 경로 문자열과 route 입력 cast. - - 지금은 고쳐졌다. 그래도 이 매뉴얼의 예시는 route ID와 `buildRouteUrl`로만 쓴다. +- 템플릿이 예전에 두던 참조 샘플 기능과 예제 화면을 가리키는 문서와 리뷰 기록. + - 그 샘플은 지웠다. 이 매뉴얼의 예시는 생성 명령 출력과 매뉴얼 안 코드 조각이다(`tests/unit/manual-code-blocks.test.ts`가 시험한다). ## 문서와 코드가 다를 때 diff --git a/docs/manual/reference/create-feature.md b/docs/manual/reference/create-feature.md index eec50049..0d08b926 100644 --- a/docs/manual/reference/create-feature.md +++ b/docs/manual/reference/create-feature.md @@ -2,7 +2,7 @@ 모든 merge 게이트를 통과하는 가장 작은 기능을 만드는 명령이다. 정본은 `scripts/create-feature.ts`이고, `--with-create`가 더하는 부분은 `scripts/create-feature-write-slice.ts`다. `test:feature-scaffold`가 생성한 기능으로 `config/ci/gates.json`의 merge 단계 명령을 돌려 확인한다. 브라우저 게이트(FE-GATE-008·009의 브라우저 명령)와 `test:system`은 빼고 돈다. 뺀 명령과 이유는 `scripts/lib/feature-scaffold-drill.ts`에 있다. -템플릿 문자열이 두 파일 안에 있고, 참조 기능을 import하지 않는다. 그래서 참조 기능을 지운 프로젝트에서도 동작한다. +템플릿 문자열이 두 파일 안에 있고, 다른 기능을 import하지 않는다. 그래서 기능이 하나도 없는 템플릿에서도 동작한다. ## 사용법 @@ -150,7 +150,7 @@ node scripts/write-dev-release-manifest.ts # dev manifest에서 그 기능의 - `tests/unit/create-feature.test.ts` (`test:unit`, FE-GATE-005) - 렌더 결과만 본다. 저장소를 건드리지 않는다. - - 접두어, 참조 기능 이름이 없음, topic 형식과 충돌, `navigationOrder`, 거부 조건, 덮어쓰기 거부와 되돌리기. + - 접두어, 예전 참조 샘플 이름이 없음, topic 형식과 충돌, `navigationOrder`, 거부 조건, 덮어쓰기 거부와 되돌리기. - 백엔드 경로 규칙, `--with-create`·`--keyed`의 descriptor 값, 모든 operation의 Envelope 선언. - 생성한 context 선언을 임시 폴더에 써서 생성기의 선언 읽기(`createFileSystemDeclarationSource`)로 읽고, 그 모듈을 import해 라우트 루트가 기능 라우트를 모두 받는지 앱 모듈 조립으로 확인한다. - `test:feature-scaffold` (FE-GATE-020) @@ -161,6 +161,5 @@ node scripts/write-dev-release-manifest.ts # dev manifest에서 그 기능의 ## 알려진 한계 -- `--context reference-context`로 참조 context에 넣은 기능은 경로가 `/examples/reference-resources/`다. 참조 기능을 지우면 context가 남고 그 경로가 제거 드릴의 잔여 검사에 걸린다. 남길 기능은 제품 context에 둔다. - 드릴은 브라우저 테스트(FE-GATE-008·009의 `test:e2e`, `test:a11y` 등)와 `test:system`을 돌리지 않는다. `check:bundle`(FE-GATE-012)은 돈다. - 새 context는 앱이 하나일 때만 만든다. 앱이 여럿이면 `--context`로 기존 context를 고른다. diff --git a/docs/manual/reference/errors.md b/docs/manual/reference/errors.md index 1c05e428..13f0823c 100644 --- a/docs/manual/reference/errors.md +++ b/docs/manual/reference/errors.md @@ -95,7 +95,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010 | `reason` | 원인 | 고칠 곳 | |---|---|---| -| `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to reference-feature only; pin an EXTERNAL_PACKAGE` | 참조 기능 전용 출처를 다른 기능이 썼다 | `contracts/-contract-contribution.ts`의 `source`를 `EXTERNAL_PACKAGE`로 | +| `: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to only; pin an EXTERNAL_PACKAGE` | 템플릿 fixture 출처(예전 참조 샘플용)를 제품 기능이 썼다 | `contracts/-contract-contribution.ts`의 `source`를 `EXTERNAL_PACKAGE`로 | | `duplicate operation: ` | 두 기여가 같은 operation ID | 접두어를 붙인다 | | `duplicate contributionId: ` | 두 기여가 같은 `contributionId` | `contracts/-contract-contribution.ts` | | `/: unknown authProfileId ` | V3 `frontend.authProfileId`가 없는 프로필 | V3 `frontend.authProfileId` | diff --git a/docs/manual/reference/global-ids.md b/docs/manual/reference/global-ids.md index d4c97522..522b6249 100644 --- a/docs/manual/reference/global-ids.md +++ b/docs/manual/reference/global-ids.md @@ -49,7 +49,7 @@ - 무효화 topic은 새로 만든다. - 형식: `qinv.` + 소문자·숫자 26자. - `scripts/create-feature.ts`의 `randomTopicSuffix`가 같은 형식으로 만든다. - - 다른 기능이나 참조 기능의 값을 복사하지 않는다. + - 다른 기능의 값을 복사하지 않는다. - route ID는 `_<화면>` 꼴로 짓는다(`INVOICE_DETAIL`). 라우트를 더하면 a11y 기록 파일도 더한다(`artifacts/tests/a11y-manual/.md`). - 문구 키는 ko-KR과 en-US에 같은 키를 넣는다. `check:i18n`이 비교한다. diff --git a/docs/manual/reference/patterns.md b/docs/manual/reference/patterns.md index b133b745..5bfb9998 100644 --- a/docs/manual/reference/patterns.md +++ b/docs/manual/reference/patterns.md @@ -3,22 +3,22 @@ 기능을 만들 때 쓰는 패턴과, 그 패턴의 정의와 예제가 어디 있는지 적는다. - **정의**: 플랫폼(기능 밖)에서 패턴을 제공하는 파일. -- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `참조 기능`은 `src/features/reference-feature/`다(Envelope가 아닌 problem details 모양). 참조 기능 경로도 다른 경로처럼 백틱으로 적는다. 문서 검사(`verify:documentation`)는 참조 기능이 있는 동안 그 경로가 있는지 확인하고, 참조 기능을 지운 사본에서는 없어도 된다고 본다(`scripts/lib/removable-template-features.ts`). +- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `코드 조각`은 매뉴얼 안의 코드 블록이다. 생성 뼈대에 없는 모양을 보이고, `tests/unit/manual-code-blocks.test.ts`가 생성 기능 위에서 타입 검사와 동작 시험을 돌린다. - 예제가 없는 패턴은 **없음**이라고 적었다. 그 패턴은 정의를 읽고 직접 쓴다. -참조 기능은 예제일 뿐이다. 복사해 이름을 바꾸지 않는다. 모양을 보고 생성 뼈대에 옮긴다. +템플릿에는 복사해 볼 기능 샘플이 없다. 모양을 보고 생성 뼈대에 옮긴다. ## 기능 조립 | 패턴 | 정의 | 예제 | 검사 | |---|---|---|---| | 기능 모듈 등록 | `src/features/feature-module.ts` (`defineFeatureModule`, `defineFeatureRuntime`), 생성기 | 생성 뼈대 `feature-module.ts`, `feature-runtime.ts` | 생성기, 기능 ID와 계약 `featureId` 일치 | -| context 소속 선언 | `src/contexts/bounded-context-module.ts` | 참조 기능의 `src/contexts/reference-context/context-module.ts` | 생성기(없는 context, 예산), 앱 모듈(루트 밖 라우트) | +| context 소속 선언 | `src/contexts/bounded-context-module.ts` | 생성 뼈대 `src/contexts/-context/context-module.ts`(새 context를 만들 때) | 생성기(없는 context, 예산), 앱 모듈(루트 밖 라우트) | | context 전용 레이아웃 | `docs/architecture/starter-experience.md` "Product home and layouts" | `tests/helpers/fixture-layout-product.tsx` (테스트 fixture) | `tests/component/context-layouts.test.tsx` | | 앱 홈 대신하기 | `src/contracts/routes.ts`의 `FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS` | 없음 (기능 예제) | 조립 (두 기능이 `APP_HOME`을 선언하면 실패) | | 조립 기여(`needs`) | `src/features/feature-adapter-contribution.ts` | 생성 뼈대 `adapters/create--feature-input.ts` | 조립 (없는 capability, 다른 기능의 input) | | 제품 capability | `src/features/product-capabilities.ts`(타입), `src/bootstrap/product-composition.ts`(값), `src/bootstrap/product-composition-contract.ts` | `recipes/frontend-capabilities/indexeddb-feature-capability.ts` | `check:types` | -| 기능 끄기 | `config/runtime/.json`의 `FEATURE_OVERRIDES` | `config/runtime/local.json` | 참조 기능의 `tests/component/product-feature-switch.test.tsx` | +| 기능 끄기 | `config/runtime/.json`의 `FEATURE_OVERRIDES` | `config/runtime/local.json` | `tests/component/product-feature-switch.test.tsx`(시험 전용 기능으로 메뉴·홈 링크·직접 주소를 본다) | ## 라우트 @@ -26,9 +26,9 @@ |---|---|---|---| | 라우트 선언 | `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` | 쓰기 slice `presentation/-route-codecs.ts`(상세 params), 참조 기능 `presentation/reference-route-codecs.ts` | 해석 실패 시 잘못된 경로 화면 | -| URL 검색값 읽기 | `src/presentation/routes/route-input.tsx`의 `useRouteInput` + 검색값 codec | 참조 기능 `presentation/reference-routes.ts` | 해석 실패 시 잘못된 경로 화면 | +| route ID로 URL 만들기 | `src/presentation/routes/route-codecs.ts`의 `buildRouteUrl` | 생성 뼈대 `presentation/-routes.ts` | 타입(기능의 route ID만 받음) | +| 파라미터·검색값 codec | `src/presentation/routes/route-codecs.ts` | 쓰기 slice `presentation/-route-codecs.ts`(상세 params). 검색값 codec은 [01 문서 6단계](../01-add-a-feature.md#6단계-라우트)의 코드 조각 | 해석 실패 시 잘못된 경로 화면 | +| URL 검색값 읽기 | `src/presentation/routes/route-input.tsx`의 `useRouteInput` + 검색값 codec | 코드 조각: [01 문서 6단계](../01-add-a-feature.md#6단계-라우트)의 `contracts/-list-search.ts`, `presentation/use--list-filters.ts` | 해석 실패 시 잘못된 경로 화면 | | URL 검색값을 바꾸는 폼 | `buildRouteUrl`의 `search`, 디자인 시스템 `SearchField`, `CollectionPage`의 `toolbar` | 기능 예제 없음. 아래 짧은 예 | 라우터를 거치는 페이지 테스트 | ### URL 검색값을 바꾸는 폼 (짧은 예) @@ -46,7 +46,7 @@ - 목록 라우트의 `searchSchema`와 `routeRuntimeContracts`의 `searchCodec`. - 그 codec을 `context-routes.ts` handle의 `codecs`와 URL 함수(`buildRouteUrl`의 세 번째 인자)에 함께 넘긴다. -- 검색값을 읽는 hook. 참조 기능 `reference-routes.ts`의 `useReferenceListFilters`가 예제다. +- 검색값을 읽는 hook. [01 문서 6단계](../01-add-a-feature.md#6단계-라우트)의 코드 조각 `use--list-filters.ts`가 예제다. ```tsx // 공지 기능의 목록 페이지. noticeRouteUrl은 생성된 -routes.ts의 URL 함수다. @@ -84,9 +84,9 @@ 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 바인딩) | 쓰기 slice `adapters/-http-gateway.ts`(400 `_INVALID` → 이름 칸), 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 | +| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 쓰기 slice `adapters/-http-gateway.ts`(400 `_INVALID` → 이름 칸). problem details 백엔드(409, 422)는 [02 결정표 4절](../02-decision-tables.md#4-결과-불명)의 코드 조각 | 기능 테스트 | | 결과와 실패 | `src/contracts/result.ts`, `src/contracts/errors.ts` | 생성 뼈대 `application/-feature-api.ts` | `FailureKind` 닫힌 어휘(타입) | -| 실패 → 화면 행동 | `src/contracts/errors.ts`의 `action` | 참조 기능 `presentation/use-reference-failure-action.ts` | 페이지 테스트 | +| 실패 → 화면 행동 | `src/contracts/errors.ts`의 `action` | 코드 조각: [01 문서 8단계](../01-add-a-feature.md#8단계-페이지)의 `presentation/use--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,29 +95,29 @@ 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에서 받는다) | 쓰기 slice `--keyed`(`contracts/-contract-contribution.ts`, `presentation/use--create.ts`), 참조 기능 생성 명령(`use-reference-feature.ts`, `reference-feature-contract-contribution.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 | -| 결과 불명 화면 | `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`) | 없음 (참조 기능은 생성 명령만 있다) | — | +| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/-contract-contribution.ts`, `presentation/use--create.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 | +| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/-create-page.tsx` | 기능 테스트만(쓰기 slice는 `-create-page.test.tsx`) | +| 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (쓰기 slice는 작성 명령만 만든다) | — | | 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 | -| 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (참조 기능은 커서 필터만, 다음 커서 없음) | 런타임 테스트만 | +| 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (생성 뼈대 목록은 첫 페이지와 `meta.page.total`만 읽는다) | 런타임 테스트만 | | 로컬 저장(IndexedDB) | `recipes/frontend-capabilities/indexeddb-feature-capability.ts` + `product-composition.ts` | `tests/fixtures/indexeddb-consumer/` (시험이 조립하는 소비자 fixture, 기능 폴더 모양) | 계약 테스트 | ## 화면 | 패턴 | 정의 | 예제 | 검사 | |---|---|---|---| -| 페이지 템플릿 | `src/presentation/templates/page-templates.tsx` | 생성 뼈대 `CollectionPage`, 참조 기능 페이지 4개 | `page-templates-own-layout-only` | +| 페이지 템플릿 | `src/presentation/templates/page-templates.tsx` | 생성 뼈대 `CollectionPage`, 쓰기 slice `DetailPage`·`FormPage` | `page-templates-own-layout-only` | | 비동기 상태 화면 | `src/presentation/components/async-surface.tsx`의 `AsyncSurface` | 생성 뼈대 목록 페이지 | 페이지 테스트 | -| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 쓰기 slice `presentation/-form.ts`와 `-create-page.tsx`, 참조 기능 `presentation/reference-resource-form.ts`와 폼 페이지 | 페이지 테스트(서버 필드 오류, 이탈 확인) | +| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 쓰기 slice `presentation/-form.ts`와 `-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인) | | 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/-message-catalog.ts` | `lint`(문구 literal), `check:i18n`(ko-KR·en-US 키) | -| 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 참조 기능 403 화면 테스트 | 가드 테스트. 역할·권한 힌트 예제는 없음 | +| 권한 분기 | 라우트 `access`, 서버 403 → 실패 | 코드 조각: [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 403 페이지 테스트 `tests/features//-forbidden.test.tsx` | 가드 테스트. 역할·권한 힌트 예제는 없음 | ## 테스트 | 패턴 | 정의 | 예제 | 검사 | |---|---|---|---| | 응답 시나리오 | `tests/mocks/handlers/http-scenarios.ts`의 `createHttpScenarioHandler` | 생성 뼈대 페이지 테스트 | `test:coverage` | -| 보낸 요청(헤더·본문) 확인 | MSW `setupServer().events.on("request:start")` | [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 짧은 예. 핸들러에서 모으는 방법은 참조 기능 `reference-production-vertical.test.tsx`의 504 재전송 테스트 | `test:coverage` | +| 보낸 요청(헤더·본문) 확인 | MSW `setupServer().events.on("request:start")` | [01 문서 10단계](../01-add-a-feature.md#10단계-테스트)의 짧은 예. 핸들러에서 모으는 방법은 쓰기 slice `--keyed`의 `tests/features//-create-page.test.tsx` | `test:coverage` | | 같은 멱등 키 재전송 | 시나리오 `in-flight-409` + 위 요청 모으기 | 01 문서 10단계 | `test:coverage` | ## 관측 diff --git a/scripts/lib/removal-fixture.ts b/scripts/lib/removal-fixture.ts index 0fd8afe2..de5b83a9 100644 --- a/scripts/lib/removal-fixture.ts +++ b/scripts/lib/removal-fixture.ts @@ -84,6 +84,8 @@ export const REMOVAL_FIXTURE_DOCUMENT_TESTS = Object.freeze([ "tests/unit/template-feature-removal-documents.test.ts", // 1105/14-02. Reads a code block of docs/manual. "tests/unit/manual-paired-backend-settings.test.ts", + // Reads the marked code blocks of docs/manual. + "tests/unit/manual-code-blocks.test.ts", ] as const); /** The tests a fixture copied from `copyTargets` cannot run. */ diff --git a/tests/fixtures/manual-code-blocks/manual-code-blocks.check.tsx b/tests/fixtures/manual-code-blocks/manual-code-blocks.check.tsx new file mode 100644 index 00000000..6bb0bf89 --- /dev/null +++ b/tests/fixtures/manual-code-blocks/manual-code-blocks.check.tsx @@ -0,0 +1,192 @@ +// @vitest-environment jsdom + +// What the manual's code blocks do. tests/unit/manual-code-blocks.test.ts +// copies this file into the tests folder of the feature the blocks are +// written for, in a repository copy that has that feature and the blocks at +// their marked paths, and puts the feature's folder name for `{{feature}}`. +// The imports resolve there, not here: written out, they would read as a +// product feature's residue to the removal drill (scripts/lib/feature-residue.ts). +import { act, renderHook } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { MemoryRouter, useLocation } from "react-router-dom"; +import { describe, expect, it, vi } from "vitest"; + +import { createAnonymousSessionAdapter } from "../../../src/adapters/auth/index.ts"; +import { createFailure } from "../../../src/contracts/errors.ts"; +import { mapInvoiceCreateProblem } from "../../../src/features/{{feature}}/adapters/invoice-problem-mapping.ts"; +import { invoiceListSearchSchema } from "../../../src/features/{{feature}}/contracts/invoice-list-search.ts"; +import { + INVOICE_CREATE_EFFECT, + INVOICE_PROBLEM_VALIDATOR, +} from "../../../src/features/{{feature}}/contracts/invoice-problem-details.ts"; +import { createInvoice } from "../../../src/features/{{feature}}/domain/invoice.ts"; +import { useInvoiceFailureAction } from "../../../src/features/{{feature}}/presentation/use-invoice-failure-action.ts"; +import { useInvoiceListFilters } from "../../../src/features/{{feature}}/presentation/use-invoice-list-filters.ts"; +import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx"; +import { SessionProvider } from "../../../src/presentation/providers/session-provider.tsx"; +import { RouteInputProvider } from "../../../src/presentation/routes/route-input.tsx"; +import { createTestApplication } from "../../helpers/create-test-application.ts"; + +const PROBLEM = Object.freeze({ + type: "https://problems.example/invoice", + title: "Invoice refused", +}); + +describe("01 step 2: the domain model", () => { + it("keeps an invoice that falls due on or after its issue day, frozen", () => { + const invoice = createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-01", dueOn: "2026-11-01" }); + + expect(invoice).toEqual({ invoiceId: "inv-1", issuedOn: "2026-11-01", dueOn: "2026-11-01" }); + expect(Object.isFrozen(invoice)).toBe(true); + }); + + it("refuses an invoice due before it is issued, and a date that is no calendar date", () => { + expect(() => + createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-02", dueOn: "2026-11-01" }), + ).toThrow(RangeError); + expect(() => + createInvoice({ invoiceId: "inv-1", issuedOn: "2026-11-02", dueOn: "next week" }), + ).toThrow(RangeError); + }); +}); + +describe("02 section 4: a problem-details backend", () => { + it("reads a problem details body and keeps only its fields", () => { + const read = INVOICE_PROBLEM_VALIDATOR.safeParse({ + ...PROBLEM, + status: 422, + code: "INVOICE_REJECTED", + detail: "a backend message the screen never shows", + issues: [{ path: "dueOn", code: "BEFORE_ISSUE", message: "dropped" }], + }); + + expect(read).toEqual({ + success: true, + data: { + ...PROBLEM, + status: 422, + code: "INVOICE_REJECTED", + issues: [{ path: "dueOn", code: "BEFORE_ISSUE" }], + }, + }); + expect(INVOICE_PROBLEM_VALIDATOR.safeParse({ type: PROBLEM.type, status: 400 }).success).toBe(false); + expect(INVOICE_PROBLEM_VALIDATOR.schemaId).toBe("InvoiceProblem"); + }); + + it("calls a create refused only for 400, 422 and the declared 409 code", () => { + const classify = (status: number, code?: string) => + INVOICE_CREATE_EFFECT.classifyProblem({ + status, + problem: { ...PROBLEM, status, ...(code === undefined ? {} : { code }) }, + }); + + expect(classify(400)).toBe("NOT_APPLIED"); + expect(classify(422, "INVOICE_REJECTED")).toBe("NOT_APPLIED"); + expect(classify(409, "CONFLICT")).toBe("NOT_APPLIED"); + // A resend that meets the first attempt still running keeps its key. + expect(classify(409, "IDEMPOTENT_IN_FLIGHT")).toBe("MAYBE_APPLIED"); + expect(classify(409)).toBe("MAYBE_APPLIED"); + expect(classify(503, "IDEMPOTENCY_UNAVAILABLE")).toBe("MAYBE_APPLIED"); + expect(classify(500)).toBe("MAYBE_APPLIED"); + expect(INVOICE_CREATE_EFFECT.classifyStatus?.(403)).toBe("NOT_APPLIED"); + }); + + it("maps a conflict, a key rule mismatch and field issues, and leaves the rest to the executor", () => { + const problem = (status: number, extra: Readonly> = {}) => ({ + ...PROBLEM, + status, + ...extra, + }); + + expect(mapInvoiceCreateProblem(problem(409, { code: "CONFLICT" }), { status: 409 })).toEqual({ + kind: "CONFLICT", + code: "CONFLICT", + }); + expect(mapInvoiceCreateProblem(problem(409), { status: 409 })).toEqual({ + kind: "CONFLICT", + code: "INVOICE_CONFLICT", + }); + expect( + mapInvoiceCreateProblem(problem(400, { code: "IDEMPOTENCY_KEY_INVALID" }), { status: 400 }), + ).toEqual({ kind: "UNKNOWN_CLIENT_FAILURE", code: "IDEMPOTENCY_KEY_INVALID" }); + expect( + mapInvoiceCreateProblem(problem(422, { issues: [{ path: "dueOn", code: "BEFORE_ISSUE" }] }), { + status: 422, + }), + ).toEqual({ + kind: "VALIDATION_REJECTED", + code: "INVOICE_REJECTED", + validationIssues: [{ path: "dueOn", code: "BEFORE_ISSUE" }], + }); + expect(mapInvoiceCreateProblem(problem(400), { status: 400 })).toBeUndefined(); + expect(mapInvoiceCreateProblem(problem(503), { status: 503 })).toBeUndefined(); + }); +}); + +describe("01 step 6: reading the list route's search values", () => { + const withSearch = (search: Readonly>) => + function Search({ children }: Readonly<{ children: ReactNode }>) { + return ( + + {children} + + ); + }; + + it("reads the search the codec accepted, typed", () => { + expect(renderHook(useInvoiceListFilters, { wrapper: withSearch({ status: "open" }) }).result.current).toEqual({ + status: "open", + }); + expect(renderHook(useInvoiceListFilters, { wrapper: withSearch({}) }).result.current).toEqual({}); + }); + + it("refuses a value the router must answer with the invalid-route screen", () => { + expect(invoiceListSearchSchema.safeParse({ status: "void" }).success).toBe(false); + expect(invoiceListSearchSchema.safeParse({ status: "open", page: "2" }).success).toBe(false); + }); +}); + +describe("01 step 8: the failure action of a page", () => { + function renderAction(failure: Parameters[0]) { + const beginSignIn = vi.fn(async (_returnTo?: string) => {}); + const application = createTestApplication({ + session: { ...createAnonymousSessionAdapter(), beginSignIn }, + }); + const rendered = renderHook( + () => ({ handle: useInvoiceFailureAction(failure), location: useLocation() }), + { + wrapper: ({ children }: Readonly<{ children: ReactNode }>) => ( + + + {children} + + + ), + }, + ); + return { beginSignIn, rendered }; + } + + it("signs in again and comes back to the same URL", async () => { + const { beginSignIn, rendered } = renderAction(createFailure("AUTH_REQUIRED", "INVOICE_LIST_ITEMS", 0)); + + await act(async () => rendered.result.current.handle?.()); + + expect(beginSignIn).toHaveBeenCalledWith("/invoice?status=open#total"); + }); + + it("leaves a forbidden screen for home", async () => { + const { rendered } = renderAction(createFailure("FORBIDDEN", "INVOICE_LIST_ITEMS", 0)); + + await act(async () => rendered.result.current.handle?.()); + + expect(rendered.result.current.location.pathname).toBe("/"); + }); + + it("gives no handler for a retry or for no failure: the query owns retry", () => { + expect( + renderAction(createFailure("NETWORK_UNREACHABLE", "INVOICE_LIST_ITEMS", 0)).rendered.result.current.handle, + ).toBeUndefined(); + expect(renderAction(undefined).rendered.result.current.handle).toBeUndefined(); + }); +}); diff --git a/tests/unit/manual-code-blocks.test.ts b/tests/unit/manual-code-blocks.test.ts new file mode 100644 index 00000000..10ddabc9 --- /dev/null +++ b/tests/unit/manual-code-blocks.test.ts @@ -0,0 +1,140 @@ +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { afterAll, describe, expect, it } from "vitest"; + +import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts"; +import { REMOVAL_FIXTURE_COPY_TARGETS } from "../../scripts/lib/removal-fixture.ts"; + +/** + * 2026-11-07. The template ships no sample feature: what the generated + * feature does not show, docs/manual shows as code blocks a product copies + * into its feature folder. Each such block has `` + * above it, the path in the feature `create:feature invoice-feature + * --with-create` writes. Here a copy of the repository gets that feature, each + * block goes to its path unchanged, and the app and test typecheck programs, + * lint and the feature's tests run on it. A block that is a test runs as it + * is; what the other blocks do is checked by tests/fixtures/manual-code-blocks. + */ +const MANUAL = "docs/manual"; +const FEATURE_ID = "invoice-feature"; +const CHECKS = "tests/fixtures/manual-code-blocks"; +const MARKED_BLOCK = /\n```tsx?\n([\s\S]*?)\n```/gu; + +async function manualDocuments(directory: string): Promise { + const documents: string[] = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) documents.push(...(await manualDocuments(target))); + else if (entry.name.endsWith(".md")) documents.push(target); + } + return documents.sort(); +} + +/** Each marked block by the path it goes to. */ +async function markedBlocks(): Promise> { + const blocks = new Map(); + for (const document of await manualDocuments(MANUAL)) { + for (const [, target = "", body = ""] of (await readFile(document, "utf8")).matchAll(MARKED_BLOCK)) { + if (blocks.has(target)) throw new Error(`${target} is marked twice in ${MANUAL}`); + blocks.set(target, `${body}\n`); + } + } + return blocks; +} + +const roots: string[] = []; + +afterAll(async () => { + await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function copyRepository(): Promise { + const root = await mkdtemp(path.join(tmpdir(), "manual-code-blocks-")); + roots.push(root); + for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) { + // A removal drill runs this test in a copy that has already lost some. + if (!existsSync(path.resolve(entry))) continue; + await cp(path.resolve(entry), path.join(root, entry), { + recursive: true, + filter: (source) => !source.includes(`${path.sep}.generated`), + }); + } + await linkFixtureNodeModules(root); + return root; +} + +function run(root: string, command: string, args: readonly string[]) { + const result = spawnSync(command, args, { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }); + return { status: result.status, output: `${result.stdout}${result.stderr}` }; +} + +describe("docs/manual code blocks, pasted into a generated feature", () => { + it("marks each block with a path in the feature it is written for", async () => { + const targets = [...(await markedBlocks()).keys()].sort(); + + expect(targets).toEqual([ + "src/features/invoice-feature/adapters/invoice-problem-mapping.ts", + "src/features/invoice-feature/contracts/invoice-list-search.ts", + "src/features/invoice-feature/contracts/invoice-problem-details.ts", + "src/features/invoice-feature/domain/invoice.ts", + "src/features/invoice-feature/presentation/use-invoice-failure-action.ts", + "src/features/invoice-feature/presentation/use-invoice-list-filters.ts", + "tests/features/invoice-feature/invoice-forbidden.test.tsx", + ]); + }); + + it("typechecks, lints and does what the manual says", async () => { + const blocks = await markedBlocks(); + const root = await copyRepository(); + const node = process.execPath; + + // The generator runs first, as `corepack pnpm create:feature` does. + const indexed = run(root, node, ["scripts/generate-product-feature-index.ts"]); + expect(indexed.status, indexed.output).toBe(0); + const created = run(root, node, ["scripts/create-feature.ts", FEATURE_ID, "--with-create"]); + expect(created.status, created.output).toBe(0); + + for (const [target, block] of blocks) { + const file = path.join(root, target); + // A block adds a file; it never stands in for one the command wrote. + expect(existsSync(file), `${target} exists before the block is pasted`).toBe(false); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, block); + } + const checks = (await readdir(CHECKS)).filter((name) => name.endsWith(".check.tsx")); + expect(checks.length).toBeGreaterThan(0); + for (const check of checks) { + await writeFile( + path.join(root, "tests/features", FEATURE_ID, check.replace(/\.check\.tsx$/u, ".test.tsx")), + (await readFile(path.join(CHECKS, check), "utf8")).replaceAll("{{feature}}", FEATURE_ID), + ); + } + + for (const program of ["tsconfig.app.json", "tsconfig.test.json"]) { + const typecheck = run(root, path.resolve("node_modules/.bin/tsc"), ["--project", program]); + expect(typecheck.output, program).toBe(""); + expect(typecheck.status, program).toBe(0); + } + const lint = run(root, path.resolve("node_modules/.bin/eslint"), [ + `src/features/${FEATURE_ID}`, + `tests/features/${FEATURE_ID}`, + "--max-warnings=0", + ]); + expect(lint.output).toBe(""); + expect(lint.status).toBe(0); + const architecture = run(root, node, ["scripts/check-architecture.ts"]); + expect(architecture.status, architecture.output).toBe(0); + + const tests = run(root, node, [ + "scripts/run-vitest.ts", + "run", + `tests/features/${FEATURE_ID}`, + "--reporter=dot", + ]); + expect(tests.status, tests.output).toBe(0); + }, 300_000); +});