Merge pull request 'chore(layout): 정리 2단계로 샘플 역할을 옮기고 샘플을 지운다' (#12) from chore/layout-2-sample-removal into main

This commit was merged in pull request #12.
This commit is contained in:
2026-11-08 07:52:57 +00:00
180 changed files with 2796 additions and 7981 deletions
+13 -4
View File
@@ -86,7 +86,10 @@ const queryClient = createQueryClient();
const preview: Preview = {
decorators: [
(Story) => (
// A page story (`parameters.page`, the galleries) draws its own
// `.ui-page`, as a route page does inside the shell's `main`; a component
// story gets a padded page around it.
(Story, context) => (
<ApplicationProvider application={application}>
<QueryClientProvider client={queryClient}>
<MemoryRouter>
@@ -94,9 +97,15 @@ const preview: Preview = {
<ThemeProvider>
<SessionProvider>
<div id="portal-root" />
<main className="ui-page" style={{ padding: "1rem" }}>
<Story />
</main>
{context.parameters["page"] === true ? (
<main>
<Story />
</main>
) : (
<main className="ui-page" style={{ padding: "1rem" }}>
<Story />
</main>
)}
</SessionProvider>
</ThemeProvider>
</LocaleProvider>
+55
View File
@@ -11,6 +11,61 @@
- 괄호 안 ID는 리뷰 발견 ID다. `MMDD/NN-MM`으로 적는다. `MMDD`는 리뷰 폴더 `docs/reviews/YYYY-MM-DD-maturity-review/`의 월일이고, 근거와 재현 조건은 그 폴더의 영역 문서에 있다. 복사한 프로젝트가 README대로 `docs/reviews/`를 지웠다면 이 폴더와 `PRODUCT.md`는 원본 템플릿 repo에서 찾는다. 라운드마다 `NN-MM`을 새로 매기므로 같은 `14-02`라도 라운드가 다르면 다른 결함이다. `F-N`은 그 라운드 `FOLLOW-UP.md`의 ID다. 리뷰 README의 절은 `MMDD README N.N`으로 적고 다시 돌린 항목은 그 뒤에 `X2`처럼 번호를 붙인다. 영역 문서가 따로 매긴 ID는 `MMDD NN 영역 P-NN-NN`, 짝 백엔드 리뷰의 ID는 `백엔드 리뷰 MMDD/NN-MM`으로 적는다. `tests/unit/changelog-review-ids.test.ts`가 라운드 없는 ID와 이 꼴을 벗어난 참조를 막는다.
- 0.2.0의 커밋 해시는 브랜치 `fix/maturity-review-2026-09-25`에서 만들었고, `main`에서도 같은 해시로 찾을 수 있다(2026-11-03에 52개 모두 확인). 그 뒤 절은 절 머리에 범위(기준 커밋과 브랜치)를 적고, 그 절의 해시는 모두 그 범위에 있다. 통합에서 해시를 다시 쓴 뒤(fixup 접기, rebase)에는 절의 해시와 범위 커밋 본문의 해시를 `git merge-base --is-ancestor <해시> <브랜치 끝>`으로 하나씩 대조하고, 결과를 그 라운드 리뷰 README의 조치 절에 적는다. 1105 통합은 이 대조를 하지 않아, 올린 커밋 `287dc6f`의 본문이 다시 짓기 전 해시 둘을 가리킨다. 맞는 해시는 그 라운드 리뷰 README의 D7 행에 있다 (1106/14-02, 1105 README 16.2). 0.2.0의 커밋 제목은 라운드 없이 ID만 적었다(`git log --grep '03-03'`).
## 미출시 — `48c7695b` → 정리 단계
2026-11-07 소유자가 지시한 저장소 정리다(design-docs `repo-structure/04-frontend-layout.md` 9.2절, 결정은 `repo-structure/README.md` 3.4절). 범위는 `main` `48c7695b`(PR #9 병합) 다음부터다. 1단계(PR #11, `85f941c4`~`121e1125`, `main` `f33e4778`에 합침)와 2단계(브랜치 `chore/layout-2-sample-removal`, `c7e80f2f`부터 브랜치 끝까지)를 담는다. 3단계(합치기)는 아직 없다. 기준점 `48c7695b`를 빼면 이 절의 해시는 모두 이 범위에 있다.
### 먼저 할 일 (BREAKING)
아래 절의 "먼저 할 일"을 마친 뒤 순서대로 한다. 단계 끝의 괄호는 아래 표의 근거 커밋이다. 두 다운스트림 코드에 적용해 게이트를 돌려 보지는 않았다(알려진 제한).
#### 옮기기 전
- 템플릿은 참조 기능(`src/features/reference-feature/`, context `src/contexts/reference-context/`)과 예제 화면(`src/features/platform-examples-feature/`, context `src/contexts/platform-examples-context/`)을 지웠다. 받으면 템플릿 쪽 파일의 삭제가 함께 온다.
- 자기 프로젝트가 그 폴더를 고쳐 남겨 두었는지 본다: `git log --oneline <마지막 동기화 기준>..HEAD -- src/features/reference-feature tests/features/reference-feature src/features/platform-examples-feature`. 고친 파일은 병합에서 수정/삭제 충돌이 된다.
#### 옮기는 법
1. **샘플 사본을 쓰지 않으면 지운다.** 충돌한 파일은 삭제 쪽을 고른다(`git rm`). 함께 지울 것: `tests/features/reference-feature/`, `tests/features/platform-examples-feature/`, `tests/e2e/reference-form.spec.ts`·`reference-route.spec.ts`·`reference-save.spec.ts`, 수동 접근성 기록 7개(`artifacts/tests/a11y-manual/REFERENCE_RESOURCE_{LIST,DETAIL,FORM,STATUS}.md`, `EXAMPLES_{UI,STATES,AUTH}.md`), 런타임 프로필 4개와 `public/config.json`의 `FEATURE_OVERRIDES."reference-feature"`, `package.json`의 `test:reference-feature`. 그다음 `corepack pnpm generate:feature-index`, `node scripts/write-dev-release-manifest.ts`를 돈다 (`e3c8db48`)
2. **샘플 사본을 남겨 쓰는 프로젝트(tech-log의 참조 기능 12파일 등)는 자기 기능으로 옮긴다.** 남길 파일이 기대던 템플릿 쪽 파일(위 1단계 목록, 지운 테스트, `TEMPLATE_FIXTURE` 출처)은 다시 생기지 않는다. 계약 기여의 출처를 `EXTERNAL_PACKAGE`로 바꾸지 않았으면 계약 조립이 `<id>: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to <fixture owner> only`로 거부한다. 지울 예정이면 `scripts/lib/removable-template-features.ts`에 적는다. 그러면 `test:sample-removal`(FE-GATE-020)이 그 기능을 지운 사본에서 게이트를 돌고, 문서는 그 경로를 지운 뒤에도 통과한다 (`e3c8db48`)
3. **레지스트리 기준선을 다시 승인한다.** 템플릿 기준선은 샘플의 라우트·operation·스키마·무효화 행을 뺀 것이다. 자기 기준선을 쓰는 프로젝트는 병합 뒤 자기 행으로 다시 받는다: `REGISTRY_BASELINE_OWNER=<담당> REGISTRY_BASELINE_REASON="<이유>" corepack pnpm update:registry-baseline`. 행을 빼는 것은 breaking이라 승인 없이 `check:registries`가 `breaking change missing evidence:`로 실패한다 (`e3c8db48`)
4. **CI 계약 기준선과 workflow를 자기 값으로 다시 기록한 프로젝트는 다시 기록한다.** FE-GATE-007에서 `test:reference-feature` 명령과 그 산출물이, FE-GATE-009·028에서 지운 라우트의 수동 접근성 기록 산출물 4개가 빠졌다. `CI_CONTRACT_BASELINE_OWNER=<팀> CI_CONTRACT_BASELINE_REASON=<이유> corepack pnpm update:ci-contract-baseline`, 그다음 `corepack pnpm generate:ci-workflow` (`e3c8db48`)
5. **초기 JS 기록을 다시 쓴다.** `config/scale/feature-shape-ceilings.json`의 `initialJavascript`에 `firstFeatureGzipBytes`가 더해졌고, 측정은 참조 기능 대신 생성 기능을 복사해 잰다. `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. 다시 쓰지 않으면 `test:unit`이 기록과 빌드가 다르다며 실패한다 (`b2042de9`)
6. **`src/features/` 아래에 기능이 아닌 폴더를 두었으면 밖으로 옮긴다.** 생성기는 `NOT_A_FEATURE` 표식을 더 읽지 않는다. 선언 없는 폴더는 `src/features/<dir> has no feature-module.ts; add one, or keep code that is no feature outside src/features`로 실패한다. 템플릿의 local-draft 샘플은 `tests/fixtures/indexeddb-consumer/`로 옮겼다 (`b72cd7d4`)
#### 옮긴 뒤 확인
1. 로컬 merge 게이트 14개를 돈다. 이 절 때문에 먼저 볼 것: `check:registries`(3단계), `check:ci`(4단계), `test:unit`(5단계), `generate:feature-index`(6단계), `verify:documentation`(지운 샘플 경로를 적은 자기 문서), `test:sample-removal`(인자 없이 돌면 목록이 빈 템플릿에서는 `SKIP`을 출력한다).
2. 시각 골든: 갤러리 두 장(`design-system-gallery-dark`, `state-surfaces-light`)은 이제 Storybook 정적 빌드의 story를 찍는다. 자기 골든을 다시 찍은 프로젝트는 `corepack pnpm test:visual:update`로 그 둘을 다시 찍는다.
3. `/examples/ui`·`/examples/states`·`/examples/auth`를 열던 자기 e2e는 플랫폼 라우트나 자기 화면으로 옮긴다. 템플릿의 그런 spec은 옮겼다(아래 표).
### 보안·계약 변경
| 표시 | 변경 | 영향 경로 | 커밋 |
|---|---|---|---|
| [계약] **BREAKING** | 참조 기능과 예제 화면(`/examples/ui`, `/examples/states`, `/examples/auth`)을 지웠다. 소유자 결정(2026-11-07): 샘플은 매뉴얼과 `create:feature`가 생겼으니 지운다. 샘플이 맡던 시험 대상은 먼저 옮겼다(아래 행들). 레지스트리 기준선과 CI 계약 기준선을 다시 승인했다. 위 "먼저 할 일" 1~4 | `src/features/`, `src/contexts/`, `tests/features/`, `config/contracts/registry-baseline.json`, `config/ci/`, `config/runtime/`, `public/` | `e3c8db48` |
| [계약] | `scripts/lib/removable-template-features.ts` 목록이 비었다. 장치는 남는다: 프로젝트가 자기 샘플을 적으면 `test:sample-removal`(인자 없음, FE-GATE-020)이 하나씩 지워 게이트를 돈다. 목록이 비면 `sample removal: SKIP`을 출력하고 보고서에 건너뛴 사례 하나를 남긴다. `--feature=<id>`의 보고서는 늘 `artifacts/tests/feature-removal-<id>.xml`이다 | `scripts/test-sample-removal.ts`, `scripts/lib/removable-template-features.ts` | `e3c8db48` |
| [계약] | 갤러리를 Storybook story로 옮겼다(`src/presentation/design-system/galleries.stories.tsx`). visual 골든 두 장이 Storybook 정적 빌드를 찍는다. visual 설정이 두 번째 web server(정적 workshop, 포트 변수 `TEST_VISUAL_WORKSHOP_PORT`)를 띄운다. 디자인 토큰 색 하나(`--color-action`)를 바꾸면 새 골든이 어두운 쪽 42,313px, 밝은 쪽 22,359px 차이로 실패하는 것을 확인했다. 옛 골든도 같은 변이를 같은 크기로 잡았다. 갤러리의 브라우저 상호작용 검사는 `tests/storybook/galleries.spec.ts`로 옮겼다. 위 "옮긴 뒤 확인" 2 | `.storybook/preview.tsx`, `playwright.visual.config.ts`, `tests/visual/`, `tests/storybook/`, `scripts/lib/storybook-static.ts` | `c7e80f2f` |
| [계약] | 기능 하나가 실제 브라우저에서 라우트·폼·저장까지 되는지는 `create:feature --with-create --keyed` 기능을 넣은 저장소 사본의 빌드가 맡는다(`tests/e2e/generated-feature.spec.ts`, `scripts/lib/generated-feature.ts`). 오래된 탭의 청크 복구 시험도 그 기능의 목록 라우트를 쓴다. 생성기 출력이 바뀌면 FE-GATE-008이 잡는다 | `tests/e2e/`, `scripts/lib/generated-feature.ts` | `794a51a3` |
| [계약] | 규모 측정이 참조 기능 대신 생성 기능을 복사해 잰다(`planShapeFeatures`). `initialJavascript`에 `firstFeatureGzipBytes`(기능이 없는 템플릿에 첫 기능을 더할 때의 비용)가 생겼고, context 비용은 둘째 기능을 새 context에 둘 때와 같은 context에 둘 때의 차이다. 기록: 템플릿 194,354 B·17파일, 첫 기능 6,327 B, 기능 하나 539 B, context 하나 4 B. 성장 기준선(0·25·100개)도 다시 쟀다. 위 "먼저 할 일" 5 | `scripts/scale/measure-feature-shape-growth.ts`, `config/scale/` | `b2042de9`, `9c87cc4d` |
| [계약] | 생성기가 `NOT_A_FEATURE` 표식을 읽지 않는다. local-draft 샘플은 IndexedDB 소비자 시험 fixture(`tests/fixtures/indexeddb-consumer/`)가 됐다. 위 "먼저 할 일" 6 | `scripts/generate-product-feature-index.ts`, `recipes/frontend-capabilities/indexeddb-feature-capability.ts` | `b72cd7d4` |
| [계약] | 브라우저 soak(`scripts/scale/browser-soak.ts`, nightly 밖)이 기본으로 생성 기능을 넣은 빌드를 만들어 그 목록 라우트에서 실패하는 백엔드를 관찰한다. `--dist`를 주면 `--feature-route`도 준다. 결과 칸 이름이 `featureVisits`·`settledFeatureVisits`·`apiRequestsPerFeatureVisit`으로 바뀌었다 | `scripts/scale/browser-soak.ts` | `e3c8db48` |
### 그 밖의 수정
- 정리 1단계: 읽는 곳 없는 산출물 13개를 지우고 `artifacts/`를 폴더째 무시한다(`85f941c4`). 아무도 읽지 않는 `config/schemas/` JSON Schema 4개를 지웠다(`0805910c`). 루트 `tasks/`와 `.superpowers/` 기록을 `docs/history/`로 옮겼다(`429b8d88`). nginx 설정 예시를 지우고 호스트가 지킬 조건만 남겼다(`121e1125`).
- `/examples/ui`·`/examples/states`를 열던 e2e(반응형, 스크롤 복원, 타이포그래피, 건너뛰기 링크)는 홈과 `/examples/platform`으로 옮겼다 (`e7210c71`).
- 매뉴얼(`docs/manual/`)의 예제 칸은 생성기 출력 경로와 매뉴얼 안 코드 조각을 가리킨다. 코드 조각 일곱 개(problem details 백엔드의 분류와 매핑, 도메인 모델, 검색값 읽기, 실패 행동, 403 페이지 시험)는 `tests/unit/manual-code-blocks.test.ts`가 생성 기능 위에서 타입 검사·lint·아키텍처 검사·동작 시험을 돌린다. problem details 예는 소유자 결정대로 02 결정표 4절에 있다 (`01cac930`).
- 기능 스위치 시험(`tests/component/product-feature-switch.test.tsx`)과 홈 시작 링크의 스위치 시험은 시험 전용 fixture 기능으로 옮겼다 (`e3c8db48`).
- 라우트 런타임 음성 fixture(`tests/fixtures/typecheck/invalid-route-runtime.ts`)는 라우트 하나만 뺀다. 빠진 라우트 수에 따라 TS2739와 TS2740으로 갈리던 진단이 TS2741 하나가 됐고 FE-GATE-003의 기대 진단도 바꿨다. 라우트가 3개로 줄자 옛 기대(TS2740)가 어긋났다 (`e47a0ab2`).
### 알려진 제한
- 두 다운스트림에 시험 병합을 하지 않아 충돌 수를 모른다(S4 가정 F4).
- 성능 lab(FE-GATE-026)의 기능 라우트 측정(`featureRouteInteractionMs`)은 템플릿에 공개 기능 라우트가 없어 `measured: false`다. 제품 기능이 생기면 잰다.
- `TEMPLATE_FIXTURE` 출처와 `REFERENCE_EXTERNAL_BEARER` 별칭이 플랫폼 코드에 남았다. 쓰는 기능이 없다.
- visual 골든의 픽셀 비교는 색 허용치(`threshold` 0.2)를 넘지 않는 미세한 토큰 변경(예: 어두운 테마 `--color-danger` red-500 → red-600)을 잡지 못한다. 옛 골든도 같았다.
## 미출시 — `bbde570` → 브랜치 `fix/maturity-review-2026-11-06`
2026-11-06 성숙도 리뷰(`docs/reviews/2026-11-06-maturity-review/`) 조치다. 범위는 아래 절의 끝 `bbde570`(PR B, PR #7)부터 브랜치 `fix/maturity-review-2026-11-06`의 끝까지다. 리뷰 기록 커밋 `302d3a5` 위에 조치 브랜치 9개를 합치고, 합친 빌드로 초기 JS 기록을 다시 적었다(`5cfc3a6`). 기준점 `bbde570`을 빼면 이 절의 해시는 모두 이 범위에 있다. PR B는 아직 `main`에 없다. 아래 절을 아직 받지 않은 프로젝트는 아래 절부터 받는다.
+2 -2
View File
@@ -8,7 +8,7 @@ web
## Users
- **템플릿을 가져다 쓰는 개발자**: 이 템플릿으로 새 서비스를 빠르게 시작하는 사람입니다. 예제 화면(홈, 플랫폼 구성, UI 구성요소, 화면 상태, 인증 연동, Reference feature)은 이 사람이 실행 구조와 공통 동작을 확인하는 용도입니다.
- **템플릿을 가져다 쓰는 개발자**: 이 템플릿으로 새 서비스를 빠르게 시작하는 사람입니다. 기본 화면(홈, 플랫폼 구성)과 Storybook 갤러리(UI 구성요소, 화면 상태)는 이 사람이 실행 구조와 공통 동작을 확인하는 용도입니다.
- **파생 서비스의 최종 사용자**: 디자인 시스템(토큰, 프리미티브, 패턴, 레이아웃, 페이지 템플릿)은 이 템플릿으로 만든 서비스를 실제로 쓰는 사람을 기준으로 합니다.
## Product Purpose
@@ -30,7 +30,7 @@ web
- 하나의 디자인 시스템으로 세 종류의 서비스를 받칩니다. 업무용·관리 도구(대시보드, 어드민, 설정), 일반 사용자용 웹 서비스, 소개·랜딩 페이지입니다.
- 디자인 시스템 위치는 `src/presentation/design-system/`입니다. 토큰은 primitive → semantic → component 세 단계로 파생됩니다(`tokens/primitive.css`, `semantic.css`, `component.css`).
- 시각 회귀 골든이 `tests/visual/__snapshots__/`에 있습니다. 화면을 바꾸면 골든도 의도적으로 갱신해야 합니다.
- 참조 기능(`src/features/reference-feature/`)은 `test:sample-removal`로 지울 수 있습니다. 예제 화면 3개(`/examples/ui`, `states`, `auth`)도 기능 `platform-examples-feature`라서 같은 드릴(`test:sample-removal -- --feature=platform-examples-feature`)로 지울 수 있습니다. 플랫폼 구성 화면(`/examples/platform`)과 홈은 기본 구성이고 제거 드릴이 없습니다. 그래서 예제 화면 3개에만 넣은 디자인은 예제를 지운 파생 서비스에서 함께 사라지고, 홈과 플랫폼 구성 화면에 넣은 디자인은 남습니다.
- 템플릿에는 샘플 기능이 없습니다(참조 기능과 예제 화면은 2026-11-07에 지웠습니다). 기능은 `create:feature`로 만듭니다. 디자인 시스템 갤러리와 화면 상태 갤러리는 Storybook story(`src/presentation/design-system/galleries.stories.tsx`)이고 시각 회귀 골든의 대상입니다. 플랫폼 구성 화면(`/examples/platform`)과 홈은 기본 구성입니다. 그래서 갤러리와 홈, 플랫폼 구성 화면에 넣은 디자인은 파생 서비스에 남습니다.
- 어떤 서비스가 먼저 만들어질지, 서비스별 우선순위는 아직 정하지 않았습니다.
## Brand Commitments
+21 -20
View File
@@ -87,8 +87,8 @@ persistent `system` / `light` / `dark` theme selector, and a language selector.
The route list is `ROUTE_REGISTRY` (`src/features/installed-feature-contracts.ts`):
the platform routes of `src/contracts/routes.ts` plus the routes of every
installed feature, the removable reference feature included. The platform
overview page (`/examples/platform`) shows the composed list at runtime, so
installed feature. The template installs none: `corepack pnpm create:feature`
adds one (`docs/manual/`). The platform overview page (`/examples/platform`) shows the composed list at runtime, so
this README keeps no copy of it and adding a feature does not edit it.
`AUTH_MODE=demo` is credential-free and accepted only in local/development
@@ -105,9 +105,9 @@ design documents use; the next table maps them.
| Tier | What it covers | Status words |
| --- | --- | --- |
| Default | In the default build and covered by the merge gates: the application shell and example routes, the REST HTTP executor, TanStack Query server state, Local/Session Storage registries, cross-tab invalidation, runtime config profiles and the release manifest check, `AUTH_MODE=external` (`demo` only in local/development), the typed message catalog, and the removable reference feature. `dist/` is served by a static host ([`docs/architecture/static-delivery.md`](docs/architecture/static-delivery.md)) | `COMPOSED` |
| Default | In the default build and covered by the merge gates: the application shell and example routes, the REST HTTP executor, TanStack Query server state, Local/Session Storage registries, cross-tab invalidation, runtime config profiles and the release manifest check, `AUTH_MODE=external` (`demo` only in local/development), the typed message catalog, and `create:feature`, which writes a feature that passes the merge gates. `dist/` is served by a static host ([`docs/architecture/static-delivery.md`](docs/architecture/static-delivery.md)) | `COMPOSED` |
| Optional (recipe) | Not installed. A project copies one of the recipes in `config/recipes/frontend-capability-recipes.json` and narrows it ([`docs/architecture/optional-adapter-recipes.md`](docs/architecture/optional-adapter-recipes.md)). `realtime`, `offline-indexeddb`, `service-worker-pwa` and `file-transfer` also ship a tested reference runtime that the default build leaves out | `RECIPE_AVAILABLE`, `NOT_INSTALLED`, `AVAILABLE_NOT_COMPOSED` |
| Experimental | Designed and decided, but the runtime is missing or unfinished; finish it before building on it. GraphQL, gRPC-Web, Connect-Web and Protobuf adapters, Range resumable download, IndexedDB query persistence, the local preview decode-safety probe. `src/features/local-draft-feature` is an architecture sample, not installed | `DESIGNED_NOT_IMPLEMENTED` |
| Experimental | Designed and decided, but the runtime is missing or unfinished; finish it before building on it. GraphQL, gRPC-Web, Connect-Web and Protobuf adapters, Range resumable download, IndexedDB query persistence, the local preview decode-safety probe | `DESIGNED_NOT_IMPLEMENTED` |
| Not supported | Deliberately not selected, or browsers cannot guarantee it: SSR, app-managed background upload and download, directory selection, persistent file handles, product query persistence, exactly-once delivery between tabs | `NOT_SELECTED`, `PLATFORM_LIMITED` |
The rows come from
@@ -121,7 +121,7 @@ and
| `COMPOSED` | capability ledger, design documents | wired into the default production path | Default |
| `INSTALLED` | a project's own recipe catalog (step 10 of the recipe procedure) | the project added the recipe | Default, for that project |
| `RECIPE_AVAILABLE` | recipe catalog `status` | a recipe exists to copy; nothing is installed | Optional |
| `NOT_INSTALLED` | recipe catalog `defaultStatus`; a declared feature the build or `FEATURE_OVERRIDES` left out. A sample directory that is no feature at all carries a `src/features/<dir>/NOT_A_FEATURE` marker file instead | not part of the build | Optional (recipe) or Experimental (feature) |
| `NOT_INSTALLED` | recipe catalog `defaultStatus`; a declared feature the build or `FEATURE_OVERRIDES` left out | not part of the build | Optional (recipe) or Experimental (feature) |
| `AVAILABLE_NOT_COMPOSED` | capability ledger; recipe `referenceRuntime.status` | code and tests exist; the default build leaves it out | Optional |
| `DESIGNED_NOT_IMPLEMENTED` | capability ledger, design documents | design approved, runtime missing | Experimental |
| `NOT_SELECTED` | capability ledger, design documents | deliberately not chosen | Not supported |
@@ -173,12 +173,13 @@ Domain code lives inside each feature; there is no top-level domain folder.
See
`docs/architecture/frontend-application-foundation.md`,
`docs/architecture/overview.md`, `docs/architecture/layers.md`, and
`docs/architecture/starter-experience.md`. The removable vertical slice is
under `src/features/reference-feature`; its domain, application input, HTTP
binding, contracts, route runtime, and presentation own their contributions.
The central installed catalogs only aggregate selected contributions. The
generic starter routes continue to typecheck, test, and build after that
feature is removed.
`docs/architecture/starter-experience.md`. A feature is a vertical slice under
`src/features/<id>`; its domain, application input, HTTP binding, contracts,
route runtime, and presentation own their contributions. The central installed
catalogs only aggregate selected contributions. The template ships no feature
(its reference sample and example screens were deleted on 2026-11-07):
`corepack pnpm create:feature <id>` writes one, and the generic starter routes
typecheck, test, and build without any.
### Platform capability review
@@ -229,15 +230,15 @@ reads them, except the one file noted below
| `CLAUDE.md` | review instructions for the template repository itself; replace it with your own |
| `PRODUCT.md` | product context of the template itself (users, purpose, principles) for design tools; replace it with your product's |
The reference feature is not in this list: deleting its directory alone
leaves tests, policy entries and CI scripts behind that fail the gates.
`scripts/test-sample-removal.ts` removes it from a copy of
the repository and lists everything that has to go with it (its header comment,
and the files outside the feature's folders in
`scripts/lib/removable-template-features.ts`); do the same in your project and
run the gates. The documents keep naming the sample's paths: the documentation
check accepts them once `src/features/reference-feature/feature-module.ts` is
gone.
A feature is not in this list: deleting its directory alone leaves tests,
policy entries and CI scripts behind that fail the gates.
`corepack pnpm test:sample-removal -- --feature=<id>` removes it from a copy of
the repository and lists everything that has to go with it (the header comment
of `scripts/test-sample-removal.ts`); do the same in your project and run the
gates. A sample your project keeps for a while can be listed in
`scripts/lib/removable-template-features.ts`: the drill then removes it without
`--feature`, and the documentation check accepts its paths once its
`feature-module.ts` is gone.
## Verification
@@ -1,18 +0,0 @@
# EXAMPLES_AUTH accessibility review
Status: pending-manual-review
Route ID: EXAMPLES_AUTH
Release ID:
Reviewer:
Reviewed at:
Signature:
Attestation: pending
M1 Keyboard: pending
M2 Visible focus: pending
M3 Route focus: pending
M4 Modal focus: not-applicable (no modal on this route)
M5 Error association: not-applicable (no form error on this route)
M6 Color signal: pending
M7 Reduced motion: pending
Screen reader: pending
Notes: Review session state announcements and unavailable external-integration behavior.
@@ -1,18 +0,0 @@
# EXAMPLES_STATES accessibility review
Status: pending-manual-review
Route ID: EXAMPLES_STATES
Release ID:
Reviewer:
Reviewed at:
Signature:
Attestation: pending
M1 Keyboard: pending
M2 Visible focus: pending
M3 Route focus: pending
M4 Modal focus: not-applicable (no modal on this route)
M5 Error association: not-applicable (no form error on this route)
M6 Color signal: pending
M7 Reduced motion: pending
Screen reader: pending
Notes: Review loading, refresh, empty, error, authentication, forbidden, and not-found announcements.
@@ -1,18 +0,0 @@
# EXAMPLES_UI accessibility review
Status: pending-manual-review
Route ID: EXAMPLES_UI
Release ID:
Reviewer:
Reviewed at:
Signature:
Attestation: pending
M1 Keyboard: pending
M2 Visible focus: pending
M3 Route focus: pending
M4 Modal focus: pending
M5 Error association: pending
M6 Color signal: pending
M7 Reduced motion: pending
Screen reader: pending
Notes: Review form primitives, Menu/Tabs keyboard behavior, Toast announcements, Tooltip supplemental copy, text-field error association and modal focus containment/restoration.
@@ -1,18 +0,0 @@
# REFERENCE_RESOURCE_DETAIL accessibility review
Status: pending-manual-review
Route ID: REFERENCE_RESOURCE_DETAIL
Release ID:
Reviewer:
Reviewed at:
Signature:
Attestation: pending
M1 Keyboard: pending
M2 Visible focus: pending
M3 Route focus: pending
M4 Modal focus: not-applicable (no modal on this route)
M5 Error association: not-applicable (no form error on this route)
M6 Color signal: pending
M7 Reduced motion: pending
Screen reader: pending
Notes: Human review pending.
@@ -1,18 +0,0 @@
# REFERENCE_RESOURCE_FORM accessibility review
Status: pending-manual-review
Route ID: REFERENCE_RESOURCE_FORM
Release ID:
Reviewer:
Reviewed at:
Signature:
Attestation: pending
M1 Keyboard: pending
M2 Visible focus: pending
M3 Route focus: pending
M4 Modal focus: pending
M5 Error association: pending
M6 Color signal: pending
M7 Reduced motion: pending
Screen reader: pending
Notes: Human review pending.
@@ -1,18 +0,0 @@
# REFERENCE_RESOURCE_LIST accessibility review
Status: pending-manual-review
Route ID: REFERENCE_RESOURCE_LIST
Release ID:
Reviewer:
Reviewed at:
Signature:
Attestation: pending
M1 Keyboard: pending
M2 Visible focus: pending
M3 Route focus: pending
M4 Modal focus: not-applicable (no modal on this route)
M5 Error association: not-applicable (no form error on this route)
M6 Color signal: pending
M7 Reduced motion: pending
Screen reader: pending
Notes: Human review pending.
@@ -1,18 +0,0 @@
# REFERENCE_RESOURCE_STATUS accessibility review
Status: pending-manual-review
Route ID: REFERENCE_RESOURCE_STATUS
Release ID:
Reviewer:
Reviewed at:
Signature:
Attestation: pending
M1 Keyboard: pending
M2 Visible focus: pending
M3 Route focus: pending
M4 Modal focus: not-applicable (no modal on this route)
M5 Error association: not-applicable (no form error on this route)
M6 Color signal: pending
M7 Reduced motion: pending
Screen reader: pending
Notes: Human review pending.
+5 -5
View File
@@ -1,11 +1,11 @@
{
"schemaVersion": 1,
"owner": "DongHyeonka",
"reason": "1106/13-01: FE-GATE-027 runs the advisory scan before the release admission",
"reason": "2026-11-07 소유자 결정: 템플릿 샘플 삭제. 참조 기능 시험 명령과 그 산출물, 지운 라우트의 수동 a11y 기록 산출물 4개를 뺀다",
"gates": 27,
"commands": 100,
"commandReferences": 104,
"artifacts": 110,
"commands": 99,
"commandReferences": 103,
"artifacts": 105,
"stages": 5,
"gateShapeSha256": "7f6f3d975c62c022d6a6f8b5f39562f73de9ca0f22aa3d086ac28959e50fa93e"
"gateShapeSha256": "df584fba26f8448c6a77638351c6906ed91869da82e20f12ac71ea7b2037c989"
}
+1 -45
View File
@@ -144,7 +144,7 @@
"script": "check:types:fixture:route-runtime",
"expect": "fail",
"expectedExitCode": 1,
"expectedDiagnosticId": "error TS2740:"
"expectedDiagnosticId": "error TS2741:"
},
{
"id": "check-types-fixture-page-action",
@@ -238,11 +238,6 @@
"script": "test:http-scenario-evidence",
"expect": "pass"
},
{
"id": "test-reference-feature",
"script": "test:reference-feature",
"expect": "pass"
},
{
"id": "test-recipes",
"script": "test:recipes",
@@ -1028,15 +1023,6 @@
"test-http-scenario-evidence"
]
},
{
"id": "artifact-artifacts-tests-reference-feature-xml",
"path": "artifacts/tests/reference-feature.xml",
"schemaId": "junit",
"production": "command-generated",
"producerCommandIds": [
"test-reference-feature"
]
},
{
"id": "artifact-artifacts-tests-optional-recipes-xml",
"path": "artifacts/tests/optional-recipes.xml",
@@ -1163,30 +1149,6 @@
"schemaId": "markdown",
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-UI-md",
"path": "artifacts/tests/a11y-manual/EXAMPLES_UI.md",
"schemaId": "markdown",
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-STATES-md",
"path": "artifacts/tests/a11y-manual/EXAMPLES_STATES.md",
"schemaId": "markdown",
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-EXAMPLES-AUTH-md",
"path": "artifacts/tests/a11y-manual/EXAMPLES_AUTH.md",
"schemaId": "markdown",
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-REFERENCE-RESOURCE-LIST-md",
"path": "artifacts/tests/a11y-manual/REFERENCE_RESOURCE_LIST.md",
"schemaId": "markdown",
"production": "source-controlled"
},
{
"id": "artifact-artifacts-tests-a11y-manual-NOT-FOUND-md",
"path": "artifacts/tests/a11y-manual/NOT_FOUND.md",
@@ -1875,7 +1837,6 @@
"commandIds": [
"test-integration",
"test-http-scenario-evidence",
"test-reference-feature",
"test-recipes"
],
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-007-txt",
@@ -1884,7 +1845,6 @@
"artifact-artifacts-tests-http-scenario-executions-json",
"artifact-artifacts-quality-http-scenario-evidence-json",
"artifact-artifacts-quality-http-scenario-evidence-fixture-json",
"artifact-artifacts-tests-reference-feature-xml",
"artifact-artifacts-tests-optional-recipes-xml"
],
"retentionClassId": "merge-cycle"
@@ -2227,10 +2187,6 @@
"logArtifactId": "artifact-artifacts-quality-gates-FE-GATE-028-txt",
"evidenceArtifactIds": [
"artifact-artifacts-tests-a11y-manual-APP-HOME-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-UI-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-STATES-md",
"artifact-artifacts-tests-a11y-manual-EXAMPLES-AUTH-md",
"artifact-artifacts-tests-a11y-manual-REFERENCE-RESOURCE-LIST-md",
"artifact-artifacts-tests-a11y-manual-NOT-FOUND-md",
"artifact-artifacts-tests-a11y-manual-report-json"
],
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"snapshotDigest": "319a798ca3c9a87d7e2943177d952b13941622f4faec23c28f36024196a9e91d",
"snapshotDigest": "2430864767622f21490feb7f0b6932f73b82c0062e4b3ec70fe2c3ef3ac76889",
"owner": "DongHyeonka",
"reason": "1103/16-04 FE-REG-API problemSchema가 FE-REG-SCHEMA api-problem 행을 참조한다",
"approvedAt": "2026-11-04T14:04:44.377Z"
"reason": "2026-11-07 소유자 결정: 템플릿 샘플 삭제(design-docs repo-structure/README.md 3.4절). 참조 기능과 예제 화면의 라우트·operation·스키마·무효화 행을 지운다",
"approvedAt": "2026-11-08T02:26:50.112Z"
}
+24 -318
View File
@@ -5,7 +5,7 @@
"registryId": "FE-REG-ROUTE",
"owner": "feature-frontend-routing-release-recovery-runtime",
"source": "src/features/installed-feature-contracts.ts",
"rowCount": 10,
"rowCount": 3,
"contract": {
"requiredFields": [
"routeId",
@@ -93,19 +93,6 @@
"searchSchema": null,
"title": "시작"
},
"EXAMPLES_AUTH": {
"access": "public",
"chunkId": "route-examples-auth",
"errorSurface": "route-boundary",
"loadingSurface": "example-page",
"navigationLabel": "인증 연동",
"navigationOrder": 40,
"paramsSchema": null,
"path": "/examples/auth",
"routeId": "EXAMPLES_AUTH",
"searchSchema": null,
"title": "인증 연동"
},
"EXAMPLES_PLATFORM": {
"access": "public",
"chunkId": "route-examples-platform",
@@ -119,32 +106,6 @@
"searchSchema": null,
"title": "플랫폼 구성"
},
"EXAMPLES_STATES": {
"access": "public",
"chunkId": "route-examples-states",
"errorSurface": "route-boundary",
"loadingSurface": "example-page",
"navigationLabel": "화면 상태",
"navigationOrder": 30,
"paramsSchema": null,
"path": "/examples/states",
"routeId": "EXAMPLES_STATES",
"searchSchema": null,
"title": "화면 상태"
},
"EXAMPLES_UI": {
"access": "public",
"chunkId": "route-examples-ui",
"errorSurface": "route-boundary",
"loadingSurface": "example-page",
"navigationLabel": "UI 구성요소",
"navigationOrder": 20,
"paramsSchema": null,
"path": "/examples/ui",
"routeId": "EXAMPLES_UI",
"searchSchema": null,
"title": "UI 구성요소"
},
"NOT_FOUND": {
"access": "public",
"chunkId": "route-not-found",
@@ -157,58 +118,6 @@
"routeId": "NOT_FOUND",
"searchSchema": null,
"title": "페이지를 찾을 수 없음"
},
"REFERENCE_RESOURCE_DETAIL": {
"access": "session-required",
"chunkId": "route-reference-resource-detail",
"errorSurface": "feature-boundary",
"loadingSurface": "reference-resource-detail",
"navigationLabel": null,
"navigationOrder": null,
"paramsSchema": "ReferenceResourceParams",
"path": "/examples/reference-resources/items/:resourceId",
"routeId": "REFERENCE_RESOURCE_DETAIL",
"searchSchema": null,
"title": "Reference detail"
},
"REFERENCE_RESOURCE_FORM": {
"access": "session-required",
"chunkId": "route-reference-resource-form",
"errorSurface": "feature-boundary",
"loadingSurface": "reference-resource-form",
"navigationLabel": null,
"navigationOrder": null,
"paramsSchema": null,
"path": "/examples/reference-resources/new",
"routeId": "REFERENCE_RESOURCE_FORM",
"searchSchema": null,
"title": "Reference form"
},
"REFERENCE_RESOURCE_LIST": {
"access": "session-required",
"chunkId": "route-reference-resources",
"errorSurface": "feature-boundary",
"loadingSurface": "reference-resource-list",
"navigationLabel": "Reference feature",
"navigationOrder": 50,
"paramsSchema": null,
"path": "/examples/reference-resources",
"routeId": "REFERENCE_RESOURCE_LIST",
"searchSchema": "ReferenceResourceListQuery",
"title": "Reference feature"
},
"REFERENCE_RESOURCE_STATUS": {
"access": "session-required",
"chunkId": "route-reference-resource-status",
"errorSurface": "feature-boundary",
"loadingSurface": "reference-resource-status",
"navigationLabel": null,
"navigationOrder": null,
"paramsSchema": null,
"path": "/examples/reference-resources/status",
"routeId": "REFERENCE_RESOURCE_STATUS",
"searchSchema": null,
"title": "Reference status"
}
}
},
@@ -216,7 +125,7 @@
"registryId": "FE-REG-ROUTE-RUNTIME",
"owner": "feature-frontend-routing-release-recovery-runtime",
"source": "src/features/installed-feature-contracts.ts",
"rowCount": 10,
"rowCount": 3,
"contract": {
"requiredFields": [
"routeId",
@@ -267,59 +176,17 @@
"routeId": "APP_HOME",
"searchCodec": "none"
},
"EXAMPLES_AUTH": {
"moduleId": "auth-example-page",
"paramsCodec": "none",
"routeId": "EXAMPLES_AUTH",
"searchCodec": "none"
},
"EXAMPLES_PLATFORM": {
"moduleId": "platform-overview-page",
"paramsCodec": "none",
"routeId": "EXAMPLES_PLATFORM",
"searchCodec": "none"
},
"EXAMPLES_STATES": {
"moduleId": "state-gallery-page",
"paramsCodec": "none",
"routeId": "EXAMPLES_STATES",
"searchCodec": "none"
},
"EXAMPLES_UI": {
"moduleId": "ui-gallery-page",
"paramsCodec": "none",
"routeId": "EXAMPLES_UI",
"searchCodec": "none"
},
"NOT_FOUND": {
"moduleId": "not-found-page",
"paramsCodec": "NotFoundSplat",
"routeId": "NOT_FOUND",
"searchCodec": "none"
},
"REFERENCE_RESOURCE_DETAIL": {
"moduleId": "reference-resource-detail-page",
"paramsCodec": "ReferenceResourceParams",
"routeId": "REFERENCE_RESOURCE_DETAIL",
"searchCodec": "none"
},
"REFERENCE_RESOURCE_FORM": {
"moduleId": "reference-resource-form-page",
"paramsCodec": "none",
"routeId": "REFERENCE_RESOURCE_FORM",
"searchCodec": "none"
},
"REFERENCE_RESOURCE_LIST": {
"moduleId": "reference-resource-page",
"paramsCodec": "none",
"routeId": "REFERENCE_RESOURCE_LIST",
"searchCodec": "ReferenceResourceListQuery"
},
"REFERENCE_RESOURCE_STATUS": {
"moduleId": "reference-resource-status-page",
"paramsCodec": "none",
"routeId": "REFERENCE_RESOURCE_STATUS",
"searchCodec": "none"
}
}
},
@@ -327,7 +194,7 @@
"registryId": "FE-REG-API",
"owner": "feature-frontend-api-client-response-envelope-contract",
"source": "src/features/loaded-feature-runtimes.ts",
"rowCount": 3,
"rowCount": 0,
"contract": {
"requiredFields": [
"operationId",
@@ -442,113 +309,13 @@
"unvalidated"
]
},
"rows": {
"CREATE_REFERENCE_RESOURCE": {
"acceptedStatuses": [
200,
201
],
"authProfileId": "EXTERNAL_BEARER",
"commandEffect": {
"classifiesStatus": true
},
"commandRecovery": {
"mode": "IDEMPOTENCY_REPLAY",
"operationIdentityField": "idempotencyKey"
},
"emptyBodyStatuses": [],
"featureId": "reference-feature",
"method": "POST",
"operationId": "CREATE_REFERENCE_RESOURCE",
"path": "/api/reference-resources",
"problemSchema": "ReferenceProblem",
"requestBody": "JSON",
"requestByteLimit": 32768,
"requestSchema": "CreateReferenceResourceCommand",
"responseBody": "REQUIRED_JSON",
"responseByteLimit": 32768,
"responseEnvelope": "NONE",
"responseSchema": "ReferenceResourcePayload",
"retryBudget": 0,
"retrySemantics": "KEYED",
"totalDeadlineMs": 10000,
"traffic": {
"maxConcurrentRequests": 1,
"maxPhysicalRequests": 1,
"maxQueuedRequests": 0,
"maxRetries": 0
},
"unvalidated": []
},
"GET_REFERENCE_RESOURCE": {
"acceptedStatuses": [
200
],
"authProfileId": "EXTERNAL_BEARER",
"commandEffect": null,
"commandRecovery": null,
"emptyBodyStatuses": [],
"featureId": "reference-feature",
"method": "GET",
"operationId": "GET_REFERENCE_RESOURCE",
"path": "/api/reference-resources/{resourceId}",
"problemSchema": "ReferenceProblem",
"requestBody": "NONE",
"requestByteLimit": 0,
"requestSchema": "ReferenceResourceParams",
"responseBody": "REQUIRED_JSON",
"responseByteLimit": 32768,
"responseEnvelope": "NONE",
"responseSchema": "ReferenceResourcePayload",
"retryBudget": 2,
"retrySemantics": "SAFE",
"totalDeadlineMs": 10000,
"traffic": {
"maxConcurrentRequests": 1,
"maxPhysicalRequests": 3,
"maxQueuedRequests": 0,
"maxRetries": 2
},
"unvalidated": []
},
"LIST_REFERENCE_RESOURCES": {
"acceptedStatuses": [
200
],
"authProfileId": "EXTERNAL_BEARER",
"commandEffect": null,
"commandRecovery": null,
"emptyBodyStatuses": [],
"featureId": "reference-feature",
"method": "GET",
"operationId": "LIST_REFERENCE_RESOURCES",
"path": "/api/reference-resources",
"problemSchema": "ReferenceProblem",
"requestBody": "NONE",
"requestByteLimit": 0,
"requestSchema": "ReferenceResourceListQuery",
"responseBody": "REQUIRED_JSON",
"responseByteLimit": 262144,
"responseEnvelope": "NONE",
"responseSchema": "ReferenceResourceListPayload",
"retryBudget": 2,
"retrySemantics": "SAFE",
"totalDeadlineMs": 10000,
"traffic": {
"maxConcurrentRequests": 1,
"maxPhysicalRequests": 3,
"maxQueuedRequests": 0,
"maxRetries": 2
},
"unvalidated": []
}
}
"rows": {}
},
{
"registryId": "FE-REG-SCHEMA",
"owner": "feature-frontend-contract-schema-registry",
"source": "src/features/loaded-feature-runtimes.ts",
"rowCount": 8,
"rowCount": 2,
"contract": {
"requiredFields": [
"schemaId",
@@ -587,15 +354,6 @@
]
},
"rows": {
"CreateReferenceResourceCommand": {
"boundary": "api-request",
"direction": "REQUEST",
"owner": "feature-frontend-reference-feature-vertical-slice",
"runtime": "zod",
"schemaId": "CreateReferenceResourceCommand",
"schemaVersion": 1,
"unknownFieldPolicy": "REJECT_UNKNOWN"
},
"none": {
"boundary": "route-params",
"owner": "feature-frontend-routing-release-recovery-runtime",
@@ -607,51 +365,6 @@
"owner": "feature-frontend-routing-release-recovery-runtime",
"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",
"owner": "feature-frontend-reference-feature-vertical-slice",
"runtime": "zod",
"schemaId": "ReferenceResourceListPayload",
"schemaVersion": 1,
"unknownFieldPolicy": "STRIP_UNKNOWN"
},
"ReferenceResourceListQuery": {
"boundary": "route-search-api-request",
"direction": "REQUEST",
"owner": "feature-frontend-reference-feature-vertical-slice",
"runtime": "zod",
"schemaId": "ReferenceResourceListQuery",
"schemaVersion": 1,
"unknownFieldPolicy": "REJECT_UNKNOWN"
},
"ReferenceResourceParams": {
"boundary": "route-params",
"direction": "REQUEST",
"owner": "feature-frontend-reference-feature-vertical-slice",
"runtime": "zod",
"schemaId": "ReferenceResourceParams",
"schemaVersion": 1,
"unknownFieldPolicy": "REJECT_UNKNOWN"
},
"ReferenceResourcePayload": {
"boundary": "api-response",
"direction": "RESPONSE",
"owner": "feature-frontend-reference-feature-vertical-slice",
"runtime": "zod",
"schemaId": "ReferenceResourcePayload",
"schemaVersion": 1,
"unknownFieldPolicy": "STRIP_UNKNOWN"
}
}
},
@@ -814,7 +527,7 @@
"registryId": "FE-REG-STORAGE",
"owner": "feature-frontend-storage-registry-contract",
"source": "src/contracts/storage-keys.ts",
"rowCount": 7,
"rowCount": 8,
"contract": {
"requiredFields": [
"logicalName",
@@ -883,6 +596,19 @@
]
},
"rows": {
"AUTH_REDIRECT_TRANSACTION": {
"backend": "external",
"classification": "opaque-cache",
"logicalName": "AUTH_REDIRECT_TRANSACTION",
"migration": "discard",
"name": "oidc-pkce-transaction",
"physicalKey": "ca-frontend:auth:v1:oidc-pkce-transaction",
"quotaFallback": "no-persist",
"schemaVersion": 1,
"scope": "auth",
"ttl": "session",
"valueCodec": "none"
},
"AUTH_TOKEN": {
"backend": "forbidden",
"classification": "sensitive-forbidden",
@@ -1304,24 +1030,9 @@
},
"rows": {
"invalidation-graph": {
"edges": [
{
"namespace": {
"namespaceId": "reference-resource",
"namespaceVersion": 1
},
"topicId": "qinv.01k10f7m3w9p6r2c8v5n4x"
}
],
"namespaces": [
{
"namespaceId": "reference-resource",
"namespaceVersion": 1
}
],
"topics": [
"qinv.01k10f7m3w9p6r2c8v5n4x"
]
"edges": [],
"namespaces": [],
"topics": []
}
}
},
@@ -1329,7 +1040,7 @@
"registryId": "FE-REG-QUERY-INVALIDATION-TOPIC-VERSION",
"owner": "feature-frontend-server-state-caching-contract",
"source": "src/features/installed-feature-contracts.ts",
"rowCount": 1,
"rowCount": 0,
"contract": {
"requiredFields": [
"topicId",
@@ -1353,12 +1064,7 @@
"topicId"
]
},
"rows": {
"[\"qinv.01k10f7m3w9p6r2c8v5n4x\"]": {
"topicId": "qinv.01k10f7m3w9p6r2c8v5n4x",
"topicVersion": 1
}
}
"rows": {}
},
{
"registryId": "FE-REG-TELEMETRY",
+1 -3
View File
@@ -13,7 +13,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
+1 -3
View File
@@ -13,7 +13,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
+1 -3
View File
@@ -14,7 +14,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
+1 -3
View File
@@ -14,7 +14,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
+12 -11
View File
@@ -9,9 +9,9 @@
"axes": [
{
"axis": "Typecheck of one app",
"verified": "Linear, about 117k instantiations and 36 MB of tsc memory per feature, up to 100 features",
"condition": "Reference-shaped features, tsconfig.app.json, the host recorded in the baseline",
"notVerified": "200 features (one full context) and beyond; 4,000 (20 x 200) would need on the order of 150 GB by the same slope"
"verified": "Linear, about 101k instantiations and 31 MB of tsc memory per feature, up to 100 features",
"condition": "Copies of the feature create:feature writes with --with-create --keyed (2026-11-07; reference-sample copies before), tsconfig.app.json, the host recorded in the baseline",
"notVerified": "200 features (one full context) and beyond; 4,000 (20 x 200) would need on the order of 125 GB by the same slope"
},
{
"axis": "Production build",
@@ -21,27 +21,28 @@
},
{
"axis": "Initial JavaScript",
"verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes, and a copy adds no initial file. initialJavascript below is the current template build, what one more feature in an existing context adds (perFeatureGzipBytes) and what a new context adds (perContextGzipBytes); tests/unit/feature-shape-growth.test.ts measures them on every unit run, bounds a feature at 1 KiB and a context at 512 B, and fails when the record no longer matches the build. The 25- and 100-copy runs are in the baseline at its source commit (before 15-01: +3,922 B per copy)",
"verified": "15-01: only each feature's declaration (route table, messages, invalidation identities) loads at boot; its runtime half loads with its routes. initialJavascript below is the current template build, which has no feature; what the first feature adds once (firstFeatureGzipBytes: the code every feature shares joins the initial chunks); what one more feature in an existing context adds (perFeatureGzipBytes); and what a second context adds (perContextGzipBytes). tests/unit/feature-shape-growth.test.ts measures them on every unit run, bounds a feature at 1 KiB and a context at 512 B, and fails when the record no longer matches the build. The 25- and 100-copy runs are in the baseline at its source commit (before 15-01: +3,922 B per copy)",
"condition": "Same; the feature-declarations and feature-platform chunk groups in vite.config.ts",
"notVerified": "How many more features fit: the initial budget (config/performance/budgets.json) minus initialJavascript.gzipBytes, divided by perFeatureGzipBytes (plus perContextGzipBytes per new context). The platform itself takes most of the budget"
"notVerified": "How many features fit: the initial budget (config/performance/budgets.json) minus initialJavascript.gzipBytes and firstFeatureGzipBytes, divided by perFeatureGzipBytes (plus perContextGzipBytes per new context). The platform itself takes most of the budget"
},
{
"axis": "Lazy JavaScript",
"verified": "About 8.5 KB gzip and eight files per feature, every file far below the 120 KiB lazy-chunk budget",
"verified": "About 6.7 KB gzip and nine files per feature, every file far below the 120 KiB lazy-chunk budget",
"condition": "Same",
"notVerified": "Download cost of many lazy files"
},
{
"axis": "Routes",
"verified": "4 per feature, composed without conflict",
"verified": "3 per feature (list, detail, create), composed without conflict",
"condition": "Same",
"notVerified": "Router matching cost at runtime"
}
],
"initialJavascript": {
"gzipBytes": 204193,
"files": 27,
"perFeatureGzipBytes": 751,
"perContextGzipBytes": 245
"gzipBytes": 194354,
"files": 17,
"firstFeatureGzipBytes": 6327,
"perFeatureGzipBytes": 539,
"perContextGzipBytes": 4
}
}
+116 -119
View File
@@ -1,216 +1,213 @@
{
"schemaVersion": 1,
"measuredAt": "2026-11-01T14:29:42.148Z",
"measuredAt": "2026-11-08T05:02:36.163Z",
"command": "node scripts/scale/measure-feature-shape-growth.ts --sizes=0,25,100 --repeats=2",
"environment": {
"node": "24.14.0",
"platform": "linux",
"arch": "x64",
"cpuModel": "Intel(R) Core(TM) Ultra 7 155H",
"logicalCpus": 22,
"availableParallelism": 22,
"cpuModel": "Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz",
"logicalCpus": 12,
"availableParallelism": 12,
"typescript": "Version 7.0.2",
"vite": "vite/8.1.5 linux-x64 node-v24.14.0"
"vite": "vite/8.1.6 linux-x64 node-v24.14.0"
},
"source": {
"commit": "373b27b09c7c24c50ea81fca0238138f6b8189a8",
"modifiedPaths": [
"scripts/scale/measure-feature-shape-growth.ts",
"tests/unit/feature-shape-growth.test.ts"
]
"commit": "e3c8db48ae0000ab63c15d2ee09a672140c408ca",
"modifiedPaths": []
},
"sourceFeature": "src/features/reference-feature",
"sourceFeature": "create:feature <id> --with-create --keyed",
"runs": [
{
"repeat": 1,
"addedFeatures": 0,
"routes": 10,
"routes": 3,
"tsc": {
"passed": true,
"firstError": null,
"files": 844,
"types": 287435,
"symbols": 794593,
"instantiations": 721205,
"memoryKb": 521732,
"wallMs": 811
"files": 868,
"types": 270953,
"symbols": 764824,
"instantiations": 660922,
"memoryKb": 507503,
"wallMs": 1149
},
"build": {
"wallMs": 428,
"initialJavascriptFiles": 16,
"initialJavascriptGzipBytes": 203816,
"lazyJavascriptFiles": 17,
"lazyJavascriptGzipBytes": 28413
"wallMs": 471,
"initialJavascriptFiles": 17,
"initialJavascriptGzipBytes": 194354,
"lazyJavascriptFiles": 6,
"lazyJavascriptGzipBytes": 8881
},
"loadBefore": [
2.97,
7.82,
8.57
2.41,
12.33,
13.56
],
"loadAfter": [
2.97,
7.82,
8.57
2.41,
12.33,
13.56
]
},
{
"repeat": 2,
"addedFeatures": 0,
"routes": 10,
"routes": 3,
"tsc": {
"passed": true,
"firstError": null,
"files": 844,
"types": 287435,
"symbols": 794593,
"instantiations": 721205,
"memoryKb": 521779,
"wallMs": 789
"files": 868,
"types": 270953,
"symbols": 764824,
"instantiations": 660922,
"memoryKb": 507208,
"wallMs": 1115
},
"build": {
"wallMs": 400,
"initialJavascriptFiles": 16,
"initialJavascriptGzipBytes": 203816,
"lazyJavascriptFiles": 17,
"lazyJavascriptGzipBytes": 28413
"wallMs": 464,
"initialJavascriptFiles": 17,
"initialJavascriptGzipBytes": 194354,
"lazyJavascriptFiles": 6,
"lazyJavascriptGzipBytes": 8881
},
"loadBefore": [
2.97,
7.82,
8.57
2.41,
12.33,
13.56
],
"loadAfter": [
2.97,
7.82,
8.57
2.41,
12.33,
13.56
]
},
{
"repeat": 1,
"addedFeatures": 25,
"routes": 110,
"routes": 78,
"tsc": {
"passed": true,
"firstError": null,
"files": 1395,
"types": 1062647,
"symbols": 2897351,
"instantiations": 3645516,
"memoryKb": 1438408,
"wallMs": 2362
"files": 1419,
"types": 924555,
"symbols": 2579662,
"instantiations": 3222688,
"memoryKb": 1300524,
"wallMs": 3027
},
"build": {
"wallMs": 556,
"initialJavascriptFiles": 16,
"initialJavascriptGzipBytes": 219508,
"lazyJavascriptFiles": 218,
"lazyJavascriptGzipBytes": 239901
"wallMs": 596,
"initialJavascriptFiles": 21,
"initialJavascriptGzipBytes": 211739,
"lazyJavascriptFiles": 235,
"lazyJavascriptGzipBytes": 185846
},
"loadBefore": [
3.13,
7.78,
8.55
2.41,
12.33,
13.56
],
"loadAfter": [
3.13,
7.78,
8.55
2.46,
12.18,
13.5
]
},
{
"repeat": 2,
"addedFeatures": 25,
"routes": 110,
"routes": 78,
"tsc": {
"passed": true,
"firstError": null,
"files": 1395,
"types": 1062647,
"symbols": 2897351,
"instantiations": 3645516,
"memoryKb": 1438614,
"wallMs": 2453
"files": 1419,
"types": 924555,
"symbols": 2579662,
"instantiations": 3222688,
"memoryKb": 1300579,
"wallMs": 2838
},
"build": {
"wallMs": 546,
"initialJavascriptFiles": 16,
"initialJavascriptGzipBytes": 219508,
"lazyJavascriptFiles": 218,
"lazyJavascriptGzipBytes": 239901
"wallMs": 607,
"initialJavascriptFiles": 21,
"initialJavascriptGzipBytes": 211739,
"lazyJavascriptFiles": 235,
"lazyJavascriptGzipBytes": 185846
},
"loadBefore": [
3.13,
7.78,
8.55
2.46,
12.18,
13.5
],
"loadAfter": [
3.2,
7.71,
8.52
2.58,
12.04,
13.45
]
},
{
"repeat": 1,
"addedFeatures": 100,
"routes": 410,
"routes": 303,
"tsc": {
"passed": true,
"firstError": null,
"files": 3045,
"types": 3373621,
"symbols": 9115707,
"instantiations": 12392128,
"memoryKb": 4264554,
"wallMs": 8403
"files": 3069,
"types": 2842959,
"symbols": 7904204,
"instantiations": 10789965,
"memoryKb": 3698826,
"wallMs": 9049
},
"build": {
"wallMs": 944,
"initialJavascriptFiles": 16,
"initialJavascriptGzipBytes": 264841,
"lazyJavascriptFiles": 818,
"lazyJavascriptGzipBytes": 873479
"wallMs": 1021,
"initialJavascriptFiles": 21,
"initialJavascriptGzipBytes": 245687,
"lazyJavascriptFiles": 910,
"lazyJavascriptGzipBytes": 677352
},
"loadBefore": [
3.2,
7.71,
8.52
2.58,
12.04,
13.45
],
"loadAfter": [
6.72,
8.32,
8.71
2.95,
11.81,
13.36
]
},
{
"repeat": 2,
"addedFeatures": 100,
"routes": 410,
"routes": 303,
"tsc": {
"passed": true,
"firstError": null,
"files": 3045,
"types": 3373621,
"symbols": 9115707,
"instantiations": 12392128,
"memoryKb": 4263823,
"wallMs": 9717
"files": 3069,
"types": 2842959,
"symbols": 7904204,
"instantiations": 10789965,
"memoryKb": 3700296,
"wallMs": 9140
},
"build": {
"wallMs": 933,
"initialJavascriptFiles": 16,
"initialJavascriptGzipBytes": 264841,
"lazyJavascriptFiles": 818,
"lazyJavascriptGzipBytes": 873479
"wallMs": 1028,
"initialJavascriptFiles": 21,
"initialJavascriptGzipBytes": 245687,
"lazyJavascriptFiles": 910,
"lazyJavascriptGzipBytes": 677352
},
"loadBefore": [
6.72,
8.32,
8.71
2.95,
11.81,
13.36
],
"loadAfter": [
6.3,
8.17,
8.66
3.9,
11.72,
13.31
]
}
]
-11
View File
@@ -129,16 +129,6 @@
"branches": 58
}
},
{
"path": "src/features/reference-feature/adapters/reference-http-gateway.ts",
"owner": "reference-feature",
"minimum": {
"lines": 90,
"statements": 90,
"functions": 90,
"branches": 90
}
},
{
"path": "src/presentation/adapters/query/application-query.ts",
"owner": "presentation-runtime",
@@ -193,7 +183,6 @@
"src/bootstrap/load-release-manifest.ts",
"src/bootstrap/read-bounded-boot-json.ts",
"src/contracts/diagnostics.ts",
"src/features/reference-feature/adapters/reference-http-gateway.ts",
"src/presentation/adapters/query/application-query.ts",
"src/adapters/http/http-contract-bridge.ts",
"src/adapters/http/http-retry-lifecycle.ts",
+3 -3
View File
@@ -51,9 +51,9 @@ checkout이 없거나 그 커밋이 없으면 실패 대신 확인하지 못한
지난 상태를 적는 문서라 빼고, git이 무시하는 생성 산출물과 복사한 프로젝트가 지운 작업 이력은
없어도 된다. 설명·수치가 코드와 맞는지는 검사하지 않는다. 규칙과 예외의 정본은
`scripts/verify-documentation-readiness.ts`다.
복사한 프로젝트가 지울 수 있는 템플릿 기능(참조 기능, 예제 화면. 목록은
`scripts/lib/removable-template-features.ts`)의 경로와 script는 그 기능이 설치돼 있을 때
(`src/features/<id>/feature-module.ts`가 있을 때) 검사하고, 지운 뒤에는 없어도 된다.
프로젝트가 지울 예정인 샘플 기능(목록은 `scripts/lib/removable-template-features.ts`, 템플릿은
비어 있다)의 경로와 script는 그 기능이 설치돼 있을 때(`src/features/<id>/feature-module.ts`가
있을 때) 검사하고, 지운 뒤에는 없어도 된다.
게이트가 직접 읽는 파일이라 지우거나 옮기면 게이트가 실패한다.
+6 -6
View File
@@ -57,8 +57,8 @@ The reviewer must verify:
- M7: non-essential motion is suppressed with reduced-motion preference
- Screen reader: headings, live regions, errors, and actions are announced once
`EXAMPLES_UI` requires real M4 modal and M5 field-error review; those items must
not be marked not-applicable on that route. Passing automated evidence means
A route with a form or a dialog requires real M4 modal and M5 field-error
review; those items must not be marked not-applicable on that route. Passing automated evidence means
only that tested pages had no critical or serious axe findings under the
recorded Chromium, Firefox, and WebKit runs.
@@ -78,7 +78,7 @@ What the automated run scans:
route's `paramsSchema` is the input of such a read, the report expects that
record from the descriptors alone and fails without it
(`scripts/write-a11y-report.ts`).
- The reference sample's list in its success, empty and error states, its
detail, its form with submit errors and its status page, each after that
state is on screen (`tests/e2e/reference-form.spec.ts`, removed with the
sample).
- The list of the feature `create:feature` writes, in its success, empty and
error states, its detail and its form with submit errors, each after that
state is on screen (`tests/e2e/generated-feature.spec.ts`, on a build with
that feature). A product's own features get the route scan above.
@@ -124,36 +124,22 @@ runtime config의 version 문자열 일치만 compatibility 증거로 사용하
artifact digest가 없는 동안에는 실제 staging conformance fixture와 수동 승인
evidence가 필요하다.
## 4. 현재 reference REST 계약
## 4. 현재 REST 계약
현재 frontend에 실제 조립된 operation은 다음 세 개다.
템플릿에는 조립된 기능 operation이 없다. 참조 샘플(`LIST_REFERENCE_RESOURCES` 등
problem details 모양의 세 operation)은 2026-11-07에 지웠다. 기능의 operation은
`corepack pnpm create:feature <id>`가 만든다. 짝 백엔드 `new-feature.sh`와 같은 경로
규칙이다(`docs/manual/reference/create-feature.md`).
| operation | request | success |
| --- | --- | --- |
| `LIST_REFERENCE_RESOURCES` | `GET /api/reference-resources?cursor&limit&tags` | `200 application/json` |
| `GET_REFERENCE_RESOURCE` | `GET /api/reference-resources/{resourceId}` | `200 application/json` |
| `CREATE_REFERENCE_RESOURCE` | `POST /api/reference-resources` | `200` 또는 `201 application/json` |
| `<BASE>_LIST_ITEMS` | `GET /<plural>` | `200`, Envelope 안의 항목 배열과 `meta.page` |
| `<BASE>_GET_ITEM` (`--with-create`) | `GET /<plural>/{<camel>Id}` | `200`, Envelope 안의 항목 |
| `<BASE>_CREATE_ITEM` (`--with-create`) | `POST /<plural>` | `201`, Envelope 안의 항목 |
현재 list payload는 `ReferenceResource[]`다. `cursor` 입력이 존재하더라도
`CursorPage` 출력 계약은 아직 아니다. backend가 같은 operation에서 배열을
page object로 조용히 바꾸면 schema mismatch로 실패한다.
resource DTO:
```text
ReferenceResourceDtoV1
id: non-empty string, maximum 120 characters
name: non-empty string, maximum 240 characters
createdAt?: RFC 3339 date-time
```
create command:
```text
CreateReferenceResourceCommandV1
name: trimmed string, 1..120
note?: trimmed string, 0..500
```
모든 operation이 `responseEnvelope: "ENVELOPE_V1"`이다. Envelope가 없는 백엔드(DTO와
problem details)에 붙이는 법은 [매뉴얼 02 결정표 4절](../manual/02-decision-tables.md)의
「problem details 백엔드의 예」다.
Backend는 frontend validation을 신뢰하지 않고 동일하거나 더 좁은 validation과
authorization을 다시 수행한다.
@@ -193,8 +179,9 @@ Envelope의 모양과 키 존재 규칙은 짝 백엔드 템플릿 문서가 정
바뀐 파일마다 다시 볼 프론트 위치를 말하며 1로 끝난다(1105/16-02).
- 프론트에서 Envelope를 읽는 곳: `src/adapters/http/backend-envelope.ts`(스키마와
해석). V3 실행기는 descriptor가 `responseEnvelope: "ENVELOPE_V1"`일 때 쓴다.
`create:feature`가 만든 기능은 이 값을 선언한다. 참조 기능은 `"NONE"`을
선언하고 DTO와 problem details를 검증한다. 이 칸은 descriptor 타입의 필수
`create:feature`가 만든 기능은 이 값을 선언한다. Envelope가 없는 백엔드의
operation은 `"NONE"`을 선언하고 DTO와 problem details를 검증한다(매뉴얼 02
결정표 4절의 예). 이 칸은 descriptor 타입의 필수
칸이라 빠뜨리면 `check:types`가 실패한다(1103/16-01).
- 실패 Envelope의 `error.code`가 "적용 안 됨"인지는 6.1절이 정한다.
- 페이지 목록의 `meta.page`(`number`·`size`·`total`·`sort`)는 기능의
@@ -272,7 +259,7 @@ Cross-origin bearer provider 최소 CORS:
## 6. Command와 idempotency
`CREATE_REFERENCE_RESOURCE`는 keyed command다. frontend memory single-flight는
`create:feature <id> --with-create --keyed`의 작성 operation은 keyed command다. frontend memory single-flight는
backend idempotency를 대체하지 않는다.
멱등성 응답의 status·`error.code`·`retryable`·`Retry-After`와 키 문법은 짝
@@ -287,9 +274,8 @@ backend idempotency를 대체하지 않는다.
`src/presentation/adapters/query/application-query.ts`
- Envelope operation의 거절 판정: `src/adapters/http/backend-envelope.ts`
`REFUSED_BEFORE_WRITE`(6.1절 표)
- 참조 기능(Envelope 없음) 판정: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`
(effect), `src/features/reference-feature/adapters/reference-http-gateway.ts`
(code)
- Envelope 없는 operation의 판정: 기능의 `commandEffect.classifyProblem`과
`mapProblem`(예: [매뉴얼 02 결정표 4절](../manual/02-decision-tables.md)의 코드 조각)
### 6.1 거절 code와 적용 여부
@@ -411,10 +397,10 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
프론트 판정과 표가 다른 곳(고치면 이 줄을 지운다):
- 참조 기능 분류기(`classifyProblem`)는 참조 fixture(problem+json)용이라
400·422를 모두 `NOT_APPLIED`로 본다. 참조 기능은 Envelope operation이 아니라
이 표의 대상이 아니다. 짝 백엔드에 붙이는 Envelope operation은
`src/adapters/http/backend-envelope.ts`의 표가 400·409·422를 정한다(`3261208`).
- 매뉴얼 02 결정표의 problem details 예(`classifyProblem`)는 400·422를 모두
`NOT_APPLIED`로 본다. Envelope operation이 아니라 이 표의 대상이 아니다. 짝
백엔드에 붙이는 Envelope operation은 `src/adapters/http/backend-envelope.ts`의
표가 400·409·422를 정한다(`3261208`).
남은 위험: "쓰기 전"은 현재 코드에서 그 handler에 닿는 출처를 센 결과다. 백엔드가
application bean에 `@Validated`를 달거나 JPA entity에 Bean Validation 제약을
@@ -8,23 +8,24 @@ These measurements are baselines, not score targets. A lower line count is not
automatically better if it hides business semantics or creates a universal
repository abstraction.
## Scenario A — reference REST feature
## Scenario A — a REST feature
The existing reference feature is the executable REST consumer.
The REST consumer is the feature `corepack pnpm create:feature <id> --with-create`
writes (the template's reference sample had this role until 2026-11-07).
It covers list/detail/create behavior, mapping, typed operation inputs,
application ports and an optimistic mutation path.
It covers list/detail/create behavior, mapping, typed operation inputs and
application ports.
The feature-owned boundary and application source is these four files:
- `application/reference-feature-api.ts`
- `contracts/reference-mapper.ts`
- `adapters/reference-http-gateway.ts`
- `adapters/create-reference-feature-input.ts`
- `application/<base>-feature-api.ts`
- `contracts/<base>-mapper.ts`
- `adapters/<base>-http-gateway.ts`
- `adapters/create-<base>-feature-input.ts`
This document does not keep their line counts; a hand-typed count drifted
from the code (review 14-07). Measure them with
`wc -l src/features/reference-feature/{application/reference-feature-api.ts,contracts/reference-mapper.ts,adapters/reference-http-gateway.ts,adapters/create-reference-feature-input.ts}`.
from the code (review 14-07). Measure them in a generated feature with
`wc -l` on those four files.
The important boundary metric is not the raw total. It is what those files need
to know about the platform.
@@ -53,13 +54,14 @@ The executable consumer probe is:
`tests/contract/consumer-experience/indexeddb-local-draft.test.ts`
It runs and reads the one Local Draft implementation under
`src/features/local-draft-feature`; the isolated fixture copy it used to probe
had drifted from `src` and was removed (09-12).
It runs and reads the one Local Draft implementation, the test fixture
`tests/fixtures/indexeddb-consumer` (the template's former local-draft sample
under `src/features/`, moved there because it is no product feature). An
earlier isolated copy had drifted from it and was removed (09-12).
The feature owns the Local Draft domain/application API and declares the slice
The consumer owns the Local Draft domain/application API and declares the slice
of the repository it calls (`LocalDraftRepository` in
`src/features/local-draft-feature/adapters/local-draft-indexeddb-store.ts`). The
`tests/fixtures/indexeddb-consumer/adapters/local-draft-indexeddb-store.ts`). The
host hands in an `IndexedDbRepositoryPort<LocalDraft, never>` through the
`indexedDb` capability; the port satisfies that slice structurally. The
cross-capability composition contract lives at:
@@ -80,7 +82,7 @@ It runs against native browser IndexedDB. The test creates the platform
save/find/remove through the feature API. The Local Draft feature still does
not import the IndexedDB runtime or native browser API.
Measured on `src/features/local-draft-feature` (09-12):
Measured on the Local Draft consumer, then under `src/features/` (09-12):
| Metric | Result |
| --- | ---: |
+2 -2
View File
@@ -101,8 +101,8 @@ Feature-specific contracts stay inside the vertical slice:
`features/<feature>/contracts`
The reference feature owns routes, schemas, mapper definitions, message
catalogs and contribution identities. Central installed files aggregate those
A feature owns its routes, schemas, mapper definitions, message catalogs and
contribution identities (`create:feature` writes them under its `contracts/`). Central installed files aggregate those
contributions; they do not own their semantics.
The message catalog is a deliberate special case: the compiled catalog remains
@@ -71,9 +71,9 @@ route/form/failure 의미 값
- `check:i18n`은 catalog key와 placeholder parity, backend message JSX 렌더링을
검사한다. 검사 범위는 공통 UI 디렉터리, `src/presentation/pages`, 모든
`src/features/*/presentation`이다. 플랫폼 구성 화면
`src/presentation/examples`와 예제 화면
`src/features/platform-examples-feature/presentation`(1103/09-04)은 화면
문구 ESLint 규칙에서 일부러 뺐다(`eslint.config.ts`).
`src/presentation/examples`와 Storybook story(디자인 시스템·화면 상태 갤러리,
2026-11-07 전에는 예제 화면 기능)는 화면 문구 ESLint 규칙에서 일부러
뺐다(`eslint.config.ts`).
- 화면 문구가 catalog에서 오는지는 ESLint `no-restricted-syntax`가 본다
(`eslint.config.ts`의 `screenTextSelectors`, 0929/08-02). 대상은 글자가 든
`JSXText`와 표시·접근성 속성(`aria-label`, `title`, `placeholder`, `alt`,
@@ -5,8 +5,8 @@ an independent general-purpose SDK. Its architectural role is:
> Frontend Application Foundation = Starter / Composition Skeleton + Reusable Capability Platform
The starter side owns bootstrap, routing, providers, project conventions and a
removable reference feature. The capability side owns reusable technical
The starter side owns bootstrap, routing, providers, project conventions and
the `create:feature` command that writes a feature; it ships no sample feature. The capability side owns reusable technical
problems such as HTTP execution, Server State, authentication boundaries,
IndexedDB/OPFS, Cache Storage, realtime, browser RPC, transfer and diagnostics.
@@ -78,9 +78,9 @@ A reusable capability boundary is composed from:
- feature-selected policy,
- one capability-specific runtime.
The HTTP reference path is the first concrete example.
The HTTP path is the first concrete example.
`src/adapters/http/feature-http-binding.ts` owns transport/outcome
normalization. The reference feature contributes only:
normalization. A feature `create:feature` writes contributes only:
- operation ID,
- route ID,
@@ -152,11 +152,11 @@ repository or move dataset/migration/lifecycle policy into the feature.
The repository now has two executable contribution shapes:
- Reference feature: `needs: ["http"]`
- Local Draft feature: `needs: ["indexedDb"]`
- A feature `create:feature` writes: `needs: ["http", "telemetry"]`
- The Local Draft consumer: `needs: ["indexedDb"]`
Local Draft is a compiled architecture consumer used to prove the second
capability shape; it is not added to the default product manifest. Its
Local Draft is a test fixture (`tests/fixtures/indexeddb-consumer`) used to
prove the second capability shape; it is not a feature of the product. Its
browser-capability test composes the feature over the real
`createIndexedDbRuntime` and native IndexedDB, proving that this seam is not
limited to an in-memory contract fixture.
@@ -124,7 +124,7 @@ bootstrap은 page별 orchestration이나 업무 규칙을 소유하지 않는다
| `src/adapters` | HTTP, auth, storage, cache, telemetry 구현 | outbound adapter |
| `src/bootstrap` | runtime config와 구현 조립 | 유일한 composition root |
| `src/contracts` | 여러 계층의 registry가 혼재 | 소유 계층으로 분산 |
| `src/features/reference-feature` | 완전한 제거 가능 수직 예제 | installed contribution과 제거 gate 유지 |
| `src/features/<id>` | 제품 기능의 수직 slice. 템플릿은 비어 있고 `create:feature`가 만든다(참조 샘플은 2026-11-07 삭제) | installed contribution과 제거 gate 유지 |
현재 구조가 잘 제공하는 기반은 다음과 같다.
@@ -178,7 +178,7 @@ Data Router tree, codec, surface, title, navigation, chunk/release recovery의
단일 조립 입력이며 registry/type/build 검증이 누락과 orphan을 거절한다.
RP-05에서 두 번째 불일치도 닫혔다. feature별 domain/application/adapter/
contract/presentation은 `src/features/reference-feature`가 소유하고, generic
contract/presentation은 그 기능 폴더(`src/features/<id>`)가 소유하고, generic
installed catalog만 bootstrap과 router에 노출된다. 제거 gate는 feature와 test를
삭제한 복제본에서 전체 P0 경로를 다시 실행한다.
@@ -351,7 +351,7 @@ src/
platform/
features/
reference-feature/
<feature>/
domain/
application/
ports/
@@ -376,8 +376,8 @@ src/
application capability만 둔다. `shared`, `common`, `utils` 같은 이름으로
기술과 업무 규칙을 무제한 혼합하지 않는다.
`features/reference-feature`는 구조를 설명하기 위한 완전한 수직
슬라이스다. 이 폴더를 삭제하고 route 등록 한 곳만 제거했을 때
`features/<feature>`는 구조를 설명하기 위한 완전한 수직
슬라이스다(2026-11-07부터 템플릿의 예는 `create:feature`가 만드는 기능이다). 이 폴더를 삭제하고 route 등록 한 곳만 제거했을 때
typecheck, architecture check, test와 build가 모두 통과해야 한다.
## 8. Input port 설계 규칙
@@ -835,6 +835,10 @@ status/attempt/duration bucket만 전달한다.
## 16. Feature 경계와 removable reference feature
> 2026-11-07: 템플릿의 참조 샘플은 지웠다. 이 절이 참조 기능에 요구한 수직 경로와
> 제거 검증은 `create:feature`가 만드는 기능이 맡는다(`test:feature-scaffold`가 게이트와
> 제거를, `tests/e2e/generated-feature.spec.ts`가 실제 브라우저 경로를 본다).
Reference feature는 단순 UI fixture가 아니라 다음 경로를 모두 실행해야
한다.
@@ -871,7 +875,7 @@ operation을 전역 core registry 안에 하드코딩하지 않는다.
제거 테스트는 다음을 수행해야 한다.
1. `src/features/reference-feature` 전체 삭제
1. `src/features/<feature>` 전체 삭제
2. reference route registration 삭제
3. reference test 삭제 또는 제외
4. 잔여 import와 registry owner 검색
+27 -29
View File
@@ -101,21 +101,16 @@ rather than adding another independent route or data-loading convention.
feature takes it over by declaring that route id (see "Product home and
layouts"). Its starter links are the first three screens of the navigation.
The example screens `/examples/ui`, `/examples/states` and `/examples/auth`
are one feature, `src/features/platform-examples-feature/`, in its own context
`src/contexts/platform-examples-context/` (1103/09-04). A product turns them
off like any feature: leave the id out of `VITE_PRODUCT_FEATURES`, or delete
the feature. To delete it, remove those two folders and
`tests/features/platform-examples-feature/` (its component tests), then run
`corepack pnpm generate:feature-index`;
`corepack pnpm test:sample-removal -- --feature=platform-examples-feature`
does the same in a copy of the repository and runs the gates there. Their
routes then leave the registry, the navigation, the bundle and the manual
accessibility list (FE-GATE-028). This document keeps naming the three
folders after they are gone: `verify:documentation` checks the paths of a
removable template feature (`scripts/lib/removable-template-features.ts`)
while the feature is installed and accepts them once its `feature-module.ts`
is gone (1105/14-01).
The template ships no example feature. Its example screens (`/examples/ui`,
`/examples/states`, `/examples/auth`) and its reference sample were deleted on
2026-11-07: the design-system and screen-state galleries are workshop stories
(`src/presentation/design-system/galleries.stories.tsx`), and the manual
(`docs/manual/`) with `create:feature` shows how a feature is built. A sample a
product keeps for a while is listed in
`scripts/lib/removable-template-features.ts`: `verify:documentation` checks its
paths while it is installed and accepts them once its `feature-module.ts` is
gone (1105/14-01), and `corepack pnpm test:sample-removal` removes it in a copy
of the repository and runs the gates there.
The platform overview (`/examples/platform`,
`src/presentation/examples/platform-overview-page.tsx`) stays a platform
@@ -125,11 +120,12 @@ routes module before the page, a second request round the 200 ms budget does
not fit. Its tests are the `tests/component/starter-*.test.tsx` files.
The platform's component tests (router, boundaries, shell, runtime tree) run
on the pages of the test-only feature in `tests/helpers/fixture-feature.tsx`
and keep passing without the examples. The browser-level checks in
`tests/e2e` and `tests/visual` use the example screens as their pages and run
where the examples are installed: a product that leaves them out points those
specs at its own screens or deletes them.
on the pages of the test-only feature in `tests/helpers/fixture-feature.tsx`.
The browser-level checks in `tests/e2e` and `tests/visual` use the home page,
the platform overview and the gallery stories; what needs a feature
(`tests/e2e/generated-feature.spec.ts`, the chunk recovery spec) builds a copy
of the repository with the one `create:feature` writes
(`scripts/lib/generated-feature.ts`).
### Ownership declarations
@@ -151,9 +147,9 @@ installed catalogs import, the context index the router loads lazily, and the
selected app. Every build and check script runs it first; run it yourself with
`corepack pnpm generate:feature-index`. It fails, naming the file, when:
- a directory under `src/features/` has no `feature-module.ts` and no
`NOT_A_FEATURE` marker file (`src/features/local-draft-feature/NOT_A_FEATURE`
is the one intentional example), or has both;
- a directory under `src/features/` has no `feature-module.ts`. Code that
is no feature (the IndexedDB consumer the tests compose,
`tests/fixtures/indexeddb-consumer`) lives outside `src/features/`;
- a feature names an undeclared context, or a context an undeclared app;
- a context or app exceeds its declared budget;
- `VITE_PRODUCT_FEATURES` names a feature the app does not declare. The
@@ -168,7 +164,7 @@ selected app. Every build and check script runs it first; run it yourself with
invalidation, topic versions and the external `contractPackages` the
release manifest is checked against at boot), its message catalogs, and
`loadRuntime`, which imports `feature-runtime.ts` dynamically.
`src/features/reference-feature/feature-module.ts` is the complete example.
`create:feature` writes a complete one.
2. Create `src/features/<feature>/feature-runtime.ts` with
`defineFeatureRuntime`: the `schemas` (FE-REG-SCHEMA rows for the
feature's route and API schemas), the adapter contributions
@@ -183,13 +179,14 @@ selected app. Every build and check script runs it first; run it yourself with
executes, and `check:registries` governs the FE-REG-API row projected from
it (`projectApiOperationRows` in `src/contracts/api-operations.ts`).
A product feature's contract contribution uses an `EXTERNAL_PACKAGE`
source. `TEMPLATE_FIXTURE` belongs to `reference-feature` only and never
joins the release contract set; the composer rejects it anywhere else.
source. `TEMPLATE_FIXTURE` was the template's reference sample source; it
never joins the release contract set, and the composer rejects it in any
product feature.
3. Create `src/features/<feature>/context-routes.ts` exporting
`FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here, and each
route handle carries the route's params/search `codecs`; the owning context
loads this file only when its route root is visited
(`src/features/reference-feature/context-routes.ts`). Each handle's
(a `create:feature <id> --with-create` feature's `context-routes.ts`). Each handle's
`routeId` must be a route of a feature contract in the same context; the
context refuses the routes when they load, naming the route, context and
features (`src/contexts/bounded-context-module.ts`).
@@ -207,7 +204,8 @@ selected app. Every build and check script runs it first; run it yourself with
that takes over the platform home is the exception ("Product home and
layouts").
5. If the feature has application input, augment `ApplicationFeatureInputs`
from the feature (`src/features/local-draft-feature/application/local-draft-api.ts`).
from the feature (the IndexedDB consumer fixture does it in
`tests/fixtures/indexeddb-consumer/application/local-draft-api.ts`).
6. Run `corepack pnpm check:architecture`, `corepack pnpm check:types`,
`corepack pnpm check:registries` and the tests. `tests/unit/two-feature-install-typecheck.test.ts`
keeps the installed catalogs compiling with more than one feature.
@@ -221,7 +219,7 @@ Files outside the feature directory. Everything else a feature needs is in
| --- | --- | --- |
| `src/.generated/*` | never by hand: every build and check script regenerates it | — |
| `public/release-manifest.json` (tracked, the dev server's manifest) | every added or removed feature: `create:feature` rewrites it (`node scripts/write-dev-release-manifest.ts`). Commit it with the feature. Two feature branches change its `setDigest` line; on a merge conflict take either side and run the command again (1105/16-01) | `test:unit` (`tests/unit/dev-release-manifest.test.ts`) names the command; the dev server does not boot (`CONTRACT_SET_PACKAGE_MISSING`) |
| `config/scale/feature-shape-ceilings.json` `initialJavascript` (tracked, only while the sample is installed) | every added or removed feature, and every template change that moves the initial JavaScript: `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. Commit it with the change; on a merge conflict run the command again | `test:unit` (the feature-shape growth test compares it with a build) |
| `config/scale/feature-shape-ceilings.json` `initialJavascript` (tracked) | every added or removed feature, and every template change that moves the initial JavaScript: `node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write`. Commit it with the change; on a merge conflict run the command again | `test:unit` (the feature-shape growth test compares it with a build) |
| `src/contexts/<context>/context-module.ts` | the feature needs a new context | `generate:feature-index`: `Feature <id> belongs to undeclared context <context>` |
| `src/contexts/<context>/context-layout.tsx` | the context needs its own frame instead of `AppShell` (see "Product home and layouts" below) | nothing: without it the context renders in `AppShell` |
| `artifacts/tests/a11y-manual/<ROUTE_ID>.md` | every route the feature adds. Copy a record and reset it to `Status: pending-manual-review` | `test:unit` (`tests/unit/manual-a11y-evidence.test.ts`), `verify:documentation` (names the route IDs) and FE-GATE-009 (`review:a11y-manual -- --format-only`). FE-GATE-028 requires the signed review at release |
@@ -157,7 +157,7 @@ export interface ApplicationFeatureInputs {}
declare module "../../../application/ports/in/application-api.ts" {
interface ApplicationFeatureInputs {
"reference-feature": ReferenceFeatureInput;
"invoice-feature": InvoiceFeatureInput;
}
}
```
@@ -342,8 +342,8 @@ export function useCreateResourceMutation() {
`useApplicationMutation`은 bound 정의(`BoundMutation`)만 받는다(1101/08-03).
`{ execute }`만 넘기는 raw 형태는 멱등 키와 scope 확인 없이 쓰기를 보내고
결과 불명 뒤 "다시 보내기"가 아무것도 하지 않아 타입에서 막는다. 실제 정의는
`src/features/reference-feature/presentation/use-reference-feature.ts`의
`REFERENCE_CREATE_MUTATION_POLICY`를 본다.
`create:feature <id> --with-create`가 만드는 `presentation/use-<base>-create.ts`의
작성 뮤테이션 정책을 본다.
기본 mutation은 navigation만으로 취소됐다고 가정하지 않는다. 서버 작업의 취소가
안전한 operation만 controller가 보관한 `AbortController`와 명시적 cancel action을
@@ -622,10 +622,9 @@ Form 또는 TanStack Form adapter를 평가한다.
- controller와 mapping: `src/presentation/forms`
- layout-only template: `src/presentation/templates`
- feature form schema/command mapper:
`src/features/reference-feature/presentation/reference-resource-form.ts`
- 실제 create page:
`src/features/reference-feature/presentation/reference-resource-form-page.tsx`
- feature form schema/command mapper: `create:feature <id> --with-create`의
`presentation/<base>-form.ts`
- 실제 create page: 같은 판의 `presentation/<base>-create-page.tsx`
`ApiFailure.validationIssues`는 HTTP 경계가 투영한 `path`와 `code`만 담는다.
backend message와 알 수 없는 path는 field copy로 사용하지 않는다.
+1 -1
View File
@@ -25,7 +25,7 @@ reader that accepts it must ship before any writer sends it.
| `FEATURE_OVERRIDES` | record; unknown feature id ignored | additive | `featureOverrideArtifactSchema` in `src/contracts/release-artifacts.ts` |
| Release manifest V2 | strict object | breaking | `releaseManifestV2ArtifactSchema` in `src/contracts/release-artifacts.ts` |
| HTTP success/failure envelope (V3 with `responseEnvelope: "ENVELOPE_V1"`) | strict object (`meta` strips) | breaking | `successEnvelopeSchema`, `failureEnvelopeSchema` in `src/adapters/http/backend-envelope.ts` |
| HTTP V3 response DTO (reference feature) | `.strip()` drops unknown fields | additive | `referenceResourceDtoSchema` in `src/features/reference-feature/contracts/reference-schemas.ts` |
| HTTP V3 response DTO (a feature's) | `.strip()` drops unknown fields | additive | `<camel>ItemDtoSchema` in `contracts/<base>-schemas.ts` of a feature `create:feature` writes |
| Realtime envelope | exact key set; unknown `eventType` is `MALFORMED_EVENT` | breaking | `decodeUnsafe` in `src/adapters/realtime/event-codec.ts` |
| Browser RPC transport error code | closed vocabulary; unknown code is a protocol violation | breaking | `decodeTransportFailure` in `src/adapters/browser-rpc/browser-rpc-runtime.ts` |
| Persisted client storage | versioned key; incompatible value discarded | use a new key version | `defineStorageKey` in `src/contracts/storage-keys.ts` |
+144 -20
View File
@@ -5,9 +5,12 @@
- 뼈대는 손으로 만들지 않는다. `corepack pnpm create:feature <id>`로 만든다.
- 뼈대를 실제 기능으로 바꾸는 순서가 아래 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/<base>`가 된다. 참조 기능을 지우면 context가 그 기능 때문에 남고, 그 경로 문자열이 제거 드릴(`test:sample-removal`)의 잔여 검사(`reference-resource`)에 걸린다(추론, 실행하지 않음). 남길 기능은 제품 context에 둔다.
④ **쓸 스킬**: `clean-architecture`, `codebase-design`
@@ -150,12 +151,34 @@ corepack pnpm create:feature invoice-feature
- 업무 규칙이 없으면 만들지 않는다. mapper가 DTO를 화면 값으로 바꾸는 것으로 충분하다.
- 있으면 `domain/<model>.ts`에 둔다.
- 생성 함수에서 불변식을 검사하고 `Object.freeze`로 고정한다.
- 이름은 와이어 필드가 아니라 업무 이름으로 짓는다(참조 기능은 `name`을 `displayName`으로 바꾼다).
- 예제(참조 기능): `src/features/reference-feature/domain/`
- 이름은 와이어 필드가 아니라 업무 이름으로 짓는다(예: 와이어 `name`을 화면 값 `displayName`으로).
- 예: 청구서는 발행일 뒤에만 마감된다. `domain/<model>.ts` 한 파일이다.
<!-- manual-code-block: src/features/invoice-feature/domain/invoice.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/<base>-schemas.ts`에 상수로 두고 요청 스키마와 폼 스키마가 같은 상수를 쓴다. 숫자가 두 곳에서 갈라지지 않는다.
- 참조 기능도 이름 길이를 스키마(`reference-schemas.ts`)와 폼(`reference-resource-form.ts`)에만 둔다. `domain/`에는 없다.
- 생성 판(`--with-create`)도 이름 길이 상수(`<BASE>_NAME_MAX_LENGTH`)를 스키마(`contracts/<base>-schemas.ts`)와 폼(`presentation/<base>-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`: `<featureId>/<operationId>: unknown authProfileId <id>`
- 스키마 ID나 operation ID가 겹치면 적재 때 그 ID를 말하며 실패한다.
- 예: `Invalid or duplicate schema definition: <schemaId>`, 계약 조립 `duplicate operation: <operationId>`
- `TEMPLATE_FIXTURE` 출처를 참조 기능 밖에서 쓰면 계약 조립이 거부한다.
- 오류의 `reason`: `<id>: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to reference-feature only; pin an EXTERNAL_PACKAGE`
- `TEMPLATE_FIXTURE` 출처를 제품 기능에 쓰면 계약 조립이 거부한다.
- 오류의 `reason`: `<id>: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to <fixture owner> 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 <id> --with-create`의 `adapters/<base>-http-gateway.ts`(400 `<BASE>_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: <codecId>`로 throw한다. codec ID는 계약 `routeRuntimeContracts`의 `paramsCodec`·`searchCodec` 값이다. 예제(참조 기능): `src/features/reference-feature/presentation/reference-routes.ts`.
- 파라미터나 검색값이 있는 라우트는 `context-routes.ts`의 handle에 `codecs`를 싣는다. 예제: `create:feature <id> --with-create`의 `context-routes.ts`(상세 라우트의 params codec).
- 링크용 URL 함수도 같은 codec을 `buildRouteUrl`의 세 번째 인자로 넘긴다. 기본 생성 판의 목록 라우트는 파라미터가 없어서 넘기지 않는다. `--with-create` 판의 상세 라우트는 codec을 넘긴다. 안 넘기면 `Unregistered route codec: <codecId>`로 throw한다. codec ID는 계약 `routeRuntimeContracts`의 `paramsCodec`·`searchCodec` 값이다. 예제: `--with-create` 판의 `presentation/<base>-routes.ts`.
- 검색값(`?status=open`)을 읽는 목록은 아래 두 조각을 더한다. 생성 뼈대의 목록 라우트에는 검색값이 없다.
- 조각 1(`contracts/<base>-list-search.ts`)이 검색값 스키마다. 그 스키마를 `presentation/<base>-route-codecs.ts`의 `<BASE>_ROUTE_CODECS`에 `<Pascal>ListSearch`라는 codec ID로 싣는다.
- 계약의 목록 라우트 `searchSchema`와 `routeRuntimeContracts`의 `searchCodec`을 그 codec ID로 바꾼다. 기본 판처럼 `context-routes.ts` handle에 `codecs`가 없으면 `--with-create` 판처럼 싣는다.
- 라우터는 페이지를 그리기 전에 그 codec으로 검색값을 해석한다. 틀린 값이면 페이지 대신 잘못된 경로 화면을 그린다.
- 조각 2(`presentation/use-<base>-list-filters.ts`)가 페이지에서 그 값을 타입대로 읽는 hook이다. 같은 codec으로 다시 읽으므로 cast가 없다.
<!-- manual-code-block: src/features/invoice-feature/contracts/invoice-list-search.ts -->
```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<typeof invoiceListSearchSchema>;
```
<!-- manual-code-block: src/features/invoice-feature/presentation/use-invoice-list-filters.ts -->
```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/:<id 이름>`을 붙인다. 예: `/notice/items/:noticeId`. `/notice/:noticeId`로 두지 않는다.
- 라우터(React Router)는 같은 자리에서 정적 경로를 먼저 고른다. 작성 폼 `/notice/new`가 있으면 id가 `new`인 공지는 `/notice/:noticeId`로 열 수 없다.
- `items/`를 끼우면 정적 경로와 겹치지 않는다. 참조 기능도 이렇게 한다(`/examples/reference-resources/items/:resourceId`).
- `items/`를 끼우면 정적 경로와 겹치지 않는다. 생성 판(`--with-create`)의 상세 라우트도 이렇게 한다(`<목록 경로>/items/:<camel>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 <id> --with-create`의 `presentation/use-<base>-create.ts`.
③ **잡는 검사 / 못 잡는 것**
@@ -524,7 +584,40 @@ projectRequest: (input) => Object.freeze({
- 화면 문구는 모두 catalog에서 가져온다(`message(key)`).
- 링크는 6단계의 URL 함수로 만든다.
- 결과 불명 화면 예제: `create:feature <id> --with-create`의 `presentation/<base>-create-page.tsx`(짝 백엔드 Envelope), 참조 기능의 `src/features/reference-feature/presentation/reference-resource-form-page.tsx`(problem details)
- 결과 불명 화면 예제: `create:feature <id> --with-create`의 `presentation/<base>-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`를 돌려준다.
<!-- manual-code-block: src/features/invoice-feature/presentation/use-invoice-failure-action.ts -->
```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 <id> --with-create --keyed`의 `tests/features/<id>/<base>-create-page.test.tsx`(POST를 받을 때마다 사본을 모으고 같은 키 재전송을 본다).
- 서버 권한 거절(403)은 라우터를 거치는 페이지 테스트로 본다. 생성된 페이지 테스트와 같은 도우미(`<base>-test-app.tsx`)를 쓴다.
- 403은 본문 없이 답한다. 실행기는 401·403의 본문을 읽지 않고 닫는다. 페이지 테스트 환경(jsdom + MSW)에서 본문이 있는 403(공유 시나리오 `forbidden-403`)은 그 닫기가 끝나지 않아 화면이 로딩에 머물렀다(2026-11-08 확인).
<!-- manual-code-block: tests/features/invoice-feature/invoice-forbidden.test.tsx -->
```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/<id>`
- 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=<id>`)은 지운 뒤 기록을 다시 쓰고 검사한다.
- 초기 JS 기록(`config/scale/feature-shape-ceilings.json`)도 기능과 함께 바뀐다. `test:unit`이 빌드와 대조한다. 생성 명령 출력 `Next:` 3번의 명령으로 다시 쓰고 같은 커밋에 넣는다. 기능 제거 드릴(`test:sample-removal -- --feature=<id>`)은 지운 뒤 기록을 다시 쓰고 검사한다.
- 로컬에서 FE-GATE-013을 돌리려면 `VITE_COMMIT_SHA=$(git rev-parse HEAD)`를 준다. 없으면 release candidate가 `source.revision`을 거절한다. 실패한 게이트의 로그는 `artifacts/quality/gates/FE-GATE-<NNN>.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/`의 고정 경로를 읽는다.
+122 -6
View File
@@ -50,9 +50,9 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
| | 배포된 계약 패키지 | 자리표시자 신원 | `TEMPLATE_FIXTURE` |
|---|---|---|---|
| 언제 | 백엔드가 `@org-contracts/<service>` 패키지를 배포했다 | 패키지가 아직 없다 | 쓰지 않는다. 참조 기능 전용이다 |
| 언제 | 백엔드가 `@org-contracts/<service>` 패키지를 배포했다 | 패키지가 아직 없다 | 쓰지 않는다. 템플릿이 예전 참조 샘플에 쓰던 출처다 |
| 만드는 법 | `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(<OPERATION>_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/<base>-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 예제(참조 기능): `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`의 `CREATE_EFFECT`.
**어디에 적나**: `contracts/<base>-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 짝 백엔드 예제는 `create:feature <id> --with-create`가 만든 그 파일이다. Envelope가 없는 백엔드의 예는 아래에 있다.
**problem details 백엔드의 예**
짝 백엔드가 아닌 백엔드는 DTO와 problem details(RFC 9457의 `type`·`title`·`status`)를 감싸지 않고 보낸다. 그 백엔드의 작성 operation이 쓰는 두 조각이다. 기능 이름은 `invoice-feature`(`create:feature invoice-feature --with-create`로 만든 기능)로 두었다. 자기 기능의 이름으로 바꿔 쓴다.
- 조각 1은 `contracts/<base>-problem-details.ts`다. problem 스키마와 검증기, 작성의 `commandEffect`를 둔다.
- descriptor마다 `responseEnvelope: "NONE" as const`, `problemValidator: <BASE>_PROBLEM_VALIDATOR`를 적는다. 작성 descriptor의 `commandEffect`는 `<BASE>_CREATE_EFFECT`다. Envelope operation 전용인 `refusedBeforeWrite`는 적지 않는다.
- 스키마 ID(`InvoiceProblem`)도 다른 스키마처럼 스키마 메타데이터(`contracts/<base>-schema-metadata.ts`)에 적는다. 없으면 `check:registries`가 실패한다.
- 조각 2는 `adapters/<base>-problem-mapping.ts`다. HTTP 바인딩의 `mapProblem`이 되는 함수다.
- `adapters/<base>-http-gateway.ts`의 작성 operation 정의에 `mapProblem: map<Base>CreateProblem`으로 넘긴다.
- 정하지 않은 status는 `undefined`를 돌려준다. 그러면 실행기가 status로 실패 종류를 정한다.
<!-- manual-code-block: src/features/invoice-feature/contracts/invoice-problem-details.ts -->
```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<typeof invoiceProblemSchema>;
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<string> = new Set(["CONFLICT"]);
export const INVOICE_CREATE_EFFECT: CommandEffectDescriptor<InvoiceProblem> =
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,
});
```
<!-- manual-code-block: src/features/invoice-feature/adapters/invoice-problem-mapping.ts -->
```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/`).
**틀리면**
+2 -2
View File
@@ -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="<id> removed" corepack pnpm update:registry-baseline
+2 -2
View File
@@ -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`가 시험한다).
## 문서와 코드가 다를 때
+8 -6
View File
@@ -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,17 +150,19 @@ 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)
- 저장소 복사본에 기능 둘(기본 하나, `--with-create --keyed` 하나)을 만들고 커밋한 뒤 게이트를 돈다.
- 타입, lint, 아키텍처, 레지스트리, i18n, 디자인 시스템, 진단, 문서, unit, component, integration, 기능 테스트, 커버리지, CI 계약, 빌드.
- `test:sample-removal` (FE-GATE-020)
- 참조 기능을 지운 복사본에서 이 명령(`--with-create`)으로 기능을 만들고 같은 게이트를 다시 돈다. 명령과 쓰기 slice가 참조 기능에 기대지 않는다는 증거다.
- `test:sample-removal -- --feature=<id>` (`test:feature-scaffold`가 부른다)
- 위에서 만든 기본 기능을 복사본에서 지우고 같은 게이트를 다시 돈다. 생성 기능이 지워진다는 증거다.
- 인자 없이 돌면(FE-GATE-020) `scripts/lib/removable-template-features.ts`에 적힌 샘플을 하나씩 지우고, 지운 복사본에서 이 명령(`--with-create`)으로 기능을 만들어 게이트를 다시 돈다. 템플릿은 그 목록이 비어 있어 건너뛰었다고(SKIP) 출력한다.
- `tests/e2e/generated-feature.spec.ts` (`test:e2e`, FE-GATE-008)
- 저장소 복사본에 `--with-create --keyed` 기능을 만들어 빌드하고, 실제 브라우저에서 로그인 뒤 목록, 폼 검증, 이탈 확인, 저장(멱등 키), 429 뒤 다시 시도, 결과 불명과 같은 키 재전송, 접근성(axe)을 본다. 생성기 출력이 바뀌면 여기서 잡힌다.
## 알려진 한계
- `--context reference-context`로 참조 context에 넣은 기능은 경로가 `/examples/reference-resources/<base>`다. 참조 기능을 지우면 context가 남고 그 경로가 제거 드릴의 잔여 검사에 걸린다. 남길 기능은 제품 context에 둔다.
- 드릴은 브라우저 테스트(FE-GATE-008·009의 `test:e2e`, `test:a11y` 등)와 `test:system`을 돌리지 않는다. `check:bundle`(FE-GATE-012)은 돈다.
- 드릴은 브라우저 테스트(FE-GATE-008·009의 `test:e2e`, `test:a11y` 등)와 `test:system`을 돌리지 않는다. `check:bundle`(FE-GATE-012)은 돈다. 브라우저에서의 동작은 위 e2e spec이 고정한 이름(`order-feature`)의 기능 하나로만 본다.
- 새 context는 앱이 하나일 때만 만든다. 앱이 여럿이면 `--context`로 기존 context를 고른다.
+2 -3
View File
@@ -56,8 +56,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| `Context <context> belongs to undeclared app <app>` | `CONTEXT_APP_ID` 오타 | `src/contexts/<context>/context-module.ts` |
| `<file> must export a literal <NAME>` | 헤더를 상수 참조나 식으로 썼다. 생성기는 글자로 읽는다 | 그 파일. `export const <NAME> = "<값>";` 꼴 |
| `<file> must export a positive integer <NAME>` | 예산 값이 정수 리터럴이 아니다 | 그 파일 |
| `src/features/<dir> has no feature-module.ts; add one or mark the directory with NOT_A_FEATURE` | 기능 폴더에 선언 파일이 없다 | `feature-module.ts`를 만들거나, 기능이 아닌 샘플 폴더면 `NOT_A_FEATURE` 파일을 둔다 |
| `src/features/<dir> has both feature-module.ts and NOT_A_FEATURE; …` | 기능이 아니라고 표시한 폴더에 선언 파일이 있다 | 기능으로 설치하려면 `NOT_A_FEATURE`를 지운다. 설치하지 않으려면 `feature-module.ts`를 지운다 |
| `src/features/<dir> has no feature-module.ts; add one, or keep code that is no feature outside src/features` | 기능 폴더에 선언 파일이 없다 | `feature-module.ts`를 만든다. 기능이 아닌 코드(시험용 소비자 등)면 `src/features/` 밖으로 옮긴다 |
| `Duplicate generated feature ids: <id>` | 두 폴더가 같은 `FEATURE_MODULE_ID` | 한쪽 `feature-module.ts` |
| `Duplicate context id: <id>` | 두 폴더가 같은 `CONTEXT_MODULE_ID` | 한쪽 `context-module.ts` |
| `Context <context> feature cardinality <n> exceeds budget <max>` | context의 기능 수가 예산을 넘었다 | `CONTEXT_MAX_FEATURES`, 또는 새 context |
@@ -96,7 +95,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
| `reason` | 원인 | 고칠 곳 |
|---|---|---|
| `<id>: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to reference-feature only; pin an EXTERNAL_PACKAGE` | 참조 기능 전용 출처를 다른 기능이 썼다 | `contracts/<base>-contract-contribution.ts`의 `source`를 `EXTERNAL_PACKAGE`로 |
| `<id>: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to <fixture owner> only; pin an EXTERNAL_PACKAGE` | 템플릿 fixture 출처(예전 참조 샘플용)를 제품 기능이 썼다 | `contracts/<base>-contract-contribution.ts`의 `source`를 `EXTERNAL_PACKAGE`로 |
| `duplicate operation: <operationId>` | 두 기여가 같은 operation ID | 접두어를 붙인다 |
| `duplicate contributionId: <id>` | 두 기여가 같은 `contributionId` | `contracts/<base>-contract-contribution.ts` |
| `<id>/<operationId>: unknown authProfileId <profile>` | V3 `frontend.authProfileId`가 없는 프로필 | V3 `frontend.authProfileId` |
+1 -1
View File
@@ -49,7 +49,7 @@
- 무효화 topic은 새로 만든다.
- 형식: `qinv.` + 소문자·숫자 26자.
- `scripts/create-feature.ts`의 `randomTopicSuffix`가 같은 형식으로 만든다.
- 다른 기능이나 참조 기능의 값을 복사하지 않는다.
- 다른 기능의 값을 복사하지 않는다.
- route ID는 `<BASE>_<화면>` 꼴로 짓는다(`INVOICE_DETAIL`). 라우트를 더하면 a11y 기록 파일도 더한다(`artifacts/tests/a11y-manual/<ROUTE_ID>.md`).
- 문구 키는 ko-KR과 en-US에 같은 키를 넣는다. `check:i18n`이 비교한다.
+19 -19
View File
@@ -3,22 +3,22 @@
기능을 만들 때 쓰는 패턴과, 그 패턴의 정의와 예제가 어디 있는지 적는다.
- **정의**: 플랫폼(기능 밖)에서 패턴을 제공하는 파일.
- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature <id> --with-create`가 더 만드는 코드다(짝 백엔드 Envelope 모양). `참조 기능`은 `src/features/reference-feature/`다(Envelope가 아닌 problem details 모양). 참조 기능 경로도 다른 경로처럼 백틱으로 적는다. 문서 검사(`verify:documentation`)는 참조 기능이 있는 동안 그 경로가 있는지 확인하고, 참조 기능을 지운 사본에서는 없어도 된다고 본다(`scripts/lib/removable-template-features.ts`).
- **예제**: 복사해 볼 수 있는 기능 코드. `생성 뼈대`는 `create:feature`가 만드는 코드다. `쓰기 slice`는 `create:feature <id> --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/<base>-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-<base>-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/<profile>.json`의 `FEATURE_OVERRIDES` | `config/runtime/local.json` | 참조 기능의 `tests/component/product-feature-switch.test.tsx` |
| 기능 끄기 | `config/runtime/<profile>.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/<base>-routes.ts`, 참조 기능 `presentation/reference-routes.ts` | 타입(기능의 route ID만 받음) |
| 파라미터·검색값 codec | `src/presentation/routes/route-codecs.ts` | 쓰기 slice `presentation/<base>-route-codecs.ts`(상세 params), 참조 기능 `presentation/reference-route-codecs.ts` | 해석 실패 시 잘못된 경로 화면 |
| URL 검색값 읽기 | `src/presentation/routes/route-input.tsx`의 `useRouteInput` + 검색값 codec | 참조 기능 `presentation/reference-routes.ts` | 해석 실패 시 잘못된 경로 화면 |
| route ID로 URL 만들기 | `src/presentation/routes/route-codecs.ts`의 `buildRouteUrl` | 생성 뼈대 `presentation/<base>-routes.ts` | 타입(기능의 route ID만 받음) |
| 파라미터·검색값 codec | `src/presentation/routes/route-codecs.ts` | 쓰기 slice `presentation/<base>-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/<base>-list-search.ts`, `presentation/use-<base>-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-<base>-list-filters.ts`가 예제다.
```tsx
// 공지 기능의 목록 페이지. noticeRouteUrl은 생성된 <base>-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/<base>-mapper.ts` | 타입 검사 |
| gateway port + HTTP 어댑터 | `src/adapters/http/index.ts`의 `createFeatureHttpBinding`, `defineFeatureHttpOperationForRoutes` | 생성 뼈대 `adapters/<base>-http-gateway.ts` | 음성 타입 fixture (operation ID, route ID, 입력) |
| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 쓰기 slice `adapters/<base>-http-gateway.ts`(400 `<BASE>_INVALID` → 이름 칸), 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 |
| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 쓰기 slice `adapters/<base>-http-gateway.ts`(400 `<BASE>_INVALID` → 이름 칸). problem details 백엔드(409, 422)는 [02 결정표 4절](../02-decision-tables.md#4-결과-불명)의 코드 조각 | 기능 테스트 |
| 결과와 실패 | `src/contracts/result.ts`, `src/contracts/errors.ts` | 생성 뼈대 `application/<base>-feature-api.ts` | `FailureKind` 닫힌 어휘(타입) |
| 실패 → 화면 행동 | `src/contracts/errors.ts`의 `action` | 참조 기능 `presentation/use-reference-failure-action.ts` | 페이지 테스트 |
| 실패 → 화면 행동 | `src/contracts/errors.ts`의 `action` | 코드 조각: [01 문서 8단계](../01-add-a-feature.md#8단계-페이지)의 `presentation/use-<base>-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-<base>-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/<base>-contract-contribution.ts`, `presentation/use-<base>-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/<base>-create-page.tsx`, 참조 기능 `presentation/reference-resource-form-page.tsx` | 기능 테스트만(쓰기 slice는 `<base>-create-page.test.tsx`) |
| 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (참조 기능은 생성 명령만 있다) | — |
| 멱등 키 쓰기 | V3 `retrySemantics: "KEYED"`, `commandRecovery`, 뮤테이션 정책(`src/contracts/server-state.ts`의 `commandMutationIdentity`로 operation ID와 키 여부를 descriptor에서 받는다) | 쓰기 slice `--keyed`(`contracts/<base>-contract-contribution.ts`, `presentation/use-<base>-create.ts`) | 계약 조립(복구 descriptor 필수), 타입(descriptor 상수 이름, 손으로 적은 operation ID는 `MutationOperationId`가 아니다), 기능 테스트 |
| 결과 불명 화면 | `src/presentation/components/async-surface.tsx`의 `onReconcileUnknownEffect`, `onResendUnknownEffect` | 쓰기 slice `presentation/<base>-create-page.tsx` | 기능 테스트만(쓰기 slice는 `<base>-create-page.test.tsx`) |
| 수정·삭제 명령 | 같은 V3 계약 (`PUT`, `PATCH`, `DELETE`) | 없음 (쓰기 slice는 작성 명령만 만든다) | — |
| 낙관적 갱신 | `useApplicationMutation`의 `optimistic` 옵션 (`application-query.ts`) | 없음 | 런타임 테스트만 |
| 페이지 넘김 | `src/adapters/query-cache/index.ts`의 `createCursorPaginationRuntime` | 없음 (참조 기능은 커서 필터만, 다음 커서 없음) | 런타임 테스트만 |
| 로컬 저장(IndexedDB) | `recipes/frontend-capabilities/indexeddb-feature-capability.ts` + `product-composition.ts` | `src/features/local-draft-feature/` (`NOT_A_FEATURE`, 기능이 아닌 샘플) | 계약 테스트 |
| 페이지 넘김 | `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/<base>-form.ts`와 `<base>-create-page.tsx`, 참조 기능 `presentation/reference-resource-form.ts`와 폼 페이지 | 페이지 테스트(서버 필드 오류, 이탈 확인) |
| 폼 | `src/presentation/forms/use-app-form.ts`의 `useAppForm` | 쓰기 slice `presentation/<base>-form.ts`와 `<base>-create-page.tsx` | 페이지 테스트(서버 필드 오류, 이탈 확인) |
| 화면 문구 | `src/presentation/i18n/index.ts`, 기능 문구 catalog | 생성 뼈대 `contracts/<base>-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/<id>/<base>-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/<id>/<base>-create-page.test.tsx` | `test:coverage` |
| 같은 멱등 키 재전송 | 시나리오 `in-flight-409` + 위 요청 모으기 | 01 문서 10단계 | `test:coverage` |
## 관측
@@ -194,7 +194,7 @@ Captured after every correctness task landed.
| `git diff --check` | 0 | clean |
| `corepack pnpm test:component` | 0 | 126 passed |
| `corepack pnpm test:integration` | 0 | 52 passed |
| `corepack pnpm test:reference-feature` | 0 | 26 passed |
| 참조 샘플 기능 시험(그 script는 2026-11-07 샘플과 함께 지웠다) | 0 | 26 passed |
| `corepack pnpm test:recipes` | 0 | 17 passed |
| `corepack pnpm test:unit` | 1 | 1585 passed / 19 failed tests; the 19 are the unchanged pre-existing `ci-artifact-contract` sandbox failures |
| `corepack pnpm check:registries` | 0 | 11 registries PASS |
@@ -340,7 +340,7 @@ Run on the landed tree. Only what actually passed is claimed as passing.
| `tests/unit` + `tests/integration`, no exclusions | — | 1643 passed / 1747; the 104 failures are the four environmental files below |
| `corepack pnpm test:component` | 0 | 126 passed |
| `corepack pnpm test:recipes` | 0 | 17 passed |
| `corepack pnpm test:reference-feature` | 0 | 26 passed |
| 참조 샘플 기능 시험(그 script는 2026-11-07 샘플과 함께 지웠다) | 0 | 26 passed |
### Environmental failures, not claimed as green
+11 -7
View File
@@ -20,15 +20,16 @@ Performance evidence is deliberately split by measurement context:
보고 예산을 정한다.
기준선 숫자는 이 문서에 적지 않는다. 손으로 적은 숫자는 두 번 낡았다. 기록은
`config/scale/feature-shape-ceilings.json`의 `initialJavascript` 한 곳이다. 이 파일과 아래
측정 테스트는 참조 기능을 복사해 재므로 샘플과 함께 지워진다. 문서 검사는 샘플을 지운 사본에서
이 경로들을 요구하지 않는다(`scripts/lib/removable-template-features.ts`).
`config/scale/feature-shape-ceilings.json`의 `initialJavascript` 한 곳이다. 측정은
`create:feature <id> --with-create --keyed`가 만드는 기능을 복사해 잰다
(`scripts/scale/measure-feature-shape-growth.ts`, 2026-11-07 전에는 참조 샘플을 복사했다).
| 칸 | 뜻 |
|---|---|
| `gzipBytes`, `files` | 템플릿 그대로의 초기 JS gzip bytes와 파일 수(entry 포함) |
| `perFeatureGzipBytes` | 있는 context에 참조 기능 모양 기능을 하나 더할 때 느는 초기 JS. 상한 1 KiB |
| `perContextGzipBytes` | 새 context를 하나 더할 때 느는 초기 JS. 상한 512 B |
| `firstFeatureGzipBytes` | 기능이 없는 템플릿에 첫 기능(과 그 context)을 더할 때 느는 초기 JS. 모든 기능이 함께 쓰는 코드가 이때 초기 청크에 들어온다. 한 번만 든다. 상한 없음(전체는 `check:bundle`의 예산이 막는다) |
| `perFeatureGzipBytes` | 있는 context에 생성 기능 모양 기능을 하나 더할 때 느는 초기 JS. 상한 1 KiB |
| `perContextGzipBytes` | 둘째 기능을 같은 context 대신 새 context에 둘 때 느는 초기 JS. 상한 512 B |
- `tests/unit/feature-shape-growth.test.ts`(unit, merge 단계)가 매번 빌드해 이
값을 재고, 상한을 넘거나 기록과 다르면(합계 256 B 초과, 파일 수 불일치, 기능·
@@ -120,11 +121,14 @@ lab 측정(`scripts/test-performance.ts`, FE-GATE-026)은 local 프로필 build
`context.sampling.targetDeepLink`에 남긴다. 예산은 `cls`와 같다(1105/15-01).
- 대상 화면(플랫폼 구성)은 기능 코드를 받지 않으므로 기능이 늘어도 수치가
거의 그대로다. 그래서 run마다 설치된 기능이 가진 첫 공개 내비게이션
라우트(`labFeatureRoute`, 템플릿에서는 `EXAMPLES_UI`)를 같은 시계로 따로 잰다
라우트(`labFeatureRoute`)를 같은 시계로 따로 잰다
(`metrics.featureRouteInteractionMs`, `context.sampling.featureRoute`,
1105/15-04). 그런 라우트가 없으면 `measured: false`로 남기고 판정하지 않는다.
템플릿은 기능이 없어 재지 않는다(2026-11-07 예제 화면 삭제 뒤. 그 전에는 예제
화면 `/examples/ui`가 이 라우트였다). 공개 내비게이션 라우트를 가진 제품 기능이
생기면 그 라우트를 잰다.
- 예산 `lab.featureRouteInteractionMs`는 500 ms다. 근거: `8a44226`에서 lab
조건으로 `EXAMPLES_UI`를 5회 재니 중앙값 406 ms(403~410)였다. 그 진입은 요청
조건으로 그때의 예제 화면 라우트를 5회 재니 중앙값 406 ms(403~410)였다. 그 진입은 요청
두 묶음이다(context 라우트 모듈과 기능 실행부, 그다음 페이지 청크와 공유
청크). 둘째 묶음이 약 100 ms(클릭 뒤 98~204 ms)다. 500 ms는 지금 진입을
통과시키고, 같은 크기의 묶음이 하나 더 붙으면 넘는다.
+7 -7
View File
@@ -38,8 +38,8 @@
- local form facade, field/error summary, dirty navigation dialog
- `src/presentation/templates`
- Standard, Collection, Detail, Form, Status page template
- `/examples/ui`, `/examples/states`
- 실행 가능한 primitive와 상태 예제
- `src/presentation/design-system/galleries.stories.tsx`
- 실행 가능한 primitive와 상태 예제(Storybook 갤러리 story)
- component/E2E/axe 테스트
- 필드 설명과 오류 연결
- native dialog 닫기와 trigger focus 복원
@@ -623,8 +623,8 @@ RP-10의 Storybook toolbar에서 최소한 다음 조합을 전환할 수 있어
## 10. Storybook과 시각 검증
현재 `/examples/ui`는 실행 중인 앱 셸과 primitive 통합을 확인하는 데 유지한다.
그러나 runtime gallery는 isolated component workshop을 대체하지 않는다.
디자인 시스템 갤러리와 화면 상태 갤러리는 Storybook story다. 앱 셸과 primitive의
통합은 `/`와 `/examples/platform`을 여는 e2e가 확인한다.
[Storybook 공식 UI 테스트 문서](https://storybook.js.org/docs/writing-tests)는
story를 기반으로 interaction, accessibility, visual test를 구성하는 방법을
@@ -796,8 +796,8 @@ long-content
### Step 9. 통합 예제를 추가한다
- `/examples/ui`에는 primitive를 추가한다.
- `/examples/states`에는 새로운 공통 상태를 추가한다.
- 갤러리 story(`galleries.stories.tsx`)의 `DesignSystem`에는 primitive를 추가한다.
- 같은 파일의 `ScreenStates`에는 새로운 공통 상태를 추가한다.
- pattern/template은 domain-neutral fixture로 실제 조합을 보여 준다.
- production profile에서 예제 route를 제외할 수 있는 계약을 유지한다.
@@ -919,7 +919,7 @@ component contract에 기록한다. 예를 들어 `Separator`에는 pending/erro
9. locale provider, pseudo-locale, RTL 검증을 추가한다.
10. Storybook, story a11y, interaction test를 추가한다.
11. pinned browser 환경의 visual regression gate를 추가한다.
12. `/examples/ui`와 `/examples/states`를 통합 smoke gallery로 유지한다.
12. 디자인 시스템·화면 상태 갤러리를 Storybook story로 유지하고 visual 골든의 대상으로 쓴다.
이 순서는 라이브러리 수를 늘리는 것이 목표가 아니다. 각 단계가 제품 개발자가
중복 구현할 문제를 하나씩 제거하고, 외부 공급자를 교체할 수 있는 로컬 계약과
+4 -3
View File
@@ -7,7 +7,8 @@ the dark theme, and `component.css` maps roles to per-component values.
`src/presentation/styles/theme.css` only imports the three files and the style
files under `src/presentation/styles/theme/`. Components consume semantic
color, spacing, typography, status, and radius tokens through static classes.
`/examples/ui` is the executable token and primitive gallery.
The executable token and primitive gallery is the workshop story
`src/presentation/design-system/galleries.stories.tsx` (`corepack pnpm storybook`).
## Rules a rebrand must keep
@@ -61,8 +62,8 @@ Arbitrary-value policy:
- user-controlled or runtime-composed class strings are forbidden
- class variants must be selected from a closed static map
The removable reference feature may demonstrate tokens, but generic production
starter modules do not import its domain, application, adapter, or presentation
A feature may demonstrate tokens, but generic production starter modules do
not import a feature's domain, application, adapter, or presentation
implementation.
This file documents the currently implemented token and primitive baseline.
@@ -503,8 +503,9 @@ tests/support/query/
helper는 production default를 복사하지 않는다. production factory를 호출하고
필요한 시간·retry만 test override로 주입한다.
RP-05의 executable reference matrix는
`tests/features/reference-feature`에 모여 있다. 설치 모드에서는 URL codec과
RP-05의 executable reference matrix는 참조 샘플의 시험 폴더에 모여 있었다(2026-11-07
샘플과 함께 삭제). 지금 기능 하나의 경로는 `create:feature`가 만든 기능의 시험
(`tests/features/<id>/`)과 `tests/e2e/generated-feature.spec.ts`가 본다. 그때 설치 모드에서는 URL codec과
query key/HTTP search의 동일성, DTO 차단, loading/success/empty/terminal,
refreshing/stale, pending/duplicate/optimistic/conflict/rollback과 MSW production
composition을 검증한다. 제거 모드는 feature source/tests와 installed
@@ -513,8 +514,8 @@ contract/runtime/adapter contribution을 제거한 복제본에서 P0 gate와 bu
RP-06 form/page matrix는 `tests/component/form-foundation.test.tsx`,
`tests/component/page-templates.test.tsx`,
`tests/features/reference-feature/reference-page.test.tsx`와
`tests/e2e/reference-form.spec.ts`에 있다. client validation에서 command 0회와
생성 기능의 `<base>-create-page.test.tsx`와
`tests/e2e/generated-feature.spec.ts`에 있다(2026-11-07 전에는 참조 샘플의 페이지 시험과 폼 e2e). client validation에서 command 0회와
첫 오류 focus, Zod transform/default, pending 중 중복 제출, 승인된 422
field/unknown field mapping, conflict 입력 보존, reset/dirty, navigation
confirmation/focus restore, URL/storage 비노출과 320px reflow를 검증한다.
@@ -808,8 +809,10 @@ production runtime config에 `MOCK_MODE`, `SCENARIO`, fake token 같은 key를
## 12. Storybook 테스트
Storybook은 component를 격리해 state를 열거하고 실제 브라우저 interaction과
접근성을 검사하는 개발·CI surface다. `/examples/ui`는 앱 통합 smoke로 유지하되
Storybook을 대신하지 않는다.
접근성을 검사하는 개발·CI surface다. 디자인 시스템 갤러리와 화면 상태 갤러리도
story다(`src/presentation/design-system/galleries.stories.tsx`). 갤러리의 브라우저
상호작용 검사는 `tests/storybook/galleries.spec.ts`가, 앱 셸 안의 통합 확인은
`/`와 `/examples/platform`을 여는 e2e가 맡는다.
### 12.1 Global decorator
@@ -945,9 +948,10 @@ Playwright `toHaveScreenshot()`을 사용한다.
- `app-shell-wide-light`: `/`, 1440×900, light, 전체 페이지 — wide app shell
- `app-shell-compact-pseudo-drawer`: `/`, 390×844, en-XA, 메뉴 서랍 열림 —
compact app shell, pseudo-locale, 열린 drawer
- `design-system-gallery-dark`: `/examples/ui`, dark — design-system 갤러리
- `state-surfaces-light`: `/examples/states` — loading, background refresh,
empty, error, 401, 403, 404
- `design-system-gallery-dark`: Storybook 정적 빌드의 갤러리 story
`platform-galleries--design-system`, 1280×900, 시스템 dark — design-system 갤러리
- `state-surfaces-light`: Storybook 정적 빌드의 `platform-galleries--screen-states`,
1280×1100 — loading, background refresh, empty, error, 401, 403, 404
- `platform-overview-light`: `/examples/platform` — 플랫폼 구성 개요
`check-test-evidence`는 기준선 PNG가 4장 이상인지만 본다. 위 목록의 각
@@ -1034,7 +1038,7 @@ TEST_RUN_ID=a playwright test
|---|---|---|
| `TEST_RUN_ID` | 다섯 Playwright 설정, `tests/e2e/preload-use.spec.ts` | `dist`, `artifacts/tests/<이름>/` |
| `RUN_OUTPUT_ROOT` | 빌드 단계 전부(`scripts/build-frontend.ts`가 부르는 것), `vite.config.ts`. 설정이 web server에만 넘긴다. 빌드 뒤 검사(`scripts/generate-supply-chain.ts`, `scripts/check-bundle.ts`)는 `.`이 아니면 멈춘다 | `.` |
| `TEST_E2E_PORT`, `TEST_VISUAL_PORT`, `TEST_CAPABILITIES_PORT`, `TEST_STORYBOOK_PORT`, `TEST_DEV_PORT` | 각 설정 | 빈 포트 |
| `TEST_E2E_PORT`, `TEST_VISUAL_PORT`, `TEST_VISUAL_WORKSHOP_PORT`, `TEST_CAPABILITIES_PORT`, `TEST_STORYBOOK_PORT`, `TEST_DEV_PORT` | 각 설정(`TEST_VISUAL_WORKSHOP_PORT`는 visual 설정의 두 번째 서버, 갤러리 골든이 여는 Storybook 정적 빌드) | 빈 포트 |
- run ID는 글자·숫자·`.`·`_`·`-` 64자 이하이고 글자나 숫자로 시작한다.
- 포트 변수를 주면 그 포트를 쓴다. 디버깅할 때 고정하는 용도다.
+1 -1
View File
@@ -19,7 +19,7 @@ Each gate is blocking in its declared scope. Failures are not downgraded with
`test:all` is the normal product-development loop. It runs, in order,
`test:runtime-schema`, `test:unit`, `test:contract`, `test:component`,
`test:integration`, the rest of what `test:coverage` runs (`tests/features`,
the reference sample's tests among them, `tests/scripts` and
each installed feature's tests, `tests/scripts` and
`tests/scale/browser-soak.contract.test.ts`), `test:platform` (`tests/platform`
and `tests/architecture`), `check:release-coherence` and `test:recipes`
(`package.json` `test:all`). So every Vitest path the merge gate's coverage
+5 -9
View File
@@ -458,9 +458,9 @@ const hookRules = {
// template literal, a ternary, an object prop such as `heading.title`) is not
// seen; review catches those. A product replaces these selectors in its own
// config, for example to allow a brand name or to drop the rule for a
// one-locale product. The platform overview (src/presentation/examples),
// the example screens (src/features/platform-examples-feature/presentation)
// and stories are workshop code and stay out; tests are outside these folders.
// one-locale product. The platform overview (src/presentation/examples) and
// stories (the galleries among them) are workshop code and stay out; tests
// are outside these folders.
const screenTextDirectories = [
"src/presentation/boundaries",
"src/presentation/components",
@@ -912,13 +912,9 @@ export default [
`${directory}/**/*.tsx`,
`tests/fixtures/i18n/*/${directory}/**/*.tsx`,
]),
// 1103/09-04. The example screens moved from src/presentation/examples
// into this feature and stay workshop code: their copy is Korean in every
// Stories are workshop code: the galleries' copy is Korean in every
// locale on purpose (08-07).
ignores: [
"**/*.stories.tsx",
"src/features/platform-examples-feature/presentation/**",
],
ignores: ["**/*.stories.tsx"],
rules: {
"no-restricted-syntax": [
...commonSecurityRules["no-restricted-syntax"],
+1 -2
View File
@@ -78,7 +78,6 @@
"test:optional-recipe-removal": "node scripts/test-optional-recipe-removal.ts",
"test:browser-file-storage-removal": "node scripts/test-browser-file-storage-runtime-removal.ts",
"test:realtime-removal": "node scripts/test-realtime-runtime-removal.ts",
"test:reference-feature": "node scripts/run-vitest.ts run tests/features/reference-feature --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/reference-feature.xml --passWithNoTests",
"check:v8-coverage-counter-semantics": "node scripts/check-v8-coverage-counter-semantics.ts",
"test:coverage": "corepack pnpm check:v8-coverage-counter-semantics && node scripts/run-vitest.ts run tests/runtime-schema tests/unit tests/contract tests/component tests/integration tests/features tests/platform tests/architecture tests/release tests/scripts tests/scale/browser-soak.contract.test.ts --coverage --maxWorkers=4 --reporter=default --reporter=junit --outputFile.junit=artifacts/tests/coverage.xml && node scripts/check-risk-coverage.ts",
"check:coverage:fixture": "node scripts/check-risk-coverage.ts --summary tests/fixtures/coverage/below-threshold.json --artifact artifacts/quality/risk-coverage-fixture.json",
@@ -149,7 +148,7 @@
"check:request-fanout": "node scripts/check-request-fanout.ts && node scripts/check-request-fanout.ts --fixture",
"check:app-build-input": "node scripts/check-app-build-input.ts",
"check:app-build-input:bundle": "node scripts/check-app-build-input.ts --require-bundle",
"test:extreme-scale:focused": "node scripts/run-vitest.ts run tests/scale/global-local-independence.test.ts tests/architecture/app-build-input.test.ts tests/architecture/request-fanout.test.ts tests/platform/traffic/request-fanout.test.ts tests/platform/traffic/request-deduplication.test.ts tests/features/reference-feature/reference-request-fanout.test.ts tests/features/reference-feature/reference-request-deduplication.test.ts tests/scripts/generate-product-feature-index.test.ts --reporter=default",
"test:extreme-scale:focused": "node scripts/run-vitest.ts run tests/scale/global-local-independence.test.ts tests/architecture/app-build-input.test.ts tests/architecture/request-fanout.test.ts tests/platform/traffic/request-fanout.test.ts tests/platform/traffic/request-deduplication.test.ts tests/scripts/generate-product-feature-index.test.ts --reporter=default",
"check:release-coherence": "node scripts/run-vitest.ts run tests/platform/release tests/release --reporter=default"
},
"dependencies": {
+5 -14
View File
@@ -4,22 +4,14 @@ import {
reservePort,
TEST_PORT_VARIABLES,
testRunPath,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
import { storybookStaticServer } from "./scripts/lib/storybook-static.ts";
// 1105/12-04. Under TEST_RUN_ID the workshop is built into the run's own
// folder (.tmp/runs/<id>/artifacts/storybook/static) with build:storybook's
// two steps and another output folder, and the results and report are the
// run's own. Unset, the gate's build:storybook writes artifacts/storybook/static.
// The static server listens on a free port (TEST_STORYBOOK_PORT pins one).
const staticDirectory = testRunPath("artifacts/storybook/static");
// 1105/12-04. Under TEST_RUN_ID the workshop build (storybookStaticServer),
// the results and the report are the run's own. The static server listens on
// a free port (TEST_STORYBOOK_PORT pins one).
const port = await reservePort(TEST_PORT_VARIABLES.storybook);
const origin = `http://127.0.0.1:${port}`;
const buildWorkshop =
testRunRoot() === "."
? "corepack pnpm build:storybook"
: "node scripts/generate-product-feature-index.ts && " +
`corepack pnpm exec storybook build -o ${staticDirectory}`;
export default defineConfig({
testDir: "./tests/storybook",
@@ -45,8 +37,7 @@ export default defineConfig({
screenshot: "only-on-failure",
},
webServer: {
command:
`${buildWorkshop} && node scripts/serve-static.ts ${staticDirectory} ${port}`,
command: storybookStaticServer(port).command,
url: origin,
reuseExistingServer: false,
},
+26 -13
View File
@@ -10,6 +10,7 @@ import {
testRunPath,
testRunRoot,
} from "./scripts/lib/run-isolation.ts";
import { storybookStaticServer } from "./scripts/lib/storybook-static.ts";
// 1105/12-04. Under TEST_RUN_ID the results, report and build are the run's
// own (.tmp/runs/<id>/); the goldens in snapshotDir are shared and only read.
@@ -18,6 +19,11 @@ import {
const dist = testRunPath("dist");
const port = await reservePort(TEST_PORT_VARIABLES.visual);
const origin = `http://127.0.0.1:${port}`;
// The design-system and screen-state galleries are workshop stories
// (src/presentation/design-system/galleries.stories.tsx); their goldens open
// the static workshop, which the second server serves
// (TEST_VISUAL_WORKSHOP_PORT pins its port).
const workshopPort = await reservePort(TEST_PORT_VARIABLES.visualWorkshop);
export default defineConfig({
testDir: "./tests/visual",
@@ -62,19 +68,26 @@ export default defineConfig({
},
},
},
webServer: {
// The home page and the platform overview print the build and release
// identity. CI sets VITE_BUILD_ID, VITE_COMMIT_SHA and RELEASE_ID for the
// whole workflow, so its build drew other text than the goldens and every
// CI run failed here. The goldens are the template's shape, captured with
// the local identity.
// 1103/11-08: CI too, or the build is checked as a release build.
env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() },
command:
`corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port ${port} --strictPort --outDir ${dist}`,
url: origin,
reuseExistingServer: false,
},
webServer: [
{
// The home page and the platform overview print the build and release
// identity. CI sets VITE_BUILD_ID, VITE_COMMIT_SHA and RELEASE_ID for
// the whole workflow, so its build drew other text than the goldens and
// every CI run failed here. The goldens are the template's shape,
// captured with the local identity.
// 1103/11-08: CI too, or the build is checked as a release build.
env: { ...LOCAL_BUILD_IDENTITY, [RUN_OUTPUT_ROOT_VARIABLE]: testRunRoot() },
command:
`corepack pnpm build && corepack pnpm preview --host 127.0.0.1 --port ${port} --strictPort --outDir ${dist}`,
url: origin,
reuseExistingServer: false,
},
{
command: storybookStaticServer(workshopPort).command,
url: `http://127.0.0.1:${workshopPort}`,
reuseExistingServer: false,
},
],
projects: [
{ name: "visual-fonts", testMatch: /fonts\.setup\.ts$/ },
{ name: "chromium-visual", dependencies: ["visual-fonts"] },
+1 -3
View File
@@ -15,7 +15,5 @@
"SERVICE_WORKER": "DEFAULT",
"OFFLINE_COMMANDS": "DEFAULT"
},
"FEATURE_OVERRIDES": {
"reference-feature": "DEFAULT"
}
"FEATURE_OVERRIDES": {}
}
-7
View File
@@ -10,13 +10,6 @@
"routeChunks": {
"route-home": "src/presentation/pages/home-page.tsx",
"route-examples-platform": "src/presentation/examples/platform-overview-page.tsx",
"route-examples-ui": "src/features/platform-examples-feature/presentation/ui-gallery-page.tsx",
"route-examples-states": "src/features/platform-examples-feature/presentation/state-gallery-page.tsx",
"route-examples-auth": "src/features/platform-examples-feature/presentation/auth-example-page.tsx",
"route-reference-resources": "src/features/reference-feature/presentation/reference-resource-page.tsx",
"route-reference-resource-detail": "src/features/reference-feature/presentation/reference-resource-detail-page.tsx",
"route-reference-resource-form": "src/features/reference-feature/presentation/reference-resource-form-page.tsx",
"route-reference-resource-status": "src/features/reference-feature/presentation/reference-resource-status-page.tsx",
"route-not-found": "src/presentation/pages/not-found-page.tsx"
},
"contractSet": {
@@ -7,8 +7,8 @@ import {
createIndexedDbRepositoryProvider,
type IndexedDbRepositoryProvider,
} from "../../src/features/feature-adapter-contribution.ts";
import type {} from "../../src/features/local-draft-feature/adapters/create-local-draft-feature-input.ts";
import type { LocalDraft } from "../../src/features/local-draft-feature/domain/local-draft.ts";
import type {} from "../../tests/fixtures/indexeddb-consumer/adapters/create-local-draft-feature-input.ts";
import type { LocalDraft } from "../../tests/fixtures/indexeddb-consumer/domain/local-draft.ts";
type LocalDraftRuntimeDependencies = IndexedDbRuntimeDependencies<
LocalDraft,
@@ -21,7 +21,8 @@ type LocalDraftRuntime = ReturnType<
/**
* 09-05. How a host builds the `indexedDb` feature capability, shown for the
* local-draft sample. IndexedDB is an opt-in reference runtime
* local-draft consumer the tests compose (tests/fixtures/indexeddb-consumer).
* IndexedDB is an opt-in reference runtime
* (`offline-indexeddb` in config/recipes/frontend-capability-recipes.json,
* `productionComposition: false`), so `src/bootstrap/runtime-adapters.ts` does
* not build it. A product that installs a feature with `needs: ["indexedDb"]`
@@ -141,10 +141,10 @@ const misplacedAdapterResults = [
),
},
{
file: "src/features/reference-feature/adapters/boundary-fixture.ts",
file: "src/features/fixture-feature/adapters/boundary-fixture.ts",
result: runEslintSource(
objectUrlBypassSource,
"src/features/reference-feature/adapters/boundary-fixture.ts",
"src/features/fixture-feature/adapters/boundary-fixture.ts",
),
},
{
+2 -3
View File
@@ -59,9 +59,8 @@ if (!fixtureMode) {
// from an ordinary `.message` read. Fixture mode runs the ESLint rule on the
// fixture trees too, so this one gate shows the whole i18n contract rejecting
// every forbidden file and passing the allowed one.
// `src/presentation/examples` (the platform overview) and the example
// screens (`src/features/platform-examples-feature/presentation`, 1103/09-04)
// are workshop code and stay out of the ESLint rule's scope on purpose.
// `src/presentation/examples` (the platform overview) and the stories are
// workshop code and stay out of the ESLint rule's scope on purpose.
const forbiddenFixtureRoot = "tests/fixtures/i18n/forbidden";
const allowedFixtureRoot = "tests/fixtures/i18n/allowed";
const sourceRoot = fixtureMode ? forbiddenFixtureRoot : ".";
+2 -2
View File
@@ -1709,7 +1709,7 @@ export const FEATURE_TRACKED_FILE_REWRITES = Object.freeze([
Object.freeze({
path: "config/scale/feature-shape-ceilings.json",
command: "node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write",
when: "by hand while the sample is installed (the file goes with it): test:unit compares it with a build",
when: "by hand with the feature: test:unit compares it with a build",
}),
]);
@@ -1772,7 +1772,7 @@ function report(plan: FeaturePlan): string {
" 2. Run the merge gates: corepack pnpm ci:gate -- FE-GATE-<NNN> for each gate of the merge stage in config/ci/gates.json (README lists the loop). test:feature-scaffold runs them on a generated feature except the browser gates FE-GATE-008/009 and test:system.",
` The feature's own tests: node scripts/run-vitest.ts run tests/features/${plan.id} (test:coverage runs them in CI)`,
" A failing gate's log is artifacts/quality/gates/FE-GATE-<NNN>.txt. Locally FE-GATE-013 needs VITE_COMMIT_SHA=$(git rev-parse HEAD); to run them as CI does, set CI=true and the CI build identity (README).",
" 3. The initial JavaScript changes. While config/scale/feature-shape-ceilings.json exists (the sample is installed), rewrite it with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write and commit it with the feature; test:unit compares it with a build. corepack pnpm check:bundle checks the budget.",
" 3. The initial JavaScript changes. Rewrite config/scale/feature-shape-ceilings.json with node scripts/scale/measure-feature-shape-growth.ts --initial-baseline --write and commit it with the feature; test:unit compares it with a build. corepack pnpm check:bundle checks the budget.",
" public/release-manifest.json (the dev server's manifest) now names the feature's contract package; commit it with the feature.",
" Two feature branches change the same lines of these files. On a merge conflict, take either side and run the command again:",
...FEATURE_TRACKED_FILE_REWRITES.map((file) => ` ${file.path}: ${file.command}`),
+8 -26
View File
@@ -272,22 +272,15 @@ function requiredInteger(source: string, name: string, file: string): number {
}
/**
* 09-07 (D-10). A feature directory must declare itself or say it is not a
* feature. A missing or misspelt `feature-module.ts` used to drop the
* feature from the product without a word.
*
* 1103/09-09. The marker was named `NOT_INSTALLED`, the runtime state of a
* declared feature the build or the runtime document left out
* (`src/contracts/product-features.ts`). It marks something else, a directory
* that is no feature at all (an architecture sample), so it has its own name,
* and a directory may not carry both the marker and a declaration.
* 09-07 (D-10). A feature directory must declare itself. A missing or
* misspelt `feature-module.ts` used to drop the feature from the product
* without a word. Code that is no feature (a test's consumer fixture) lives
* outside src/features.
*/
export const NOT_A_FEATURE_MARKER = "NOT_A_FEATURE";
async function readDeclarations(
directory: string,
fileName: string,
requiredUnless?: string,
required = false,
): Promise<readonly Readonly<{ directory: string; file: string; source: string }>[]> {
const found: { directory: string; file: string; source: string }[] = [];
let items;
@@ -299,24 +292,13 @@ async function readDeclarations(
for (const item of items) {
if (!item.isDirectory()) continue;
const file = resolve(directory, item.name, fileName);
const marker =
requiredUnless !== undefined &&
(await readFile(resolve(directory, item.name, requiredUnless)).then(
() => true,
() => false,
));
let source: string;
try {
source = await readFile(file, "utf8");
} catch {
if (requiredUnless === undefined || marker) continue;
if (!required) continue;
throw new Error(
`src/features/${item.name} has no ${fileName}; add one or mark the directory with ${requiredUnless}`,
);
}
if (marker) {
throw new Error(
`src/features/${item.name} has both ${fileName} and ${requiredUnless}; delete ${requiredUnless} to install it, or ${fileName} to keep it out`,
`src/features/${item.name} has no ${fileName}; add one, or keep code that is no feature outside src/features`,
);
}
found.push({ directory: item.name, file, source });
@@ -368,7 +350,7 @@ export async function createFileSystemDeclarationSource(
for (const declaration of await readDeclarations(
resolve(root, "src/features"),
"feature-module.ts",
NOT_A_FEATURE_MARKER,
true,
)) {
const feature: FeatureDeclaration = {
id: requiredLiteral(declaration.source, "FEATURE_MODULE_ID", declaration.file),
+1 -1
View File
@@ -113,7 +113,7 @@ type ReadFacts = Readonly<{
* not listed.
*
* This finds the detail pages that take their params schema from their read
* (the reference sample and every `create:feature --with-create` slice). A
* (every `create:feature --with-create` slice). A
* detail page whose params schema differs is not found, and its record alone
* decides, as before.
*/
+2 -2
View File
@@ -34,8 +34,8 @@ import path from "node:path";
* a test title), and no text rule tells that from a reference, so a spec
* that names only a one-word ID is not found either.
*
* The reference sample keeps its own, wider pattern in
* scripts/test-sample-removal.ts: the template owns all of its files.
* The drill applies the same rule to a sample a project lists in
* scripts/lib/removable-template-features.ts.
*/
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
+126
View File
@@ -0,0 +1,126 @@
import { spawnSync } from "node:child_process";
import { cp, mkdtemp, rename, rm } from "node:fs/promises";
import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { localBuildEnvironment } from "./build-environment.ts";
import { linkFixtureNodeModules } from "./fixture-node-modules.ts";
import { REMOVAL_FIXTURE_COPY_TARGETS } from "./removal-fixture.ts";
/**
* 2026-11-07. The template ships no feature. What needs one in a real build
* runs on the feature `create:feature` writes, added to a copy of the
* repository: the browser checks that one feature works end to end (route,
* form, save, a save whose result is lost; tests/e2e/generated-feature.spec.ts
* and the chunk recovery spec, whose fixture builds take `addGeneratedFeature`
* as their edit) and the browser soak's failing-backend visits
* (scripts/scale/browser-soak.ts, `buildWithGeneratedFeature`). A change of
* the generator's output fails there. The `--keyed` write slice is the widest
* one the command makes.
*/
export const GENERATED_FEATURE_ID = "order-feature";
export type GeneratedRoute = Readonly<{
routeId: string;
path: string;
chunkId: string;
/** The lazy page's module id (`routeRuntimeContracts`), the name of its chunk. */
moduleId: string;
}>;
export type GeneratedFeature = Readonly<{
list: GeneratedRoute;
detail: GeneratedRoute;
create: GeneratedRoute;
/** The feature's ko-KR and en-US catalogs. */
messages: Readonly<Record<"ko-KR" | "en-US", Readonly<Record<string, string>>>>;
/** The collection the operations call: API_BASE_URL of the build plus the path. */
api: string;
}>;
function node(root: string, args: readonly string[]): string {
const result = spawnSync(process.execPath, args, { cwd: root, encoding: "utf8" });
if (result.status !== 0) {
throw new Error(`node ${args.join(" ")} failed in ${root}:\n${result.stdout}\n${result.stderr}`);
}
return result.stdout;
}
/** The edit of a fixture build: `corepack pnpm create:feature order-feature --with-create --keyed`. */
export async function addGeneratedFeature(root: string): Promise<void> {
node(root, ["scripts/generate-product-feature-index.ts"]);
node(root, ["scripts/create-feature.ts", GENERATED_FEATURE_ID, "--with-create", "--keyed"]);
}
/**
* What the specs need to drive the feature, read from the copy the command
* wrote it into (node runs that TypeScript as it is): the three routes, the
* words and where its API is.
*/
export function generatedFeature(root: string): GeneratedFeature {
const feature = path.join(root, "src/features", GENERATED_FEATURE_ID);
const module = (file: string) => JSON.stringify(pathToFileURL(path.join(feature, file)).href);
const source = `
const { ORDER_FEATURE_CONTRACT } = await import(${module("contracts/order-feature-contract.ts")});
const { ORDER_MESSAGE_CATALOGS } = await import(${module("contracts/order-message-catalog.ts")});
const { ORDER_LIST_ITEMS_CONTRACT } = await import(${module("contracts/order-contract-contribution.ts")});
const { API_BASE_URL } = JSON.parse(await (await import("node:fs/promises")).readFile("config/runtime/local.json", "utf8"));
const route = (id) => ({
routeId: id,
path: ORDER_FEATURE_CONTRACT.routes[id].path,
chunkId: ORDER_FEATURE_CONTRACT.routes[id].chunkId,
moduleId: ORDER_FEATURE_CONTRACT.routeRuntimeContracts[id].moduleId,
});
process.stdout.write(JSON.stringify({
list: route("ORDER_LIST"),
detail: route("ORDER_DETAIL"),
create: route("ORDER_CREATE"),
messages: ORDER_MESSAGE_CATALOGS,
api: new URL(ORDER_LIST_ITEMS_CONTRACT.contract.pathTemplate.slice(1), API_BASE_URL).href,
}));
`;
return JSON.parse(node(root, ["--input-type=module", "-e", source])) as GeneratedFeature;
}
/** A route's path with its one parameter filled in. */
export function routePath(route: GeneratedRoute, id?: string): string {
return id === undefined ? route.path : route.path.replace(/:[A-Za-z][A-Za-z0-9_]*/u, id);
}
/**
* A production build of a copy of the repository with the generated feature,
* in the local configuration. `remove` deletes the copy.
*/
export async function buildWithGeneratedFeature(prefix: string): Promise<
Readonly<{ dist: string; feature: GeneratedFeature; remove(): Promise<void> }>
> {
const root = await mkdtemp(path.join(tmpdir(), `${prefix}-`));
const remove = () => rm(root, { recursive: true, force: true });
try {
for (const entry of REMOVAL_FIXTURE_COPY_TARGETS) {
if (!existsSync(entry)) continue;
await cp(entry, path.join(root, entry), {
recursive: true,
filter: (source) => !source.includes(`${path.sep}.generated`),
});
}
await linkFixtureNodeModules(root);
await addGeneratedFeature(root);
const build = spawnSync(process.execPath, ["scripts/build-frontend.ts"], {
cwd: root,
encoding: "utf8",
env: localBuildEnvironment(),
});
if (build.status !== 0) {
throw new Error(`scripts/build-frontend.ts failed in ${root}:\n${build.stdout}\n${build.stderr}`);
}
const dist = path.join(root, "dist-generated-feature");
await rename(path.join(root, "dist"), dist);
return Object.freeze({ dist, feature: generatedFeature(root), remove });
} catch (error) {
await remove();
throw error;
}
}
+12 -39
View File
@@ -1,14 +1,16 @@
/**
* The features this template ships that a copied project may delete: the
* reference sample (README "Files you can delete after copying") and the
* example screens (docs/architecture/starter-experience.md, CHANGELOG "먼저
* 할 일" 6). Each owns its folder under `src/features/` and `tests/features/`
* and the context it is the only feature of. The reference sample also owns
* files outside them, which `scripts/test-sample-removal.ts` deletes with it.
* The sample features a project ships and may delete later: each owns its
* folder under `src/features/` and `tests/features/`, the context it is the
* only feature of, and possibly files and package scripts outside them.
*
* This is the one list. The removal drill reads the reference sample's paths
* and scripts from it, and the documentation check reads the whole of it: a
* feature counts as deleted once its `feature-module.ts` is gone.
* The template ships none: its reference sample and example screens were
* deleted on 2026-11-07, when the manual and `create:feature` took over their
* roles. A project that keeps a sample of its own lists it here. Then
* `test:sample-removal` without `--feature` (FE-GATE-020) deletes each one
* from a copy of the repository with these paths and scripts and runs the
* gates, and verify:documentation lets the documents name its paths until
* the sample is gone: a sample counts as deleted once its
* `feature-module.ts` is.
*/
export type RemovableTemplateFeature = Readonly<{
/** Its FEATURE_MODULE_ID, also its folder under src/features and tests/features. */
@@ -21,36 +23,7 @@ export type RemovableTemplateFeature = Readonly<{
scripts: readonly string[];
}>;
export const REMOVABLE_TEMPLATE_FEATURES: readonly RemovableTemplateFeature[] = Object.freeze([
Object.freeze({
featureId: "reference-feature",
contextDirectory: "src/contexts/reference-context",
// 0929/10-02. The HTTP scenario catalog (tests/mocks) and the negative
// type fixtures of the feature APIs run on the test contracts, so they
// are platform checks and stay (commonTestPaths in the drill).
extraPaths: Object.freeze([
"tests/component/product-feature-switch.test.tsx",
"tests/e2e/reference-form.spec.ts",
"tests/e2e/reference-route.spec.ts",
"tests/e2e/reference-save.spec.ts",
// 11-04: the growth measurement copies this sample feature.
"tests/unit/feature-shape-growth.test.ts",
"scripts/scale/measure-feature-shape-growth.ts",
"config/scale/feature-shape-growth.json",
"config/scale/feature-shape-ceilings.json",
]),
scripts: Object.freeze(["test:reference-feature"]),
}),
// 1103/09-04. The example screens /examples/ui, /examples/states and
// /examples/auth. The platform overview (/examples/platform) is a platform
// route and is not part of it.
Object.freeze({
featureId: "platform-examples-feature",
contextDirectory: "src/contexts/platform-examples-context",
extraPaths: Object.freeze([]),
scripts: Object.freeze([]),
}),
]);
export const REMOVABLE_TEMPLATE_FEATURES: readonly RemovableTemplateFeature[] = Object.freeze([]);
/** Every path removing `feature` deletes: its folders, its context and its extra files. */
export function removableTemplateFeaturePaths(feature: RemovableTemplateFeature): readonly string[] {
+3 -1
View File
@@ -40,7 +40,7 @@ export const REMOVAL_FIXTURE_COPY_TARGETS = Object.freeze([
/**
* This is the only copy-target list. Each removal script used to keep its own,
* and they drifted: the reference-feature fixture omitted
* and they drifted: the reference sample's fixture omitted
* `playwright.capabilities.config.ts`, which the repository file inventory
* requires, so supply-chain generation failed inside the fixture and took every
* provider suite down with it — twenty-odd failures with one cause.
@@ -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. */
+18
View File
@@ -113,15 +113,33 @@ export function checkoutBuildReadFailure(
/**
* The port variable of each Playwright config's web server. Unset, the config
* picks a free port; set, it uses that one (to pin a port while debugging).
* `visualWorkshop` is the visual config's second server, the static workshop
* the gallery goldens open.
*/
export const TEST_PORT_VARIABLES = Object.freeze({
e2e: "TEST_E2E_PORT",
visual: "TEST_VISUAL_PORT",
visualWorkshop: "TEST_VISUAL_WORKSHOP_PORT",
capabilities: "TEST_CAPABILITIES_PORT",
storybook: "TEST_STORYBOOK_PORT",
dev: "TEST_DEV_PORT",
} as const);
/**
* The origin of a config's second server, for its specs. The runner reserved
* the port in `variable` (reservePort) and its workers inherit it.
*/
export function reservedOrigin(
variable: string,
environment: Readonly<Record<string, string | undefined>> = process.env,
): string {
const port = environment[variable];
if (port === undefined || port === "") {
throw new Error(`${variable} is not set: run this spec through its Playwright config`);
}
return `http://127.0.0.1:${port}`;
}
/**
* A port nothing listens on now: the one the kernel gives a socket bound to
* port 0, which is closed again. Another process can still take it before the
+27
View File
@@ -0,0 +1,27 @@
import { testRunPath, testRunRoot } from "./run-isolation.ts";
/**
* The static workshop a Playwright config serves: the workshop tests
* (playwright.storybook.config.ts) and the gallery goldens
* (playwright.visual.config.ts) open the same build.
*
* 1105/12-04. Under TEST_RUN_ID the workshop is built into the run's own
* folder (.tmp/runs/<id>/artifacts/storybook/static) with build:storybook's
* two steps and another output folder. Unset, the gate's build:storybook
* writes artifacts/storybook/static.
*/
export function storybookStaticServer(port: number): Readonly<{
directory: string;
command: string;
}> {
const directory = testRunPath("artifacts/storybook/static");
const build =
testRunRoot() === "."
? "corepack pnpm build:storybook"
: "node scripts/generate-product-feature-index.ts && " +
`corepack pnpm exec storybook build -o ${directory}`;
return Object.freeze({
directory,
command: `${build} && node scripts/serve-static.ts ${directory} ${port}`,
});
}
+49 -34
View File
@@ -4,6 +4,7 @@ import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import path from "node:path";
import { buildWithGeneratedFeature } from "../lib/generated-feature.ts";
import {
classifyCounterSeries,
classifyMemorySlope,
@@ -13,8 +14,12 @@ import {
/**
* scale-architecture.md §33 / §44. Browser soak on the existing Playwright runner.
*
* Serves the built `dist/` on an OS-assigned 127.0.0.1 port and keeps one
* long-lived page cycling through the app's routes by client-side navigation.
* Serves a build on an OS-assigned 127.0.0.1 port and keeps one long-lived
* page cycling through the app's routes by client-side navigation. One of
* them is a feature's protected list (`featureRoute`), signed in once, whose
* reads fail. The template has no feature: by default the soak builds a copy
* with the one `create:feature` writes (scripts/lib/generated-feature.ts);
* `--dist` with `--feature-route` soaks a build of a product's own.
* The served runtime config turns telemetry on (pointed at a local collector)
* and points the API at a stub that always answers 503, so every cycle also
* exercises bounded retries and telemetry under a sustained backend failure.
@@ -51,9 +56,9 @@ export type SoakSummary = Readonly<{
storageKeyDelta: number;
storageByteDelta: number;
apiRequests: number;
referenceVisits: number;
settledReferenceVisits: number;
apiRequestsPerReferenceVisit: number;
featureVisits: number;
settledFeatureVisits: number;
apiRequestsPerFeatureVisit: number;
telemetryPosts: number;
telemetryEvents: number;
maxTelemetryPostsPerMinute: number;
@@ -83,7 +88,7 @@ export const SOAK_LIMITS = Object.freeze({
maxTimerDelta: 10,
maxStorageKeyDelta: 2,
/** One logical execution: 1 attempt + at most 2 retries. */
maxApiRequestsPerReferenceVisit: 3,
maxApiRequestsPerFeatureVisit: 3,
/** Two bounded pipelines (platform events + feature events) x 20/min. */
maxTelemetryPostsPerMinute: 40,
});
@@ -104,8 +109,8 @@ export function summarizeSoak(
export type SoakTotals = Readonly<{
cycles: number;
navigationFailures: number;
referenceVisits: number;
settledReferenceVisits: number;
featureVisits: number;
settledFeatureVisits: number;
finalInFlightRequests: number;
apiRequests: number;
telemetryPosts: number;
@@ -148,12 +153,12 @@ export function evaluateSoak(
storageKeyDelta: delta((sample) => sample.storageKeys),
storageByteDelta: delta((sample) => sample.storageBytes),
apiRequests: totals.apiRequests,
referenceVisits: totals.referenceVisits,
settledReferenceVisits: totals.settledReferenceVisits,
apiRequestsPerReferenceVisit:
totals.referenceVisits === 0
featureVisits: totals.featureVisits,
settledFeatureVisits: totals.settledFeatureVisits,
apiRequestsPerFeatureVisit:
totals.featureVisits === 0
? 0
: Math.round((totals.apiRequests / totals.referenceVisits) * 1_000) / 1_000,
: Math.round((totals.apiRequests / totals.featureVisits) * 1_000) / 1_000,
telemetryPosts: totals.telemetryPosts,
telemetryEvents: totals.telemetryEvents,
maxTelemetryPostsPerMinute,
@@ -192,15 +197,15 @@ export function evaluateSoak(
{
name: "backend failure exercised",
passed:
summary.settledReferenceVisits > 0 && summary.apiRequests > 0 && summary.telemetryEvents > 0,
detail: `${summary.settledReferenceVisits} settled visits, ${summary.apiRequests} API requests, ${summary.telemetryEvents} telemetry events`,
summary.settledFeatureVisits > 0 && summary.apiRequests > 0 && summary.telemetryEvents > 0,
detail: `${summary.settledFeatureVisits} settled visits, ${summary.apiRequests} API requests, ${summary.telemetryEvents} telemetry events`,
},
{
name: "request amplification",
passed:
summary.referenceVisits > 0 &&
summary.apiRequestsPerReferenceVisit <= SOAK_LIMITS.maxApiRequestsPerReferenceVisit,
detail: `${summary.apiRequests} requests / ${summary.referenceVisits} visits`,
summary.featureVisits > 0 &&
summary.apiRequestsPerFeatureVisit <= SOAK_LIMITS.maxApiRequestsPerFeatureVisit,
detail: `${summary.apiRequests} requests / ${summary.featureVisits} visits`,
},
{
name: "telemetry rate",
@@ -348,6 +353,8 @@ export async function runBrowserSoak(
intervalMs: number;
warmupMs: number;
routes: readonly string[];
/** A feature's protected list: signed in on, then visited with the rest. */
featureRoute: string;
}>,
): Promise<SoakArtifact> {
try {
@@ -397,13 +404,14 @@ export async function runBrowserSoak(
await page.addInitScript(PAGE_PROBES);
const cdp = await page.context().newCDPSession(page);
await cdp.send("Performance.enable");
await page.goto(`${baseUrl}/examples/reference-resources`, { waitUntil: "load" });
await page.goto(`${baseUrl}${options.featureRoute}`, { waitUntil: "load" });
await page.waitForSelector("#root > *", { timeout: 15_000 });
// Protected routes need a session: start the local demo session once, so
// the reference feature really dispatches its (failing) API requests.
const login = page.getByRole("button", { name: /로그인 시작|Sign in|Start sign-in/u });
if (await login.count()) {
await login.first().click();
// the feature really dispatches its (failing) API requests.
// The prompt draws once the feature's context routes have loaded.
const login = page.getByRole("button", { name: /로그인 시작|Sign in|Start sign-in/u }).first();
if (await login.waitFor({ timeout: 10_000 }).then(() => true, () => false)) {
await login.click();
await page.waitForTimeout(500);
}
@@ -412,8 +420,8 @@ export async function runBrowserSoak(
let nextSample = 0;
let cycles = 0;
let navigationFailures = 0;
let referenceVisits = 0;
let settledReferenceVisits = 0;
let featureVisits = 0;
let settledFeatureVisits = 0;
const probe = async () =>
(await page.evaluate(() =>
(window as unknown as { __soakProbe: () => Probe }).__soakProbe(),
@@ -421,7 +429,7 @@ export async function runBrowserSoak(
while (Date.now() - started < options.durationMs) {
const route = options.routes[cycles % options.routes.length] ?? "/";
cycles += 1;
if (route === "/examples/reference-resources") referenceVisits += 1;
if (route === options.featureRoute) featureVisits += 1;
// Client-side navigation keeps one long-lived document, like a real session.
await page.evaluate((target) => {
window.history.pushState({}, "", target);
@@ -436,10 +444,10 @@ export async function runBrowserSoak(
);
if (!rendered) navigationFailures += 1;
// Most visits leave after 50ms, which cancels the query (a cancelled
// request is intentionally not reported). Every 5th reference visit
// request is intentionally not reported). Every 5th feature visit
// dwells until its interaction settles, so the failing backend is really
// observed end to end: bounded retries, then feature/platform telemetry.
if (route === "/examples/reference-resources" && referenceVisits % 5 === 1) {
if (route === options.featureRoute && featureVisits % 5 === 1) {
await page.waitForTimeout(200);
await page
.waitForFunction(
@@ -448,7 +456,7 @@ export async function runBrowserSoak(
{ timeout: 5_000 },
)
.catch(() => undefined);
settledReferenceVisits += 1;
settledFeatureVisits += 1;
}
const elapsedMs = Date.now() - started;
if (elapsedMs >= nextSample) {
@@ -483,8 +491,8 @@ export async function runBrowserSoak(
{
cycles,
navigationFailures,
referenceVisits,
settledReferenceVisits,
featureVisits,
settledFeatureVisits,
finalInFlightRequests,
apiRequests: counters.apiRequests,
telemetryPosts: counters.telemetryPosts,
@@ -526,16 +534,23 @@ async function main(): Promise<void> {
const argument = (name: string, fallback: string) =>
process.argv.find((entry) => entry.startsWith(`--${name}=`))?.slice(name.length + 3) ?? fallback;
const artifact = path.resolve(argument("artifact", "artifacts/scale/browser-soak.json"));
const ownBuild = argument("dist", "");
const generated = ownBuild === "" ? await buildWithGeneratedFeature("browser-soak") : undefined;
const featureRoute = generated ? generated.feature.list.path : argument("feature-route", "");
if (featureRoute === "") {
throw new Error("--dist needs --feature-route=<a feature's protected list path in that build>");
}
const result = await runBrowserSoak({
distRoot: argument("dist", "dist"),
distRoot: generated?.dist ?? ownBuild,
durationMs: Number(argument("duration-ms", "60000")),
intervalMs: Number(argument("interval-ms", "5000")),
warmupMs: Number(argument("warmup-ms", "15000")),
routes: argument(
"routes",
"/,/examples/reference-resources,/examples/platform,/examples/ui,/examples/states,/examples/reference-resources/status",
["/", featureRoute, "/examples/platform", generated?.feature.create.path ?? "/not-found"].join(","),
).split(","),
});
featureRoute,
}).finally(() => generated?.remove());
await mkdir(path.dirname(artifact), { recursive: true });
await writeFile(artifact, `${JSON.stringify(result, null, 2)}\n`);
process.stdout.write(
+137 -105
View File
@@ -1,10 +1,12 @@
import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { availableParallelism, cpus, loadavg, tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { gzipSync } from "node:zlib";
import { PLATFORM_ROUTE_REGISTRY } from "../../src/contracts/routes.ts";
import { planFeature, type InstalledFacts } from "../create-feature.ts";
import { classifyViteJavascript } from "../lib/classify-vite-bundle.ts";
import { linkFixtureNodeModules } from "../lib/fixture-node-modules.ts";
import { VITE_BUILD_INPUTS } from "../lib/vite-build-inputs.ts";
@@ -12,11 +14,13 @@ import { parseTscExtendedDiagnostics, type TscDiagnostics } from "./collect-tsc-
/**
* 11-04 (D-18). Cost of one app as its feature count grows, measured with
* features shaped like the real one: `src/features/reference-feature` copied N
* times with every feature-owned identifier renamed (feature id, route ids and
* paths, API operations, schemas, query namespace, invalidation topic,
* messages). The copies live in contexts of their own (200 features each, the
* context ceiling) so the reference context is unchanged.
* features shaped like a real one: N copies of the feature `create:feature`
* writes with `--with-create --keyed` (a list, a detail and a create with its
* form), each planned by the command's own planner (`planFeature`) with its
* own ids and its own pinned contract package. The copies live in contexts of
* their own, 200 features each (the context ceiling the baseline records).
* 2026-11-07: the copies were the template's reference sample, renamed; the
* template ships no sample now.
*
* For each N the script runs the product generator, `tsc --extendedDiagnostics`
* over tsconfig.app.json and `vite build`, and records compiler counts, wall
@@ -36,70 +40,102 @@ export const FEATURE_SHAPE_BASELINE_PATH = "config/scale/feature-shape-growth.js
/** What the declared ceilings rest on, derived by hand from the baseline. */
export const FEATURE_SHAPE_CEILINGS_PATH = "config/scale/feature-shape-ceilings.json";
const SOURCE_FEATURE = "src/features/reference-feature";
const FEATURES_PER_CONTEXT = 200;
// Platform-owned names that only happen to contain "reference".
const PLATFORM_TOKENS = [
"REFERENCE_FEATURE_V1",
"supportReference",
] as const;
/** The command each copy is, as the baseline records it. */
export const SHAPE_FEATURE_COMMAND = "create:feature <id> --with-create --keyed";
export const FEATURES_PER_CONTEXT = 200;
/** Renames every feature-owned identifier of the reference feature for copy `id`. */
export function renameReferenceFeature(
text: string,
id: string,
context: Readonly<{ id: string; routeRoot: string }>,
): string {
const upper = id.toUpperCase();
// 1101/07-04. Assembly refuses the reference fixture source in any other
// feature, so a copy pins an external package and declares it in its
// contracts, as a product feature would.
const contractPackage = [
"Object.freeze({",
` packageId: "@feature-shape/${id}",`,
' version: "1.0.0",',
' digest: `sha256:${"0".repeat(64)}`,',
" runtimeProtocolVersion: 1 as const,",
' sourceRevision: "0000000",',
" })",
].join("\n");
let renamed = text
.replace(
/source: Object\.freeze\(\{\s*kind: "TEMPLATE_FIXTURE" as const,\s*fixtureId: "REFERENCE_FEATURE_V1" as const,\s*revision: 1 as const,\s*\}\)/u,
`source: Object.freeze({\n kind: "EXTERNAL_PACKAGE" as const,\n package: ${contractPackage},\n })`,
)
.replace(
"contractPackages: Object.freeze([]),",
`contractPackages: Object.freeze([${contractPackage}]),`,
/** Copy `index`: its feature id and the context it lands in. */
export function shapeFeature(index: number, featuresPerContext = FEATURES_PER_CONTEXT) {
const contextNumber = Math.floor(index / featuresPerContext);
return Object.freeze({
id: `s${String(index).padStart(3, "0")}-feature`,
context: Object.freeze({ id: `shape-context-${contextNumber}`, routeRoot: `shape-${contextNumber}` }),
});
}
function contextModule(context: Readonly<{ id: string; routeRoot: string }>): string {
return (
`export const CONTEXT_MODULE_ID = "${context.id}";\n` +
`export const CONTEXT_APP_ID = "template-app";\n` +
`export const CONTEXT_ROUTE_PATH = "${context.routeRoot}/*";\n` +
`export const CONTEXT_MAX_FEATURES = ${FEATURES_PER_CONTEXT};\n`
);
}
/**
* The source files of `features` copies: the context declarations and what
* `create:feature` writes under src/features (its tests and accessibility
* records are not part of a build). Each copy pins `@feature-shape/<id>`, as
* a product feature pins its published package, and gets a topic of its own.
*/
export function planShapeFeatures(
features: number,
featuresPerContext = FEATURES_PER_CONTEXT,
): ReadonlyMap<string, string> {
const files = new Map<string, string>();
const contexts: { id: string; routePath: string }[] = [];
const routes: InstalledFacts["routes"][number][] = Object.values(PLATFORM_ROUTE_REGISTRY).map(
(route) => ({
routeId: route.routeId,
path: route.path,
chunkId: route.chunkId,
navigationOrder: route.navigationOrder,
}),
);
const featureIds: string[] = [];
const topics: string[] = [];
for (let index = 0; index < features; index += 1) {
const { id, context } = shapeFeature(index, featuresPerContext);
if (index % featuresPerContext === 0) {
contexts.push({ id: context.id, routePath: `${context.routeRoot}/*` });
files.set(`src/contexts/${context.id}/context-module.ts`, contextModule(context));
}
const navigationOrder =
Math.max(0, ...routes.flatMap((route) => (route.navigationOrder === null ? [] : [route.navigationOrder]))) + 10;
const plan = planFeature(
{
id,
context: context.id,
write: "KEYED",
contractPackage: {
packageId: `@feature-shape/${id}`,
version: "1.0.0",
digest: `sha256:${"0".repeat(64)}`,
sourceRevision: "0000000",
},
},
{
appIds: ["template-app"],
featureIds,
contexts,
contextDirectories: contexts.map((declared) => declared.id),
routes,
topics,
messageKeys: [],
},
() => String(index).padStart(26, "0"),
);
PLATFORM_TOKENS.forEach((token, index) => {
renamed = renamed.replaceAll(token, `\u0000${index}\u0000`);
});
renamed = renamed
.replaceAll("/examples/reference-resources", `/${context.routeRoot}/${id}-resources`)
.replaceAll("qinv.01k10f7m3w9p6r2c8v5n4x", `qinv.shape.${id}`)
.replaceAll("NoRequest", `${upper}NoRequest`)
.replaceAll("reference-context", context.id)
.replaceAll("REFERENCE", upper)
.replaceAll("Reference", upper)
.replaceAll("reference", id);
PLATFORM_TOKENS.forEach((token, index) => {
renamed = renamed.replaceAll(`\u0000${index}\u0000`, token);
});
return renamed;
}
async function copyRenamed(from: string, to: string, rename: (text: string) => string) {
await mkdir(to, { recursive: true });
for (const entry of await readdir(from, { withFileTypes: true })) {
const source = path.join(from, entry.name);
const target = path.join(to, rename(entry.name));
if (entry.isDirectory()) await copyRenamed(source, target, rename);
else await writeFile(target, rename(await readFile(source, "utf8")));
for (const [file, content] of plan.files) {
if (file.startsWith("src/")) files.set(file, content);
}
featureIds.push(id);
topics.push(plan.topic);
for (const route of plan.routes) {
routes.push({
routeId: route.routeId,
path: route.path,
chunkId: `${route.routeId}-chunk`,
navigationOrder: route.routeId === plan.routeId ? navigationOrder : null,
});
}
}
return files;
}
async function createFixture(features: number): Promise<string> {
async function createFixture(
features: number,
featuresPerContext = FEATURES_PER_CONTEXT,
): Promise<string> {
const root = await mkdtemp(path.join(tmpdir(), `feature-shape-${features}-`));
for (const input of VITE_BUILD_INPUTS) {
await mkdir(path.dirname(path.join(root, input)), { recursive: true });
@@ -107,26 +143,9 @@ async function createFixture(features: number): Promise<string> {
}
await rm(path.join(root, "src/.generated"), { recursive: true, force: true });
await linkFixtureNodeModules(root);
for (let index = 0; index < features; index += 1) {
const contextNumber = Math.floor(index / FEATURES_PER_CONTEXT);
const context = { id: `shape-context-${contextNumber}`, routeRoot: `shape-${contextNumber}` };
if (index % FEATURES_PER_CONTEXT === 0) {
const contextFile = path.join(root, "src/contexts", context.id, "context-module.ts");
await mkdir(path.dirname(contextFile), { recursive: true });
await writeFile(
contextFile,
`export const CONTEXT_MODULE_ID = "${context.id}";\n` +
`export const CONTEXT_APP_ID = "template-app";\n` +
`export const CONTEXT_ROUTE_PATH = "${context.routeRoot}/*";\n` +
`export const CONTEXT_MAX_FEATURES = ${FEATURES_PER_CONTEXT};\n`,
);
}
const id = `s${String(index).padStart(3, "0")}`;
await copyRenamed(
path.resolve(SOURCE_FEATURE),
path.join(root, "src/features", `${id}-feature`),
(text) => renameReferenceFeature(text, id, context),
);
for (const [file, content] of planShapeFeatures(features, featuresPerContext)) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
}
return root;
}
@@ -166,15 +185,15 @@ async function javascriptGzipBytes(root: string, files: readonly string[]) {
}
/**
* 15-01. Initial JavaScript of the app with `features` reference copies
* added: the generator and `vite build` only, no typecheck. The unit suite
* 15-01. Initial JavaScript of the app with `features` copies added: the generator and `vite build` only, no typecheck. The unit suite
* (merge stage) bounds what one more feature adds to the initial chunk with
* it, so the growth is caught on the PR instead of at the next release.
*/
async function measureInitialJavascript(
features: number,
featuresPerContext = FEATURES_PER_CONTEXT,
): Promise<Readonly<{ gzipBytes: number; files: number }>> {
const root = await createFixture(features);
const root = await createFixture(features, featuresPerContext);
try {
run(process.execPath, [path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`], root);
run(path.resolve("node_modules/.bin/vite"), ["build", "--logLevel", "error"], root);
@@ -187,17 +206,20 @@ async function measureInitialJavascript(
}
/**
* 1103/15-02, 15-04. The template's initial JavaScript and what one more
* feature and one more context add to it. The first copy lands in a new
* context (shape-context-0) and the second in the same one, so the second
* copy is a feature alone and the rest of the first is the context.
* `initialJavascript` in config/scale/feature-shape-ceilings.json records
* these numbers; tests/unit/feature-shape-growth.test.ts compares them with
* the build on every unit run.
* 1103/15-02, 15-04. The template's initial JavaScript and what features add
* to it. Two copies in one context against one copy are one more feature
* alone; the same two copies in two contexts against that are one more
* context. 2026-11-07: the template has no feature, so the first copy also
* brings the code every feature shares into the initial chunks; that is
* `firstFeatureGzipBytes`, paid once. `initialJavascript` in
* config/scale/feature-shape-ceilings.json records these numbers;
* tests/unit/feature-shape-growth.test.ts compares them with the build on
* every unit run.
*/
export type InitialJavascriptCosts = Readonly<{
gzipBytes: number;
files: number;
firstFeatureGzipBytes: number;
perFeatureGzipBytes: number;
perContextGzipBytes: number;
}>;
@@ -205,13 +227,14 @@ export type InitialJavascriptCosts = Readonly<{
export async function measureInitialJavascriptCosts(): Promise<InitialJavascriptCosts> {
const none = await measureInitialJavascript(0);
const one = await measureInitialJavascript(1);
const two = await measureInitialJavascript(2);
const perFeatureGzipBytes = two.gzipBytes - one.gzipBytes;
const twoInOneContext = await measureInitialJavascript(2);
const twoInTwoContexts = await measureInitialJavascript(2, 1);
return {
gzipBytes: none.gzipBytes,
files: none.files,
perFeatureGzipBytes,
perContextGzipBytes: one.gzipBytes - none.gzipBytes - perFeatureGzipBytes,
firstFeatureGzipBytes: one.gzipBytes - none.gzipBytes,
perFeatureGzipBytes: twoInOneContext.gzipBytes - one.gzipBytes,
perContextGzipBytes: twoInTwoContexts.gzipBytes - twoInOneContext.gzipBytes,
};
}
@@ -228,10 +251,18 @@ export const INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES = 256;
/**
* Fields of the record that no longer describe the build. The total may be
* INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES off; the per-feature and
* per-context costs are differences of builds with the same id but only a
* few hundred bytes, so 10%; the file count is exact.
* INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES off; the first-feature,
* per-feature and per-context costs are differences of builds with the same
* id, so 10%, and at least COST_RECORD_TOLERANCE_BYTES: a context costs a few
* bytes now, and gzip moves a difference that small by a byte or two when
* the build id changes. The file count is exact.
*/
export const COST_RECORD_TOLERANCE_BYTES = 16;
function costTolerance(bytes: number): number {
return Math.max(Math.abs(bytes) * 0.1, COST_RECORD_TOLERANCE_BYTES);
}
export function initialJavascriptRecordDrift(
measured: InitialJavascriptCosts,
record: InitialJavascriptCosts,
@@ -239,8 +270,9 @@ export function initialJavascriptRecordDrift(
const allowed: Readonly<Record<keyof InitialJavascriptCosts, number>> = {
gzipBytes: INITIAL_JAVASCRIPT_RECORD_TOLERANCE_BYTES,
files: 0,
perFeatureGzipBytes: Math.abs(measured.perFeatureGzipBytes) * 0.1,
perContextGzipBytes: Math.abs(measured.perContextGzipBytes) * 0.1,
firstFeatureGzipBytes: costTolerance(measured.firstFeatureGzipBytes),
perFeatureGzipBytes: costTolerance(measured.perFeatureGzipBytes),
perContextGzipBytes: costTolerance(measured.perContextGzipBytes),
};
return (Object.keys(allowed) as (keyof InitialJavascriptCosts)[])
.filter((field) => Math.abs(record[field] - measured[field]) > allowed[field])
@@ -393,7 +425,7 @@ async function main(): Promise<void> {
vite: version("vite"),
},
source,
sourceFeature: SOURCE_FEATURE,
sourceFeature: SHAPE_FEATURE_COMMAND,
runs,
};
const output = process.argv.includes("--write")
+2 -2
View File
@@ -71,8 +71,8 @@ try {
if (created.passed && createdWrite.passed) {
// The generator's Next: 3. A project re-records the initial JavaScript
// with its features (config/scale/feature-shape-ceilings.json, which
// test:unit compares with a build) and commits it with them. Without the
// sample there is no record to keep.
// test:unit compares with a build) and commits it with them. A project
// that deleted the measurement has no record to keep.
const measurement = "scripts/scale/measure-feature-shape-growth.ts";
if (existsSync(path.join(fixtureRoot, measurement))) {
const recorded = spawnSync(process.execPath, [measurement, "--initial-baseline", "--write"], {
+93 -67
View File
@@ -8,8 +8,10 @@ import {
} from "node:fs/promises";
import { spawnSync } from "node:child_process";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { ROUTE_FEATURE_OWNER } from "../src/features/installed-feature-contracts.ts";
import { loadCiGateContract } from "./contracts/ci-gates.ts";
import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts";
import { productFeatureResidue } from "./lib/feature-residue.ts";
import { isProductionModulePath } from "./lib/risk-coverage.ts";
@@ -32,42 +34,92 @@ import {
import { REMOVABLE_TEMPLATE_FEATURES } from "./lib/removable-template-features.ts";
/**
* 09-07 (D-10). Removes one installed feature, `--feature=<id>` (default: the
* reference sample), from a copy of the repository and proves the rest still
* typechecks, tests, covers and builds. Every feature loses its directory, its
* tests/features directory, its context when no other feature is left in it,
* its runtime-profile override and its central policy rows. The sample also
* owns the extra paths and scripts listed in SAMPLE_EXTRAS.
* 09-07 (D-10). Removes one installed feature, `--feature=<id>`, from a copy
* of the repository and proves the rest still typechecks, tests, covers and
* builds. Every feature loses its directory, its tests/features directory,
* its context when no other feature is left in it, its runtime-profile
* override and its central policy rows. A sample that
* scripts/lib/removable-template-features.ts lists also loses its extra paths
* and package scripts, with the CI evidence only those scripts produce, and
* the copy then gets a feature from create:feature and runs the gates again.
*
* Without `--feature` (FE-GATE-020) each listed sample is removed in turn.
* The template lists none since its samples were deleted (2026-11-07): the
* run then reports the drill as skipped, not passed, and test:feature-scaffold
* removes a generated feature through `--feature`.
*/
const featureId =
process.argv.find((argument) => argument.startsWith("--feature="))
?.slice("--feature=".length) ?? "reference-feature";
const SAMPLE_REPORT = "artifacts/tests/sample-removal.xml";
const requestedFeature = process.argv
.find((argument) => argument.startsWith("--feature="))
?.slice("--feature=".length);
if (requestedFeature === undefined) {
const checks: RemovalCheck[] = REMOVABLE_TEMPLATE_FEATURES.map((sample) => {
const status = spawnSync(
process.execPath,
[fileURLToPath(import.meta.url), `--feature=${sample.featureId}`],
{ stdio: "inherit" },
).status;
return status === 0
? { name: sample.featureId, passed: true }
: {
name: sample.featureId,
passed: false,
failure: `test:sample-removal -- --feature=${sample.featureId} exited ${status ?? "on a signal"}`,
};
});
await mkdir("artifacts/tests", { recursive: true });
if (checks.length === 0) {
await writeFile(
SAMPLE_REPORT,
`<?xml version="1.0" encoding="UTF-8"?>\n` +
`<testsuite name="sample-removal" tests="1" failures="0" skipped="1">` +
`<testcase name="listed-samples"><skipped message="scripts/lib/removable-template-features.ts lists no sample" /></testcase>` +
`</testsuite>\n`,
);
process.stdout.write(
"sample removal: SKIP (scripts/lib/removable-template-features.ts lists no sample; " +
"test:feature-scaffold removes a generated feature with --feature)\n",
);
} else {
await writeFile(SAMPLE_REPORT, renderRemovalJunit("sample-removal", checks));
if (checks.some((check) => !check.passed)) process.exitCode = 1;
}
process.exit();
}
const featureId: string = requestedFeature;
type FeatureExtras = Readonly<{
paths: readonly string[];
ciScripts: readonly string[];
evidencePathFragments: readonly string[];
residue: RegExp;
}>;
// The sample's own files and scripts outside its folders are declared with
// the other removable template features, which verify:documentation reads too.
const REFERENCE_SAMPLE = REMOVABLE_TEMPLATE_FEATURES.find(
(feature) => feature.featureId === "reference-feature",
);
if (REFERENCE_SAMPLE === undefined) {
throw new Error("scripts/lib/removable-template-features.ts does not declare reference-feature");
/** The CI evidence that only `scripts` produce: it goes with them. */
async function evidenceOnlyFrom(scripts: readonly string[]): Promise<string[]> {
if (scripts.length === 0) return [];
const contract = await loadCiGateContract(process.cwd());
const commandIds = new Set(
contract.commands.filter(({ script }) => scripts.includes(script)).map(({ id }) => id),
);
return contract.artifacts.flatMap((artifact) =>
artifact.production === "command-generated" &&
artifact.producerCommandIds.length > 0 &&
artifact.producerCommandIds.every((commandId) => commandIds.has(commandId))
? [artifact.path]
: [],
);
}
const SAMPLE_EXTRAS: Readonly<Record<string, FeatureExtras>> = Object.freeze({
"reference-feature": Object.freeze({
paths: REFERENCE_SAMPLE.extraPaths,
ciScripts: REFERENCE_SAMPLE.scripts,
evidencePathFragments: [
"reference-feature.xml",
],
residue: /REFERENCE_RESOURCE|reference-feature|reference-resource/i,
}),
// The sample's own files and scripts outside its folders, which
// verify:documentation reads too.
const listedSample = REMOVABLE_TEMPLATE_FEATURES.find(
(feature) => feature.featureId === featureId,
);
const extras: FeatureExtras = Object.freeze({
paths: listedSample?.extraPaths ?? [],
ciScripts: listedSample?.scripts ?? [],
evidencePathFragments: await evidenceOnlyFrom(listedSample?.scripts ?? []),
});
function escapeRegExp(value: string): string {
@@ -106,15 +158,6 @@ async function locateFeature(id: string) {
}
const located = await locateFeature(featureId);
const extras: FeatureExtras = SAMPLE_EXTRAS[featureId] ?? Object.freeze({
paths: [],
ciScripts: [],
evidencePathFragments: [],
residue: new RegExp(
`${escapeRegExp(featureId)}|${escapeRegExp(located.directory)}`,
"i",
),
});
// Captured from this repository before the copy loses them.
const featureRouteIds = Object.entries(ROUTE_FEATURE_OWNER)
.filter(([, owner]) => owner === featureId)
@@ -124,7 +167,7 @@ const fixtureRoot = await createRemovalFixtureRoot(`${featureId}-removal`);
const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath");
const featureSource = `src/features/${located.directory}`;
const featureTests = `tests/features/${located.directory}`;
const isSample = featureId in SAMPLE_EXTRAS;
const isSample = listedSample !== undefined;
/**
* Platform tests that must survive the sample feature's removal. Asserting they
* are still present is what stops the removal fixture from "passing" by having
@@ -281,12 +324,6 @@ try {
const retainedCriticalModules = coveragePolicy.criticalModules.filter(
(modulePolicy) => !modulePolicy.path?.startsWith(`${featureSource}/`),
);
if (
isSample &&
retainedCriticalModules.length === coveragePolicy.criticalModules.length
) {
throw new Error("Reference feature coverage policy is not registered");
}
coveragePolicy.criticalModules = retainedCriticalModules;
coveragePolicy.highRiskPaths = coveragePolicy.highRiskPaths.filter(
(modulePath) => !modulePath.startsWith(`${featureSource}/`),
@@ -299,7 +336,7 @@ try {
);
coveragePolicy.repositoryBaseline -= removedProductionModuleCount;
if (coveragePolicy.repositoryBaseline <= 0) {
throw new Error("Reference feature removal produced an invalid coverage baseline");
throw new Error(`${featureId} removal produced an invalid coverage baseline`);
}
await writeFile(
coveragePolicyFile,
@@ -400,7 +437,7 @@ try {
// JavaScript of the features installed now, and test:unit compares a build
// with it. A product re-records it when it adds a feature; removing that
// feature changes it again, so the fixture re-records it as the product
// would. The sample removal deletes the measurement with the sample.
// would.
const measurement = path.join(fixtureRoot, "scripts/scale/measure-feature-shape-growth.ts");
if (await access(measurement).then(() => true, () => false)) {
const measured = spawnSync(
@@ -414,22 +451,13 @@ try {
}
await regenerateRemovalFixtureWorkflow(fixtureRoot);
const residue: string[] = [];
if (isSample) {
for (const root of ["src", "tests"]) {
for (const file of await filesBelow(path.join(fixtureRoot, root))) {
const relative = path.relative(fixtureRoot, file);
const content = await readFile(file, "utf8");
if (extras.residue.test(`${relative}\n${content}`)) {
residue.push(relative);
}
}
}
} else {
// 1105/16-04. Template tests use example feature IDs as data; only what
// still points at the removed feature counts (scripts/lib/feature-residue.ts).
residue.push(...(await productFeatureResidue(fixtureRoot, featureId, located.directory)));
}
// 1105/16-04. Template tests use example feature IDs as data; only what
// still points at the removed feature counts (scripts/lib/feature-residue.ts).
const residue = await productFeatureResidue(fixtureRoot, featureId, located.directory);
const builtResiduePattern = new RegExp(
`${escapeRegExp(featureId)}|${escapeRegExp(located.directory)}`,
"i",
);
const missingCommonTests: string[] = [];
for (const testPath of commonTestPaths) {
@@ -471,7 +499,7 @@ try {
for (const file of await filesBelow(path.join(fixtureRoot, "dist"))) {
if (!/\.(?:js|css|html|json)$/.test(file)) continue;
const content = await readFile(file, "utf8");
if (extras.residue.test(content)) {
if (builtResiduePattern.test(content)) {
builtResidue.push(path.relative(fixtureRoot, file));
}
}
@@ -493,9 +521,9 @@ try {
outcome("built-fixture-id-residue", builtResidue, "built residue"),
);
// U7 (decision 4). The same copy, now without the sample, gets one feature
// from create:feature and runs the same gates again: the command and the
// feature it writes need nothing from the sample.
// U7 (decision 4). The same copy, now without the listed sample, gets one
// feature 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.
@@ -513,9 +541,7 @@ try {
const failed = checks.filter((entry) => !entry.passed);
await mkdir("artifacts/tests", { recursive: true });
await writeFile(
isSample
? "artifacts/tests/sample-removal.xml"
: `artifacts/tests/feature-removal-${featureId}.xml`,
`artifacts/tests/feature-removal-${featureId}.xml`,
renderRemovalJunit(`${featureId}-removal`, checks),
);
if (failed.length > 0) {
+6 -9
View File
@@ -187,15 +187,12 @@ const gateIds = new Set([
).gates.map((gate) => gate.id),
...RETIRED_GATE_IDS,
]);
// 1105/14-01. A copy may delete the template features listed in
// scripts/lib/removable-template-features.ts, and the CHANGELOG tells
// tech-log to delete the example screens. The documents are the template's:
// a product that edited them to drop the feature's paths would conflict on
// every sync. While a feature is installed (its feature-module.ts exists),
// its paths and scripts are checked like any other; once it is not, they are
// not drift. tech-log keeps the reference sample's folder with its contracts
// but without its module, screens and tests (CHANGELOG "먼저 할 일" 1). A
// misspelt feature folder is not on the list and still fails.
// 1105/14-01. A copy may delete the sample features listed in
// scripts/lib/removable-template-features.ts (the template lists none since
// 2026-11-07). The documents may name a sample's paths: while it is installed
// (its feature-module.ts exists), its paths and scripts are checked like any
// other; once it is not, they are not drift. A misspelt feature folder is not
// on the list and still fails.
const removedTemplateFeatures = REMOVABLE_TEMPLATE_FEATURES.filter(
(feature) => !exists(`src/features/${feature.featureId}/feature-module.ts`),
);
-1
View File
@@ -35,7 +35,6 @@ export const EXTREME_SCALE_GATES = Object.freeze([
"check:observability",
"check:release-coherence",
"test:platform",
"test:reference-feature",
"check:scale:pr",
"check:scale:main",
"check:scale:baseline",
@@ -1,12 +0,0 @@
/**
* 1103/09-04. The template's example screens (UI gallery, screen states,
* auth integration) as one removable bounded context. A product leaves
* `platform-examples-feature` out of `VITE_PRODUCT_FEATURES`, or deletes it,
* and the three routes leave the registry, the navigation, the bundle and the
* manual accessibility list together. The root is `examples/*`; the sample
* feature's own context keeps a more specific path below it.
*/
export const CONTEXT_MODULE_ID = "platform-examples-context";
export const CONTEXT_APP_ID = "template-app";
export const CONTEXT_ROUTE_PATH = "examples/*";
export const CONTEXT_MAX_FEATURES = 1;
@@ -1,10 +0,0 @@
/**
* Ownership declaration of the reference bounded context (the rules are in
* docs/architecture/starter-experience.md, "Ownership declarations"): the app
* that owns it, its route root, and its direct-feature budget. Features name
* this id as their owner.
*/
export const CONTEXT_MODULE_ID = "reference-context";
export const CONTEXT_APP_ID = "template-app";
export const CONTEXT_ROUTE_PATH = "examples/reference-resources/*";
export const CONTEXT_MAX_FEATURES = 200;
@@ -1,6 +0,0 @@
local-draft is an architecture sample for the indexedDb feature capability, not
a product feature. It has no feature-module.ts on purpose, so the index
generator (scripts/generate-product-feature-index.ts) leaves it out; its
composition is exercised by tests/contract/reusable-capability and
recipes/frontend-capabilities/indexeddb-feature-capability.ts. To install it,
add feature-module.ts and context-routes.ts and delete this file.
@@ -1,17 +0,0 @@
import type { RouteObject } from "react-router-dom";
import { PLATFORM_EXAMPLES_CONTRACT } from "./contracts/platform-examples-contract.ts";
import { PLATFORM_EXAMPLES_ROUTE_RUNTIME } from "./presentation/platform-examples-runtime.ts";
export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze(
Object.values(PLATFORM_EXAMPLES_CONTRACT.routes).map((definition) =>
Object.freeze({
id: definition.routeId,
path: definition.path,
handle: Object.freeze({
routeId: definition.routeId,
runtime: PLATFORM_EXAMPLES_ROUTE_RUNTIME[definition.routeId],
}),
}),
),
);
@@ -1,82 +0,0 @@
export const PLATFORM_EXAMPLES_FEATURE_ID = "platform-examples-feature";
/**
* 1103/09-04. Three of the template's example screens, formerly fixed
* platform routes. The platform overview (`EXAMPLES_PLATFORM`) stays a
* platform route: the lab gate (FE-GATE-026) times entering it, and a feature
* route's first entry costs a second request round (its context's routes
* module, then the page). Paths, chunk ids and surfaces are unchanged: the
* visual and e2e tests and the manual accessibility records still name them.
* Declaration only, so it holds data; the pages load with `context-routes.ts`.
*/
export const PLATFORM_EXAMPLES_CONTRACT = Object.freeze({
featureId: PLATFORM_EXAMPLES_FEATURE_ID,
routes: Object.freeze({
EXAMPLES_UI: Object.freeze({
routeId: "EXAMPLES_UI",
path: "/examples/ui",
paramsSchema: null,
searchSchema: null,
access: "public",
loadingSurface: "example-page",
errorSurface: "route-boundary",
chunkId: "route-examples-ui",
title: "UI 구성요소",
navigationLabel: "UI 구성요소",
navigationOrder: 20,
}),
EXAMPLES_STATES: Object.freeze({
routeId: "EXAMPLES_STATES",
path: "/examples/states",
paramsSchema: null,
searchSchema: null,
access: "public",
loadingSurface: "example-page",
errorSurface: "route-boundary",
chunkId: "route-examples-states",
title: "화면 상태",
navigationLabel: "화면 상태",
navigationOrder: 30,
}),
EXAMPLES_AUTH: Object.freeze({
routeId: "EXAMPLES_AUTH",
path: "/examples/auth",
paramsSchema: null,
searchSchema: null,
access: "public",
loadingSurface: "example-page",
errorSurface: "route-boundary",
chunkId: "route-examples-auth",
title: "인증 연동",
navigationLabel: "인증 연동",
navigationOrder: 40,
}),
}),
routeRuntimeContracts: Object.freeze({
EXAMPLES_UI: Object.freeze({
routeId: "EXAMPLES_UI",
moduleId: "ui-gallery-page",
paramsCodec: "none",
searchCodec: "none",
}),
EXAMPLES_STATES: Object.freeze({
routeId: "EXAMPLES_STATES",
moduleId: "state-gallery-page",
paramsCodec: "none",
searchCodec: "none",
}),
EXAMPLES_AUTH: Object.freeze({
routeId: "EXAMPLES_AUTH",
moduleId: "auth-example-page",
paramsCodec: "none",
searchCodec: "none",
}),
}),
invalidation: Object.freeze({
topics: Object.freeze([]),
namespaces: Object.freeze([]),
edges: Object.freeze([]),
}),
topicVersions: Object.freeze([]),
contractPackages: Object.freeze([]),
} as const);
@@ -1,23 +0,0 @@
/**
* 1103/09-04. The route titles and navigation labels the shell reads; they
* moved here from the platform catalog with the routes. The pages' own copy
* stays Korean in every locale (08-07).
*/
export const PLATFORM_EXAMPLES_MESSAGE_CATALOGS = Object.freeze({
"ko-KR": Object.freeze({
"route.EXAMPLES_UI.navigation": "UI 구성요소",
"route.EXAMPLES_UI.title": "UI 구성요소",
"route.EXAMPLES_STATES.navigation": "화면 상태",
"route.EXAMPLES_STATES.title": "화면 상태",
"route.EXAMPLES_AUTH.navigation": "인증 연동",
"route.EXAMPLES_AUTH.title": "인증 연동",
}),
"en-US": Object.freeze({
"route.EXAMPLES_UI.navigation": "UI components",
"route.EXAMPLES_UI.title": "UI components",
"route.EXAMPLES_STATES.navigation": "Screen states",
"route.EXAMPLES_STATES.title": "Screen states",
"route.EXAMPLES_AUTH.navigation": "Authentication",
"route.EXAMPLES_AUTH.title": "Authentication",
}),
} as const);
@@ -1,27 +0,0 @@
import { defineFeatureModule } from "../feature-module.ts";
import {
PLATFORM_EXAMPLES_CONTRACT,
PLATFORM_EXAMPLES_FEATURE_ID,
} from "./contracts/platform-examples-contract.ts";
import { PLATFORM_EXAMPLES_MESSAGE_CATALOGS } from "./contracts/platform-examples-message-catalog.ts";
export const FEATURE_MODULE_ID =
"platform-examples-feature" satisfies typeof PLATFORM_EXAMPLES_FEATURE_ID;
/** Owning bounded context (route root and budget live in its declaration). */
export const FEATURE_CONTEXT_ID = "platform-examples-context";
/**
* 1103/09-04. The template's example screens as a feature, so the product's
* feature selection, `FEATURE_OVERRIDES`, the removal drill and the manual
* accessibility list apply to them like to any feature. Declaration only:
* the pages load with the context routes, and the runtime half is empty.
*/
export const PLATFORM_EXAMPLES_FEATURE_MODULE = defineFeatureModule({
id: FEATURE_MODULE_ID,
contracts: PLATFORM_EXAMPLES_CONTRACT,
routes: PLATFORM_EXAMPLES_CONTRACT.routes,
messages: PLATFORM_EXAMPLES_MESSAGE_CATALOGS,
loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME,
} as const);
export const FEATURE_MODULE = PLATFORM_EXAMPLES_FEATURE_MODULE;
@@ -1,13 +0,0 @@
import { defineFeatureRuntime } from "../feature-module.ts";
import { PLATFORM_EXAMPLES_FEATURE_ID } from "./contracts/platform-examples-contract.ts";
/**
* 1103/09-04. The example screens call no feature API: they show the
* design system and the shell's session. The runtime half is empty.
*/
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: PLATFORM_EXAMPLES_FEATURE_ID,
schemas: Object.freeze({}),
adapters: [],
contractContributions: [],
} as const);
@@ -1,61 +0,0 @@
import { PageHeader } from "../../../presentation/design-system/index.ts";
import {
useSession,
useSessionAction,
} from "../../../presentation/providers/session-provider.tsx";
export default function AuthExamplePage() {
const { sessionState } = useSession();
const { pending, failed, run } = useSessionAction();
return (
// 08-07. Example copy is Korean in every locale (outside the catalog).
<section className="ui-page" lang="ko-KR">
<PageHeader
title="인증 연동"
description="스켈레톤은 자격 증명을 소유하지 않고 외부 인증 구현이 연결될 포트와 화면 상태만 제공합니다."
/>
<section className="ui-panel auth-example" aria-labelledby="auth-state-title">
<div>
<h2 id="auth-state-title">현재 세션 상태</h2>
<output className="session-status" data-state={sessionState}>
{sessionState}
</output>
</div>
<div className="button-row">
<button
className="ui-button"
type="button"
disabled={pending || sessionState === "integration-failed"}
onClick={() => run("sign-in")}
>
로그인 시작
</button>
<button
className="ui-button ui-button--secondary"
type="button"
disabled={pending || sessionState !== "authenticated"}
onClick={() => run("sign-out")}
>
로그아웃
</button>
<button
className="ui-button ui-button--secondary"
type="button"
disabled={pending || sessionState !== "recovery-pending"}
onClick={() => run("recover")}
>
세션 복구
</button>
</div>
{sessionState === "integration-failed" ? (
<p role="status">
외부 인증 소유자가 연결되지 않았습니다. 런타임 호스트의 인증
계약을 연결하세요.
</p>
) : null}
{failed ? <p role="alert">인증 작업을 완료하지 못했습니다.</p> : null}
</section>
</section>
);
}
@@ -1,17 +0,0 @@
import { lazy } from "react";
/** One lazy chunk per example page, as when they were platform routes. */
export const PLATFORM_EXAMPLES_ROUTE_RUNTIME = {
EXAMPLES_UI: Object.freeze({
moduleId: "ui-gallery-page",
Component: lazy(() => import("./ui-gallery-page.tsx")),
}),
EXAMPLES_STATES: Object.freeze({
moduleId: "state-gallery-page",
Component: lazy(() => import("./state-gallery-page.tsx")),
}),
EXAMPLES_AUTH: Object.freeze({
moduleId: "auth-example-page",
Component: lazy(() => import("./auth-example-page.tsx")),
}),
} as const;
@@ -1,101 +0,0 @@
import { useState } from "react";
import { deriveAsyncState } from "../../../application/view-models/async-state.ts";
import { createFailure } from "../../../contracts/errors.ts";
import {
AsyncSurface,
EmptySurface,
LoadingSurface,
TerminalErrorSurface,
AuthRequiredSurface,
ForbiddenSurface,
NotFoundSurface,
Button,
Card,
PageHeader,
} from "../../../presentation/design-system/index.ts";
export default function StateGalleryPage() {
const [lastAction, setLastAction] = useState(
"상태 화면의 작업을 선택하면 결과가 여기에 표시됩니다.",
);
const refreshingState = deriveAsyncState({
data: ["기존 데이터"],
isFetching: true,
});
return (
// 08-07. Example copy is Korean in every locale (outside the catalog).
<section className="ui-page" lang="ko-KR">
<PageHeader
title="화면 상태"
description="로딩, 빈 화면, 오류, 인증 필요와 권한 없음 상태가 다음 행동까지 일관되게 안내합니다."
/>
<section className="gallery-section" aria-labelledby="async-states-title">
<header className="gallery-section__header">
<h2 id="async-states-title">비동기 데이터 상태</h2>
<p>초기 로딩과 백그라운드 갱신을 구분해 기존 콘텐츠를 보존합니다.</p>
</header>
<div className="component-grid component-grid--two">
<Card title="초기 로딩">
<LoadingSurface label="예제 데이터를 불러오는 중" />
</Card>
<Card title="백그라운드 갱신">
<AsyncSurface headingLevel={4} state={refreshingState}>
<div className="state-preview-content">기존 콘텐츠는 계속 표시됩니다.</div>
</AsyncSurface>
</Card>
<Card title="빈 화면">
<EmptySurface
headingLevel={4}
title="아직 표시할 항목이 없습니다."
description="첫 항목을 추가하거나 필터를 초기화할 수 있습니다."
action={
<Button onClick={() => setLastAction("빈 화면 작업을 실행했습니다.")}>
첫 작업 시작
</Button>
}
/>
</Card>
<Card title="복구 가능한 오류">
<TerminalErrorSurface
headingLevel={4}
userMessageKey={
createFailure("NETWORK_UNREACHABLE", "EXAMPLE", 0)
.userMessageKey
}
action="retry"
onAction={() => setLastAction("오류 요청을 다시 시도했습니다.")}
/>
</Card>
</div>
</section>
<section className="gallery-section" aria-labelledby="access-states-title">
<header className="gallery-section__header">
<h2 id="access-states-title">접근과 탐색 상태</h2>
<p>인증 여부와 서버 권한 결과를 서로 다른 상태로 전달합니다.</p>
</header>
<div className="component-grid component-grid--three">
<AuthRequiredSurface
headingLevel={3}
onSignIn={() => setLastAction("로그인 연동 작업을 시작했습니다.")}
/>
<ForbiddenSurface
headingLevel={3}
onNavigate={() => setLastAction("접근 가능한 화면으로 이동합니다.")}
/>
<NotFoundSurface
headingLevel={3}
onNavigate={() => setLastAction("시작 화면으로 이동합니다.")}
/>
</div>
</section>
<output className="gallery-notice" aria-live="polite">
{lastAction}
</output>
</section>
);
}
-92
View File
@@ -1,92 +0,0 @@
# Reference feature ownership and removal
이 모듈은 제품 도메인이 아니라 새 기능의 수직 경계를 검증하는 제거 가능한
reference implementation이다.
## 소유 경계
- `domain`: 외부 DTO와 React를 모르는 불변 model
- `application`: UI가 호출하는 list/get/create input과 gateway 계약
- `adapters`: HTTP executor를 gateway로 투영하는 outbound adapter
- `contracts`: route/API/query contribution, Zod DTO와 request schema, mapper
- `presentation`: route input을 query/form controller로 연결하는 inbound
adapter, 독립 form schema/command mapper와 list/detail/form/status page
generic application은 비어 있는 `ApplicationFeatureInputs`와 typed
`features.has/get/load` registry만 소유한다. input은 reference route에 처음
들어갈 때 router가 `features.load`로 실행부를 적재한 뒤에 생긴다. 이 feature의 application API가 module
augmentation으로 `"reference-feature": ReferenceFeatureInput`을 기여하므로
등록되지 않은 ID와 잘못된 input shape는 typecheck에서 거절된다. feature hook은
별도 cast나 runtime shape 확인 없이 정확한 input type을 받는다. 다만 동적 호출로
설치되지 않은 ID가 들어오는 경우를 위해 `get`의 runtime guard도 유지한다.
예측 가능한 실패는 canonical shared contract인
`src/contracts/result.ts`의 `Result<Value, Failure = AppFailure>`로 반환한다.
`src/application/result.ts`는 기존 호출자를 위한 deprecated migration shim일
뿐 새 코드의 import 경로가 아니다. `AppFailure.kind`는
`ERROR_REGISTRY` key에서 파생된 닫힌 vocabulary다. 폐기된 별칭 `ApiFailure`
대신 `AppFailure`를 import한다(lint가 막는다). mapper는 `boundary-mapper.ts`의
`BoundaryMappingResult`를 반환한다.
HTTP adapter는 `src/adapters/http/feature-http-binding.ts`의 capability-specific
typed binding을 사용한다. feature는 operation ID, route ID, request type, 성공
value type, mapper만 소유한다. timeout/cancellation/auth/transport/contract
violation을 `AppFailure`로 정규화하는 책임은 reusable HTTP capability가 소유한다.
따라서 gateway 메서드는 transport outcome이나 runtime result guard를 반복 구현하지
않고도 정확한 결과 타입을 반환한다.
route codec과 URL builder는 `src/presentation/routes/route-codecs.ts`, route type은
`route-contract.ts`, React context/provider/hook은 `route-input.tsx`가 각각
소유한다. reference page는 `app-router.tsx`를 역참조하지 않고 좁은
`useRouteInput` 경계만 사용하므로 lazy route와 router 사이의 순환 의존을 만들지
않는다. page는 HTTP client, storage, auth owner, output port나 TanStack API를
직접 import하지 않는다.
page는 경로 문자열을 적지 않는다. 경로는 계약의 `path` 한 곳에만 있다.
`presentation/reference-routes.ts`가 다음 helper를 둔다. 이 기능의 route codec은
`presentation/reference-route-codecs.ts`에 있다.
- 링크: `referenceRouteUrl(routeId, { params, search })`. 위 `buildRouteUrl`에
이 기능의 codec을 넘긴다.
- route 입력: `useReferenceListFilters()`, `useReferenceResourceId()`. 이미
통과한 codec으로 다시 읽어 cast 없이 타입을 얻는다.
## 설치 지점
feature가 실제 contribution을 소유한다.
- 선언(초기 청크, `feature-module.ts`): route 표와 invalidation은
`reference-feature-contract.ts`, 문구는 `reference-message-catalog.ts`
- 실행부(`feature-runtime.ts`, reference route에 들어갈 때 적재): 스키마 메타데이터
`reference-schema-metadata.ts`, bootstrap input
`REFERENCE_FEATURE_ADAPTER_CONTRIBUTION`, HTTP contract contribution
- route codec과 page component: `REFERENCE_FEATURE_ROUTE_CODECS`,
`REFERENCE_FEATURE_ROUTE_RUNTIME` (`context-routes.ts`가 route handle에 실어
lazy로 적재)
`feature-module.ts`는 `feature-runtime.ts`를 동적 import로만 가리킨다. 정적
import로 바꾸면 실행부 전체가 다시 초기 청크에 들어간다(15-01). 중앙 파일인
`installed-feature-contracts.ts`, `installed-feature-adapters.ts`,
`installed-contract-contributions.ts`는 선택된 contribution을 합치는 역할만
한다. 새 기능의 내부 조립 규칙을 중앙 catalog에 추가하지 않는다.
## 검증과 제거
```sh
corepack pnpm test:reference-feature
corepack pnpm test:sample-removal
```
첫 명령은 URL filter와 query key/HTTP request의 동일성, schema/mapper, 모든
query/mutation/form 상태와 production composition을 검증한다. 두 번째 명령은 임시
복제본에서 이 source/test 디렉터리를 제거하고 installed catalog를 빈 목록으로
재생성한다. feature 소유 coverage include, risk-policy 행과 test-evidence
contribution도 제거한 뒤 typecheck, architecture, registry, unit/integration,
coverage, source evidence, home smoke, production build와 source/built fixture ID
잔여 0개를 검사한다. generic feature registry의 성공 경로는 reference와 무관한
unit test가 소유하므로 feature 삭제 후에도 공통 boundary coverage가 유지된다.
CI의 negative type fixture는 잘못된 feature ID/input shape, registry에 없는
failure kind, operation과 route ID의 불일치가 실제로 컴파일 실패하는지도
검증한다. Architecture fixture는 허용 edge뿐 아니라 unresolved import, 금지 계층
edge와 TypeScript 순환 의존을 각각 거절해야 통과한다.
@@ -1,50 +0,0 @@
import {
createFeatureHttpBinding,
type InstalledHttpOperationExecutor,
} from "../../../adapters/http/index.ts";
import {
defineFeatureAdapterContribution,
} from "../../feature-adapter-contribution.ts";
import { createReferenceFeatureInput } from "../application/reference-feature-api.ts";
import type { TelemetryPort } from "../../../platform/telemetry/telemetry-port.ts";
import {
REFERENCE_FEATURE_ID,
} from "../contracts/reference-feature-contract.ts";
import {
createReferenceHttpGateway,
REFERENCE_HTTP_OPERATIONS,
} from "./reference-http-gateway.ts";
export type InstalledContractOperationExecutor =
InstalledHttpOperationExecutor;
/**
* Feature-owned composition seam.
*
* The feature receives only the HTTP capability it declares in `needs`.
* HTTP lifecycle/error normalization stays in the reusable capability binding.
*/
export function createReferenceFeatureInstalledInput(context: Readonly<{
http: InstalledHttpOperationExecutor;
telemetry?: TelemetryPort;
}>) {
const http = createFeatureHttpBinding(
context.http,
REFERENCE_HTTP_OPERATIONS,
);
return Object.freeze({
featureId: REFERENCE_FEATURE_ID,
input: createReferenceFeatureInput(
createReferenceHttpGateway(http),
context.telemetry === undefined ? {} : { telemetry: context.telemetry },
),
});
}
export const REFERENCE_FEATURE_ADAPTER_CONTRIBUTION =
defineFeatureAdapterContribution({
featureId: REFERENCE_FEATURE_ID,
needs: ["http", "telemetry"] as const,
createInput: createReferenceFeatureInstalledInput,
});
@@ -1,92 +0,0 @@
import {
defineFeatureHttpOperationForRoutes,
type FeatureHttpBinding,
} from "../../../adapters/http/index.ts";
import {
CREATE_REFERENCE_RESOURCE_CONTRACT,
GET_REFERENCE_RESOURCE_CONTRACT,
LIST_REFERENCE_RESOURCES_CONTRACT,
} from "../contracts/reference-feature-contract-contribution.ts";
import {
REFERENCE_FEATURE_CONTRACT,
} from "../contracts/reference-feature-contract.ts";
import {
mapReferenceResourceListPayload,
mapReferenceResourcePayload,
} from "../contracts/reference-mapper.ts";
import type {
ReferenceGateway,
} from "../application/reference-feature-api.ts";
export type ReferenceFeatureRouteId =
keyof typeof REFERENCE_FEATURE_CONTRACT.routes;
const defineReferenceHttpOperation =
defineFeatureHttpOperationForRoutes<ReferenceFeatureRouteId>();
export const REFERENCE_HTTP_OPERATIONS = Object.freeze({
LIST_REFERENCE_RESOURCES: defineReferenceHttpOperation({
contract: LIST_REFERENCE_RESOURCES_CONTRACT,
routeId: "REFERENCE_RESOURCE_LIST",
mapSuccess: mapReferenceResourceListPayload,
}),
CREATE_REFERENCE_RESOURCE: defineReferenceHttpOperation({
contract: CREATE_REFERENCE_RESOURCE_CONTRACT,
routeId: "REFERENCE_RESOURCE_LIST",
mapSuccess: mapReferenceResourcePayload,
mapProblem(problem, metadata) {
if (metadata.status === 409) {
return Object.freeze({
kind: "CONFLICT" as const,
code: problem.code ?? "REFERENCE_RESOURCE_CONFLICT",
});
}
// 백엔드 1101/02-01. The paired backend's answer to a key outside its
// rule. The executor checked the key before sending, so this names a
// rule mismatch between the two sides: 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 ?? "REFERENCE_RESOURCE_REJECTED",
validationIssues: problem.issues ?? [],
});
}
return undefined;
},
}),
GET_REFERENCE_RESOURCE: defineReferenceHttpOperation({
contract: GET_REFERENCE_RESOURCE_CONTRACT,
routeId: "REFERENCE_RESOURCE_DETAIL",
mapSuccess: mapReferenceResourcePayload,
}),
} as const);
export type ReferenceHttpBinding = FeatureHttpBinding<
typeof REFERENCE_HTTP_OPERATIONS
>;
export function createReferenceHttpGateway(
http: ReferenceHttpBinding,
): ReferenceGateway {
return Object.freeze({
list(filters, context) {
return http.execute("LIST_REFERENCE_RESOURCES", filters, context);
},
create(command, context) {
return http.execute("CREATE_REFERENCE_RESOURCE", command, context);
},
get(resourceId, context) {
return http.execute(
"GET_REFERENCE_RESOURCE",
Object.freeze({ resourceId }),
context,
);
},
});
}
@@ -1,71 +0,0 @@
import {
defineAppError,
type AppError,
} from "../../../platform/errors/app-error.ts";
import type { AppFailure } from "../../../contracts/errors.ts";
/**
* scale-architecture.md §17–§19. The reference feature's own domain errors.
*
* This union is local to the feature. It satisfies the platform `AppError`
* envelope structurally; nothing central enumerates it, so adding or removing
* this feature never edits a shared error type.
*/
export type ReferenceError =
| (AppError & {
readonly kind: "reference.not-found";
readonly category: "domain";
readonly severity: "warning";
readonly retryability: "never";
})
| (AppError & {
readonly kind: "reference.conflict";
readonly category: "domain";
readonly severity: "warning";
readonly retryability: "never";
})
| (AppError & {
readonly kind: "reference.rejected";
readonly category: "validation";
readonly severity: "warning";
readonly retryability: "never";
});
export const REFERENCE_ERRORS = Object.freeze({
NOT_FOUND: defineAppError({
kind: "reference.not-found",
category: "domain",
severity: "warning",
retryability: "never",
}),
CONFLICT: defineAppError({
kind: "reference.conflict",
category: "domain",
severity: "warning",
retryability: "never",
}),
REJECTED: defineAppError({
kind: "reference.rejected",
category: "validation",
severity: "warning",
retryability: "never",
}),
} satisfies Record<string, ReferenceError>);
/**
* Interprets a transport-normalized failure in this feature's own vocabulary.
* Anything that is not a reference domain outcome stays `null`: the platform
* error mapping, not this feature, owns transport/contract failures.
*/
export function toReferenceError(failure: AppFailure): ReferenceError | null {
switch (failure.kind) {
case "NOT_FOUND":
return REFERENCE_ERRORS.NOT_FOUND;
case "CONFLICT":
return REFERENCE_ERRORS.CONFLICT;
case "VALIDATION_REJECTED":
return REFERENCE_ERRORS.REJECTED;
default:
return null;
}
}
@@ -1,137 +0,0 @@
import type { Result } from "../../../contracts/result.ts";
import type {} from "../../../application/ports/in/application-api.ts";
import {
toReferenceView,
type ReferenceResourceView,
} from "../contracts/reference-mapper.ts";
import type { ReferenceResource } from "../domain/reference-resource.ts";
import type { MutationIntent } from "../../../contracts/mutation-intent.ts";
import type { ExecutionContext } from "../../../platform/execution/execution-context.ts";
import type { TelemetryPort } from "../../../platform/telemetry/telemetry-port.ts";
import type { AppFailure } from "../../../contracts/errors.ts";
import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts";
/**
* scale-architecture.md §10. Every call may join a caller-owned interaction so several
* operations share one request/retry/concurrency budget and one deadline.
*/
export type ReferenceCallContext = Readonly<{
signal?: AbortSignal;
execution?: ExecutionContext;
}>;
export type ReferenceListFilters = Readonly<{
cursor?: string;
limit: number;
tags?: readonly string[];
}>;
export type ReferenceResult<Value> = Result<Value>;
export type ReferenceCreateCommand = Readonly<{
name: string;
note?: string;
}>;
export type ReferenceFeatureInput = Readonly<{
listResources(
filters: ReferenceListFilters,
context?: ReferenceCallContext,
): Promise<ReferenceResult<readonly ReferenceResourceView[]>>;
createResource(
command: ReferenceCreateCommand,
context?: ReferenceCallContext & Readonly<{ intent?: MutationIntent }>,
): Promise<ReferenceResult<ReferenceResourceView>>;
getResource(
resourceId: string,
context?: ReferenceCallContext,
): Promise<ReferenceResult<ReferenceResourceView>>;
}>;
declare module "../../../application/ports/in/application-api.ts" {
interface ApplicationFeatureInputs {
"reference-feature": ReferenceFeatureInput;
}
}
export type ReferenceGateway = Readonly<{
list(
filters: ReferenceListFilters,
context?: ReferenceCallContext,
): Promise<ReferenceResult<readonly ReferenceResource[]>>;
create(
command: ReferenceCreateCommand,
context?: ReferenceCallContext & Readonly<{ intent?: MutationIntent }>,
): Promise<ReferenceResult<ReferenceResource>>;
get(
resourceId: string,
context?: ReferenceCallContext,
): Promise<ReferenceResult<ReferenceResource>>;
}>;
/**
* scale-architecture.md §24. Feature-owned telemetry payload. The platform envelope carries it;
* no central union lists it. Only the bounded failure kind leaves the feature.
*/
export type ReferenceLoadFailedPayload = Readonly<{
operation: "list" | "detail";
reason: AppFailure["kind"];
}>;
function reportLoadFailure(
telemetry: TelemetryPort | undefined,
operation: ReferenceLoadFailedPayload["operation"],
failure: AppFailure,
context: ReferenceCallContext | undefined,
): void {
if (!telemetry || failure.kind === "REQUEST_ABORTED") return;
const payload: ReferenceLoadFailedPayload = { operation, reason: failure.kind };
try {
// Fire-and-forget: telemetry never changes the business result.
void Promise.resolve(
telemetry.emit({
kind: "reference.load.failed",
severity: "warning",
featureId: REFERENCE_FEATURE_ID,
...(context?.execution === undefined
? {}
: { interactionId: context.execution.interaction.id }),
payload,
}),
).catch(() => undefined);
} catch {
// A throwing port is contained at the call site (scale-architecture.md §26).
}
}
export function createReferenceFeatureInput(
gateway: ReferenceGateway,
observability: Readonly<{ telemetry?: TelemetryPort }> = {},
): ReferenceFeatureInput {
const { telemetry } = observability;
return Object.freeze({
async listResources(filters, context) {
const result = await gateway.list(filters, context);
if (!result.ok) reportLoadFailure(telemetry, "list", result.error, context);
return result.ok
? {
ok: true as const,
value: result.value.map((resource) => toReferenceView(resource)),
}
: result;
},
async createResource(command, context) {
const result = await gateway.create(command, context);
return result.ok
? { ok: true as const, value: toReferenceView(result.value) }
: result;
},
async getResource(resourceId, context) {
const result = await gateway.get(resourceId, context);
if (!result.ok) reportLoadFailure(telemetry, "detail", result.error, context);
return result.ok
? { ok: true as const, value: toReferenceView(result.value) }
: result;
},
});
}
@@ -1,23 +0,0 @@
import type { RouteObject } from "react-router-dom";
import { REFERENCE_FEATURE_CONTRACT } from "./contracts/reference-feature-contract.ts";
import { REFERENCE_FEATURE_ROUTE_RUNTIME } from "./presentation/reference-feature-runtime.ts";
import { REFERENCE_FEATURE_ROUTE_CODECS } from "./presentation/reference-route-codecs.ts";
export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze(
Object.values(REFERENCE_FEATURE_CONTRACT.routes).map((definition) => {
const runtime = REFERENCE_FEATURE_ROUTE_RUNTIME[
definition.routeId as keyof typeof REFERENCE_FEATURE_ROUTE_RUNTIME
];
return Object.freeze({
id: definition.routeId,
path: definition.path,
handle: Object.freeze({
routeId: definition.routeId,
runtime,
// 15-01. The route's params/search codecs load with its routes.
codecs: REFERENCE_FEATURE_ROUTE_CODECS,
}),
});
}),
);
@@ -1,252 +0,0 @@
import { z } from "../../../contracts/zod.ts";
import type {
CommandEffectDescriptor,
InstalledContractContribution,
InstalledHttpContract,
} from "../../../contracts/external-contract-runtime.ts";
import { zodValidator } from "../../../contracts/zod-validator.ts";
import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts";
import {
createReferenceResourceCommandSchema,
referenceProblemSchema,
referenceResourceDtoSchema,
referenceResourceListQuerySchema,
referenceResourceParamsSchema,
type ReferenceProblem,
} from "./reference-schemas.ts";
export type { ReferenceProblem } from "./reference-schemas.ts";
/**
* §4.8. The single `TEMPLATE_FIXTURE` contribution. It keeps the reference
* HTTP vertical executable as deterministic template data and is excluded from
* `contractSet`. A product feature MUST instead pin an external package and
* import it from its own `contracts/<service>-contract-contribution.ts`.
*/
const PROBLEM_VALIDATOR = zodValidator(
"ReferenceProblem",
referenceProblemSchema,
);
/**
* 0929/03-01. A 409 does not by itself mean "refused": a resend with the same
* key can meet the first attempt still running (the paired backend answers
* `409 IDEMPOTENT_IN_FLIGHT`). Only the conflict codes this fixture declares
* are `NOT_APPLIED`; any other 409 stays `MAYBE_APPLIED`, so the coordinator
* keeps the intent and the next send reuses the key. Answering `NOT_APPLIED`
* there would let the next save mint a new key and create the resource twice.
*/
const CREATE_NOT_APPLIED_CONFLICT_CODES: ReadonlySet<string> = new Set([
"CONFLICT",
]);
/**
* Fixture-side classifier standing in for the package-provided pure bounded
* classifier. A status the fixture does not describe stays `MAYBE_APPLIED`.
*/
const CREATE_EFFECT: CommandEffectDescriptor<ReferenceProblem> = Object.freeze({
successEffect: "APPLIED_CONFIRMED" as const,
classifyProblem({
status,
problem,
}: Readonly<{ status: number; problem: ReferenceProblem }>) {
if (status === 400 || status === 422) return "NOT_APPLIED";
if (
status === 409 &&
problem.code !== undefined &&
CREATE_NOT_APPLIED_CONFLICT_CODES.has(problem.code)
) {
return "NOT_APPLIED";
}
return "MAYBE_APPLIED";
},
/**
* D-2. The reference backend rejects an unauthenticated, forbidden or
* rate-limited create before touching state.
*/
classifyStatus: () => "NOT_APPLIED" as const,
});
export const LIST_REFERENCE_RESOURCES_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "LIST_REFERENCE_RESOURCES",
method: "GET" as const,
pathTemplate: "/api/reference-resources",
inputValidator: zodValidator(
"ReferenceResourceListQuery",
referenceResourceListQuerySchema,
),
outputValidator: zodValidator(
"ReferenceResourceListPayload",
z.array(referenceResourceDtoSchema).max(100),
),
problemValidator: PROBLEM_VALIDATOR,
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "NONE" as const,
commandRecovery: null,
commandEffect: null,
projectRequest(input: z.output<typeof referenceResourceListQuerySchema>) {
const entries: (readonly [string, string])[] = [];
if (input.cursor !== undefined) entries.push(["cursor", input.cursor]);
entries.push(["limit", String(input.limit)]);
for (const tag of input.tags ?? []) entries.push(["tags", tag]);
return Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze(entries),
body: null,
});
},
}),
frontend: Object.freeze({
policyId: "REFERENCE_LIST_V1",
requestByteLimit: 0,
responseByteLimit: 262_144,
totalDeadlineMs: 10_000,
retryBudget: 2 as const,
authProfileId: "EXTERNAL_BEARER",
diagnosticsOperation: "reference.list",
traffic: Object.freeze({
maxPhysicalRequests: 3,
maxRetries: 2,
maxConcurrentRequests: 1,
maxQueuedRequests: 0,
}),
}),
}) satisfies InstalledHttpContract<
z.output<typeof referenceResourceListQuerySchema>,
readonly z.output<typeof referenceResourceDtoSchema>[],
ReferenceProblem
>;
export const GET_REFERENCE_RESOURCE_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "GET_REFERENCE_RESOURCE",
method: "GET" as const,
pathTemplate: "/api/reference-resources/{resourceId}",
inputValidator: zodValidator(
"ReferenceResourceParams",
referenceResourceParamsSchema,
),
outputValidator: zodValidator(
"ReferenceResourcePayload",
referenceResourceDtoSchema,
),
problemValidator: PROBLEM_VALIDATOR,
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "NONE" as const,
commandRecovery: null,
commandEffect: null,
projectRequest(input: z.output<typeof referenceResourceParamsSchema>) {
return Object.freeze({
pathValues: Object.freeze({ resourceId: input.resourceId }),
queryEntries: Object.freeze([]),
body: null,
});
},
}),
frontend: Object.freeze({
policyId: "REFERENCE_DETAIL_V1",
requestByteLimit: 0,
responseByteLimit: 32_768,
totalDeadlineMs: 10_000,
retryBudget: 2 as const,
authProfileId: "EXTERNAL_BEARER",
diagnosticsOperation: "reference.detail",
traffic: Object.freeze({
maxPhysicalRequests: 3,
maxRetries: 2,
maxConcurrentRequests: 1,
maxQueuedRequests: 0,
}),
}),
}) satisfies InstalledHttpContract<
z.output<typeof referenceResourceParamsSchema>,
z.output<typeof referenceResourceDtoSchema>,
ReferenceProblem
>;
export const CREATE_REFERENCE_RESOURCE_CONTRACT = Object.freeze({
contract: Object.freeze({
operationId: "CREATE_REFERENCE_RESOURCE",
method: "POST" as const,
pathTemplate: "/api/reference-resources",
inputValidator: zodValidator(
"CreateReferenceResourceCommand",
createReferenceResourceCommandSchema,
),
outputValidator: zodValidator(
"ReferenceResourcePayload",
referenceResourceDtoSchema,
),
problemValidator: PROBLEM_VALIDATOR,
acceptedStatuses: Object.freeze([200, 201]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "KEYED" as const,
requestBody: "JSON" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "NONE" as const,
commandRecovery: Object.freeze({
mode: "IDEMPOTENCY_REPLAY" as const,
operationIdentityField: "idempotencyKey",
}),
commandEffect: CREATE_EFFECT,
projectRequest(input: z.output<typeof createReferenceResourceCommandSchema>) {
return Object.freeze({
pathValues: Object.freeze({}),
queryEntries: Object.freeze([]),
body: Object.freeze({ ...input }),
});
},
}),
frontend: Object.freeze({
policyId: "REFERENCE_CREATE_V1",
requestByteLimit: 32_768,
responseByteLimit: 32_768,
totalDeadlineMs: 10_000,
/**
* §8.3. A KEYED command has no automatic retry after a dispatched attempt
* lost its response; the fixture therefore declares a zero budget rather
* than relying on a runtime special case.
*/
retryBudget: 0 as const,
authProfileId: "EXTERNAL_BEARER",
diagnosticsOperation: "reference.create",
traffic: Object.freeze({
maxPhysicalRequests: 1,
maxRetries: 0,
maxConcurrentRequests: 1,
maxQueuedRequests: 0,
}),
}),
}) satisfies InstalledHttpContract<
z.output<typeof createReferenceResourceCommandSchema>,
z.output<typeof referenceResourceDtoSchema>,
ReferenceProblem
>;
export const REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION: InstalledContractContribution =
Object.freeze({
contributionId: "reference-feature-http-v1",
featureId: REFERENCE_FEATURE_ID,
source: Object.freeze({
kind: "TEMPLATE_FIXTURE" as const,
fixtureId: "REFERENCE_FEATURE_V1" as const,
revision: 1 as const,
}),
http: Object.freeze([
LIST_REFERENCE_RESOURCES_CONTRACT,
GET_REFERENCE_RESOURCE_CONTRACT,
CREATE_REFERENCE_RESOURCE_CONTRACT,
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
events: Object.freeze([]),
});
@@ -1,120 +0,0 @@
import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts";
import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts";
export const REFERENCE_FEATURE_ID = "reference-feature";
export const REFERENCE_RESOURCE_QUERY_NAMESPACE = defineQueryNamespaceIdentity(
"reference-resource",
1,
);
export const REFERENCE_RESOURCE_INVALIDATION_TOPIC =
defineQueryInvalidationTopic("qinv.01k10f7m3w9p6r2c8v5n4x");
/**
* 15-01. The declaration half: what the shell reads before a reference route
* is entered. It is in the initial chunk, so it holds data only. The schema
* metadata is `reference-schema-metadata.ts` and the HTTP operations are
* `reference-feature-contract-contribution.ts`, both loaded with
* `feature-runtime.ts`.
*/
export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
featureId: REFERENCE_FEATURE_ID,
routes: Object.freeze({
REFERENCE_RESOURCE_LIST: Object.freeze({
routeId: "REFERENCE_RESOURCE_LIST",
path: "/examples/reference-resources",
paramsSchema: null,
searchSchema: "ReferenceResourceListQuery",
access: "session-required",
loadingSurface: "reference-resource-list",
errorSurface: "feature-boundary",
chunkId: "route-reference-resources",
title: "Reference feature",
navigationLabel: "Reference feature",
navigationOrder: 50,
}),
REFERENCE_RESOURCE_DETAIL: Object.freeze({
routeId: "REFERENCE_RESOURCE_DETAIL",
// 08-13. `items/` keeps an id such as `new` or `status` off the static routes.
path: "/examples/reference-resources/items/:resourceId",
paramsSchema: "ReferenceResourceParams",
searchSchema: null,
access: "session-required",
loadingSurface: "reference-resource-detail",
errorSurface: "feature-boundary",
chunkId: "route-reference-resource-detail",
title: "Reference detail",
navigationLabel: null,
navigationOrder: null,
}),
REFERENCE_RESOURCE_FORM: Object.freeze({
routeId: "REFERENCE_RESOURCE_FORM",
path: "/examples/reference-resources/new",
paramsSchema: null,
searchSchema: null,
access: "session-required",
loadingSurface: "reference-resource-form",
errorSurface: "feature-boundary",
chunkId: "route-reference-resource-form",
title: "Reference form",
navigationLabel: null,
navigationOrder: null,
}),
REFERENCE_RESOURCE_STATUS: Object.freeze({
routeId: "REFERENCE_RESOURCE_STATUS",
path: "/examples/reference-resources/status",
paramsSchema: null,
searchSchema: null,
access: "session-required",
loadingSurface: "reference-resource-status",
errorSurface: "feature-boundary",
chunkId: "route-reference-resource-status",
title: "Reference status",
navigationLabel: null,
navigationOrder: null,
}),
}),
routeRuntimeContracts: Object.freeze({
REFERENCE_RESOURCE_LIST: Object.freeze({
routeId: "REFERENCE_RESOURCE_LIST",
moduleId: "reference-resource-page",
paramsCodec: "none",
searchCodec: "ReferenceResourceListQuery",
}),
REFERENCE_RESOURCE_DETAIL: Object.freeze({
routeId: "REFERENCE_RESOURCE_DETAIL",
moduleId: "reference-resource-detail-page",
paramsCodec: "ReferenceResourceParams",
searchCodec: "none",
}),
REFERENCE_RESOURCE_FORM: Object.freeze({
routeId: "REFERENCE_RESOURCE_FORM",
moduleId: "reference-resource-form-page",
paramsCodec: "none",
searchCodec: "none",
}),
REFERENCE_RESOURCE_STATUS: Object.freeze({
routeId: "REFERENCE_RESOURCE_STATUS",
moduleId: "reference-resource-status-page",
paramsCodec: "none",
searchCodec: "none",
}),
}),
invalidation: Object.freeze({
topics: Object.freeze([REFERENCE_RESOURCE_INVALIDATION_TOPIC]),
namespaces: Object.freeze([REFERENCE_RESOURCE_QUERY_NAMESPACE]),
edges: Object.freeze([
Object.freeze({
topicId: REFERENCE_RESOURCE_INVALIDATION_TOPIC,
namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE,
}),
]),
}),
topicVersions: Object.freeze([
Object.freeze({
topicId: REFERENCE_RESOURCE_INVALIDATION_TOPIC,
topicVersion: 1,
}),
]),
// TEMPLATE_FIXTURE contributions are not part of the contract set.
contractPackages: Object.freeze([]),
} as const);
@@ -1,59 +0,0 @@
import {
createReferenceResource,
type ReferenceResource,
} from "../domain/reference-resource.ts";
import {
mappingFailure,
mappingSuccess,
type BoundaryMappingResult,
} from "../../../contracts/boundary-mapper.ts";
import type { ReferenceResourceDto } from "./reference-schemas.ts";
export type ReferenceResourceView = Readonly<{
resourceId: string;
title: string;
createdAt: string | null;
optimistic?: boolean;
}>;
/**
* Operation-specific mapper. The HTTP contract has already validated the wire
* shape, so this mapper owns only wire -> domain construction.
*/
export function mapReferenceResourcePayload(
dto: ReferenceResourceDto,
): BoundaryMappingResult<ReferenceResource> {
try {
return mappingSuccess(
createReferenceResource({
id: dto.id,
displayName: dto.name,
createdAt: dto.createdAt ?? null,
}),
);
} catch {
return mappingFailure("MAPPING_INVARIANT_REJECTED");
}
}
export function mapReferenceResourceListPayload(
payload: readonly ReferenceResourceDto[],
): BoundaryMappingResult<readonly ReferenceResource[]> {
const output: ReferenceResource[] = [];
for (const item of payload) {
const mapped = mapReferenceResourcePayload(item);
if (!mapped.ok) return mapped;
output.push(mapped.value);
}
return mappingSuccess(Object.freeze(output));
}
export function toReferenceView(
resource: ReferenceResource,
): ReferenceResourceView {
return Object.freeze({
resourceId: resource.id,
title: resource.displayName,
createdAt: resource.createdAt,
});
}
@@ -1,112 +0,0 @@
export const REFERENCE_MESSAGE_CATALOGS = Object.freeze({
"ko-KR": Object.freeze({
"route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature",
"route.REFERENCE_RESOURCE_LIST.title": "Reference resources",
"route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail",
"route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail",
"route.REFERENCE_RESOURCE_FORM.navigation": "Reference form",
"route.REFERENCE_RESOURCE_FORM.title": "Create reference resource",
"route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status",
"route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status",
"reference.list.eyebrow": "제거 가능한 수직 슬라이스",
"reference.list.description":
"URL codec, application input, HTTP/schema/mapper와 query 상태를 한 경로로 검증합니다.",
"reference.list.create": "새 항목 만들기",
"reference.list.refresh": "새로고침",
"reference.list.resultCount": "총 {count}개 항목",
"reference.list.title": "참조 기능",
"reference.list.filterLimit": "최대 {limit}개",
"reference.list.filterTags": "태그 {tags}",
"reference.list.resources": "참조 리소스 목록",
"reference.form.back": "목록으로 돌아가기",
"reference.form.eyebrow": "폼 페이지",
"reference.form.title": "Reference resource 만들기",
"reference.form.description":
"presentation schema, command mapper, 422/conflict와 dirty navigation 정책을 실행합니다.",
"reference.form.name": "새 항목 이름",
"reference.form.nameDescription":
"앞뒤 공백은 command mapper 전에 제거됩니다.",
"reference.form.note": "설명",
"reference.form.noteDescription":
"선택 입력이며 비어 있으면 command에 포함되지 않습니다.",
"reference.form.cancel": "취소",
"reference.form.save": "저장",
"reference.form.saving": "저장 중…",
"reference.form.reset": "초기화",
"reference.form.reloadList": "목록을 새로 불러와 확인",
"reference.form.saved": "저장했습니다.",
"reference.form.conflict": "충돌을 해결한 뒤 다시 제출할 수 있습니다.",
"reference.form.privacy":
"form value는 URL, storage, telemetry에 저장되지 않고 submit 시에만 application command로 변환됩니다.",
"reference.detail.eyebrow": "상세 페이지",
"reference.detail.titlePending": "참조 상세",
"reference.detail.resourceId": "리소스 ID",
"reference.detail.createdAt": "생성 시각",
"reference.detail.description":
"route param과 detail query의 reset 경계를 확인합니다.",
"reference.detail.summaryPending": "요약 정보를 준비하고 있습니다.",
"reference.detail.sectionSlot":
"이 영역에는 제품별 상세 section을 조립할 수 있습니다.",
"reference.detail.aside": "상세 페이지의 관련 정보 slot입니다.",
"reference.status.eyebrow": "상태 페이지 · 점검",
"reference.status.title": "잠시 사용할 수 없습니다.",
"reference.status.description":
"도메인 데이터나 raw 오류를 노출하지 않는 중립적인 상태 페이지 예시입니다.",
"reference.status.back": "목록으로 이동",
}),
"en-US": Object.freeze({
"route.REFERENCE_RESOURCE_LIST.navigation": "Reference feature",
"route.REFERENCE_RESOURCE_LIST.title": "Reference resources",
"route.REFERENCE_RESOURCE_DETAIL.navigation": "Reference detail",
"route.REFERENCE_RESOURCE_DETAIL.title": "Reference resource detail",
"route.REFERENCE_RESOURCE_FORM.navigation": "Reference form",
"route.REFERENCE_RESOURCE_FORM.title": "Create reference resource",
"route.REFERENCE_RESOURCE_STATUS.navigation": "Reference status",
"route.REFERENCE_RESOURCE_STATUS.title": "Reference resource status",
"reference.list.eyebrow": "Removable vertical slice",
"reference.list.description":
"Checks the URL codec, application input, HTTP/schema/mapper and query state along one path.",
"reference.list.create": "Create item",
"reference.list.refresh": "Refresh",
"reference.list.resultCount": "Total items: {count}",
"reference.list.title": "Reference feature",
"reference.list.filterLimit": "limit {limit}",
"reference.list.filterTags": "tags {tags}",
"reference.list.resources": "Reference resources",
"reference.form.back": "Back to the list",
"reference.form.eyebrow": "FormPage",
"reference.form.title": "Create a reference resource",
"reference.form.description":
"Runs the presentation schema, command mapper, 422/conflict and dirty navigation policies.",
"reference.form.name": "New item name",
"reference.form.nameDescription":
"Leading and trailing spaces are removed before the command mapper.",
"reference.form.note": "Description",
"reference.form.noteDescription":
"Optional. An empty value is left out of the command.",
"reference.form.cancel": "Cancel",
"reference.form.save": "Save",
"reference.form.saving": "Saving…",
"reference.form.reset": "Reset",
"reference.form.reloadList": "Reload the list to check",
"reference.form.saved": "Saved.",
"reference.form.conflict": "Resolve the conflict, then submit again.",
"reference.form.privacy":
"Form values are never written to the URL, storage or telemetry; they become an application command only on submit.",
"reference.detail.eyebrow": "DetailPage",
"reference.detail.titlePending": "Reference detail",
"reference.detail.resourceId": "Resource ID",
"reference.detail.createdAt": "Created",
"reference.detail.description":
"Checks the reset boundary between the route parameter and the detail query.",
"reference.detail.summaryPending": "Preparing the summary.",
"reference.detail.sectionSlot":
"Product-specific detail sections can be assembled here.",
"reference.detail.aside": "Related information slot of the detail page.",
"reference.status.eyebrow": "StatusPage · maintenance",
"reference.status.title": "Temporarily unavailable.",
"reference.status.description":
"An example of a neutral status page that exposes no domain data or raw errors.",
"reference.status.back": "Go to the list",
}),
} as const);
@@ -1,63 +0,0 @@
/**
* FE-REG-SCHEMA rows of the reference feature's route and API schemas.
* Runtime half only (`feature-runtime.ts`); the app boot never imports it.
* The HTTP operations are the V3 descriptors in
* `reference-feature-contract-contribution.ts`; FE-REG-API reads them.
*/
export const REFERENCE_SCHEMA_METADATA = Object.freeze({
ReferenceResourceParams: Object.freeze({
schemaId: "ReferenceResourceParams",
boundary: "route-params",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
ReferenceResourceListQuery: Object.freeze({
schemaId: "ReferenceResourceListQuery",
boundary: "route-search-api-request",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
CreateReferenceResourceCommand: Object.freeze({
schemaId: "CreateReferenceResourceCommand",
boundary: "api-request",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
ReferenceResourceListPayload: Object.freeze({
schemaId: "ReferenceResourceListPayload",
boundary: "api-response",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
ReferenceResourcePayload: Object.freeze({
schemaId: "ReferenceResourcePayload",
boundary: "api-response",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
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",
}),
});
@@ -1,67 +0,0 @@
import { z } from "../../../contracts/zod.ts";
export const referenceResourceListQuerySchema = z
.object({
cursor: z.string().min(1).optional(),
limit: z.coerce.number().int().min(1).max(100).default(20),
tags: z
.preprocess(
(value) =>
value === undefined
? undefined
: Array.isArray(value)
? value
: [value],
z.array(z.string().trim().min(1)).readonly(),
)
.optional(),
})
.strict();
export const referenceResourceParamsSchema = z
.object({
resourceId: z.string().trim().min(1).max(120),
})
.strict();
export const referenceResourceDtoSchema = z
.object({
id: z.string().min(1).max(120),
name: z.string().min(1).max(240),
createdAt: z.string().datetime().optional(),
})
.strip();
export type ReferenceResourceDto = z.output<
typeof referenceResourceDtoSchema
>;
export const referenceProblemSchema = 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(),
/** 03-04. 422 field issues; backend messages are stripped. */
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 ReferenceProblem = z.output<typeof referenceProblemSchema>;
export const createReferenceResourceCommandSchema = z
.object({
name: z.string().trim().min(1).max(120),
note: z.string().trim().max(500).optional(),
})
.strict();
@@ -1,14 +0,0 @@
export type ReferenceResource = Readonly<{
id: string;
displayName: string;
createdAt: string | null;
}>;
export function createReferenceResource(
values: ReferenceResource,
): ReferenceResource {
if (!values.id || !values.displayName) {
throw new TypeError("Reference resource invariants require id and displayName");
}
return Object.freeze({ ...values });
}
@@ -1,26 +0,0 @@
import { defineFeatureModule } from "../feature-module.ts";
import {
REFERENCE_FEATURE_CONTRACT,
REFERENCE_FEATURE_ID,
} from "./contracts/reference-feature-contract.ts";
import { REFERENCE_MESSAGE_CATALOGS } from "./contracts/reference-message-catalog.ts";
export const FEATURE_MODULE_ID =
"reference-feature" satisfies typeof REFERENCE_FEATURE_ID;
/** Owning bounded context (route root and budget live in its declaration). */
export const FEATURE_CONTEXT_ID = "reference-context";
/**
* 15-01. Declaration only: this file and what it imports statically are in the
* initial chunk. The executable half is `feature-runtime.ts`, imported here
* dynamically and loaded when a reference route is entered.
*/
export const REFERENCE_FEATURE_MODULE = defineFeatureModule({
id: FEATURE_MODULE_ID,
contracts: REFERENCE_FEATURE_CONTRACT,
routes: REFERENCE_FEATURE_CONTRACT.routes,
messages: REFERENCE_MESSAGE_CATALOGS,
loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME,
} as const);
export const FEATURE_MODULE = REFERENCE_FEATURE_MODULE;
@@ -1,18 +0,0 @@
import { defineFeatureRuntime } from "../feature-module.ts";
import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-reference-feature-input.ts";
import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./contracts/reference-feature-contract-contribution.ts";
import { REFERENCE_FEATURE_ID } from "./contracts/reference-feature-contract.ts";
import { REFERENCE_SCHEMA_METADATA } from "./contracts/reference-schema-metadata.ts";
/**
* 15-01. The executable half of the reference feature. `feature-module.ts`
* imports this file dynamically; the router loads it when a reference route
* is entered (`application.features.load`), so none of it is in the initial
* chunk.
*/
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: REFERENCE_FEATURE_ID,
schemas: REFERENCE_SCHEMA_METADATA,
adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION],
contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION],
} as const);
@@ -1,32 +0,0 @@
import { lazy } from "react";
import { REFERENCE_FEATURE_ID } from "../contracts/reference-feature-contract.ts";
// 16-04. The codecs have their own file: the pages' link helpers need them and
// this file lazy-loads the pages, so a page importing it would close a cycle.
import { REFERENCE_FEATURE_ROUTE_CODECS } from "./reference-route-codecs.ts";
export const REFERENCE_FEATURE_ROUTE_RUNTIME = {
REFERENCE_RESOURCE_LIST: Object.freeze({
moduleId: "reference-resource-page",
Component: lazy(() => import("./reference-resource-page.tsx")),
}),
REFERENCE_RESOURCE_DETAIL: Object.freeze({
moduleId: "reference-resource-detail-page",
Component: lazy(() => import("./reference-resource-detail-page.tsx")),
}),
REFERENCE_RESOURCE_FORM: Object.freeze({
moduleId: "reference-resource-form-page",
Component: lazy(() => import("./reference-resource-form-page.tsx")),
}),
REFERENCE_RESOURCE_STATUS: Object.freeze({
moduleId: "reference-resource-status-page",
Component: lazy(() => import("./reference-resource-status-page.tsx")),
}),
} as const;
/** Context-owned lazy route modules consume this executable contribution. */
export const REFERENCE_FEATURE_RUNTIME_CONTRIBUTION = Object.freeze({
featureId: REFERENCE_FEATURE_ID,
routeCodecs: REFERENCE_FEATURE_ROUTE_CODECS,
routeRuntime: REFERENCE_FEATURE_ROUTE_RUNTIME,
});
@@ -1,65 +0,0 @@
import { Link } from "react-router-dom";
import {
AsyncSurface,
DetailPage,
} from "../../../presentation/design-system/index.ts";
import { useLocale } from "../../../presentation/i18n/index.ts";
import {
referenceRouteUrl,
useReferenceResourceId,
} from "./reference-routes.ts";
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
import { useReferenceDetail } from "./use-reference-feature.ts";
export default function ReferenceResourceDetailPage() {
const { date, message } = useLocale();
const resourceId = useReferenceResourceId();
const { query } = useReferenceDetail(resourceId);
const resource = query.data;
const failureAction = useReferenceFailureAction(query.state.failure);
return (
<DetailPage
key={resourceId}
breadcrumb={
<Link to={referenceRouteUrl("REFERENCE_RESOURCE_LIST")}>
{message("reference.list.resources")}
</Link>
}
heading={{
eyebrow: message("reference.detail.eyebrow"),
title: resource?.title ?? message("reference.detail.titlePending"),
description: message("reference.detail.description"),
}}
metadata={
resource ? (
<dl>
<dt>{message("reference.detail.resourceId")}</dt>
<dd>{resource.resourceId}</dd>
<dt>{message("reference.detail.createdAt")}</dt>
<dd>
{resource.createdAt
? date(new Date(resource.createdAt))
: message("common.noDisplayValue")}
</dd>
</dl>
) : (
<p>{message("reference.detail.summaryPending")}</p>
)
}
feedback={
<AsyncSurface
state={query.state}
onAction={failureAction}
onRetry={query.retry}
>
{resource ? (
<p>{message("reference.detail.sectionSlot")}</p>
) : null}
</AsyncSurface>
}
aside={<p>{message("reference.detail.aside")}</p>}
/>
);
}
@@ -1,215 +0,0 @@
import { useCallback, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import {
Button,
AsyncSurface,
DirtyNavigationDialog,
ErrorSummary,
Form,
FormActions,
FormFailureStatus,
FormPage,
FormField,
useAppForm,
useDirtyNavigationGuard,
} from "../../../presentation/design-system/index.ts";
import { useLocale } from "../../../presentation/i18n/index.ts";
import { useQueryInvalidationCoordinator } from "../../../presentation/adapters/query/query-invalidation-provider.tsx";
import { REFERENCE_RESOURCE_INVALIDATION_TOPIC } from "../contracts/reference-feature-contract.ts";
import {
REFERENCE_FORM_DEFAULTS,
referenceResourceFormSchema,
toCreateReferenceCommand,
type ReferenceResourceFormValues,
} from "./reference-resource-form.ts";
import { referenceRouteUrl } from "./reference-routes.ts";
import { useReferenceFailureAction } from "./use-reference-failure-action.ts";
import { useReferenceCreate } from "./use-reference-feature.ts";
export default function ReferenceResourceFormPage() {
const navigate = useNavigate();
const { message } = useLocale();
const fieldLabels = {
name: message("reference.form.name"),
note: message("reference.form.note"),
} satisfies Record<keyof ReferenceResourceFormValues, string>;
const mutation = useReferenceCreate();
const invalidation = useQueryInvalidationCoordinator();
const submit = useCallback(
(command: ReturnType<typeof toCreateReferenceCommand>) =>
mutation.submit(command),
[mutation],
);
const form = useAppForm({
schema: referenceResourceFormSchema,
defaultValues: REFERENCE_FORM_DEFAULTS,
allowedServerFields: ["name", "note"],
mapToCommand: toCreateReferenceCommand,
submit,
});
const failureAction = useReferenceFailureAction(form.failure ?? undefined);
const mutationEffectUnknown =
mutation.state.indicator === "mutation-effect-unknown";
const mutationBlocked =
mutationEffectUnknown || mutation.state.indicator === "mutation-pending";
// 1105/08-04. A save this form did not start holds the coordinator: one
// left running when the user came back to the form, or the check behind
// "confirm applied". The save button is off and, for the first, the
// feedback says a save is running, instead of a click that does nothing.
const otherSaveRunning =
mutation.state.indicator === "mutation-pending" && !form.pending;
// 1106/08-01. The result of that save belongs to the form that started
// it, not to this one. Once it ends, the feedback points to the list,
// which shows whether the item is there, until this form saves itself.
const [otherSaveSeen, setOtherSaveSeen] = useState(false);
if (!otherSaveSeen && otherSaveRunning && form.result === "idle") {
setOtherSaveSeen(true);
} else if (otherSaveSeen && (form.pending || form.result !== "idle")) {
setOtherSaveSeen(false);
}
const guard = useDirtyNavigationGuard(form.dirty && !form.pending);
const reloadList = (
<p>
<Link
to={referenceRouteUrl("REFERENCE_RESOURCE_LIST")}
onClick={() => {
void invalidation
?.invalidate([REFERENCE_RESOURCE_INVALIDATION_TOPIC])
.catch(() => {});
}}
>
{message("reference.form.reloadList")}
</Link>
</p>
);
return (
<Form
id={form.formId}
pending={form.pending}
onSubmit={(event) => {
if (mutationBlocked) {
event.preventDefault();
return;
}
void form.submitForm(event);
}}
>
<FormPage
feedbackId={form.feedbackId}
breadcrumb={
<button
className="ui-button ui-button--ghost"
type="button"
onClick={() => navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST"))}
>
{message("reference.form.back")}
</button>
}
heading={{
eyebrow: message("reference.form.eyebrow"),
title: message("reference.form.title"),
description: message("reference.form.description"),
}}
errorSummary={
<ErrorSummary
fieldErrors={form.fieldErrors}
formErrors={form.formErrors}
fieldLabels={fieldLabels}
fieldId={form.fieldId}
onFocusField={form.focusField}
/>
}
fields={
<>
<FormField
{...form.field("name")}
label={fieldLabels.name}
description={message("reference.form.nameDescription")}
autoComplete="off"
required
/>
<FormField
{...form.field("note")}
label={fieldLabels.note}
description={message("reference.form.noteDescription")}
autoComplete="off"
/>
</>
}
formActions={
<FormActions sticky>
<Button
variant="secondary"
onClick={() => navigate(referenceRouteUrl("REFERENCE_RESOURCE_LIST"))}
disabled={form.pending || mutationBlocked}
>
{message("reference.form.cancel")}
</Button>
{/* 1103/08-02. Busy, not disabled, while saving: a disabled
button drops keyboard focus. The form refuses a second
submit itself. */}
<Button
type="submit"
pending={form.pending}
pendingLabel={message("reference.form.saving")}
disabled={mutationEffectUnknown || otherSaveRunning}
>
{message("reference.form.save")}
</Button>
<Button
variant="ghost"
onClick={() => form.reset()}
disabled={!form.dirty || form.pending || mutationBlocked}
>
{message("reference.form.reset")}
</Button>
</FormActions>
}
feedback={
form.failure ? (
<FormFailureStatus
failure={form.failure}
onAction={
form.result === "retry-later"
? () => void form.submitForm()
: failureAction
}
/>
) : mutationEffectUnknown ? (
<>
<AsyncSurface
state={mutation.state}
supportReference={form.supportReference}
onReconcileUnknownEffect={(resolution) => {
void mutation
.reconcileUnknownEffect(resolution)
.then(form.settleApplied);
}}
onResendUnknownEffect={() => {
void form.resendUnknown(mutation.resendUnknownEffect);
}}
/>
{reloadList}
</>
) : form.result === "success" ? (
<p role="status">{message("reference.form.saved")}</p>
) : form.result === "conflict" ? (
<p role="status">{message("reference.form.conflict")}</p>
) : otherSaveRunning && form.result !== "effect-unknown" ? (
// 1105/08-04. While this form's own unknown result is being
// checked, the result that follows is shown instead.
<AsyncSurface state={mutation.state} />
) : otherSaveSeen ? (
reloadList
) : null
}
aside={
<p>{message("reference.form.privacy")}</p>
}
guard={<DirtyNavigationDialog guard={guard} />}
/>
</Form>
);
}

Some files were not shown because too many files have changed in this diff Show More