Files
clean-architecture-frontend…/docs/architecture/starter-experience.md
T
DongHyeonka ca161878f2 feat(routes): 기능이 홈을 대신하고 context가 자기 레이아웃을 선언한다 (1101/09-03)
문제: 라우터는 모든 context gateway를 `AppShell` 하나 아래에 붙이고 플랫폼
`/`를 index로 둔다. 기능이 `APP_HOME`을 선언하면 `composeUniqueRecord`가
throw한다. 그래서 제품 홈이 기능 화면이거나 화면이 `AppShell`이 아닌 자기
셸을 쓰면 제품이 템플릿 라우터와 조립 카탈로그를 고쳐야 한다. memento는
카탈로그 브리지(`APP_HOME` 허용 목록)와 라우터 브리지(`ownsShell`)를 넣고
동기화마다 병합한다. tech-log는 라우터를 PUBLIC/STUDIO 그룹 라우터로 통째로
바꿔 생성기 설치 경로(context gateway)를 쓰지 못한다.

고른 방법: 리뷰 4.3의 (B). 선언 두 개를 연다.
- 홈 대체: 플랫폼이 기능이 대신할 수 있는 라우트 id를 선언한다
  (`FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS = ["APP_HOME"]`,
  src/contracts/routes.ts). 그 id를 선언한 기능의 정의가 플랫폼 정의를
  대신한다. 둘이 선언하면 카탈로그를 읽을 때 두 기능 id를 담아 throw한다
  (`withoutTakenOverPlatformRoutes`). 다른 플랫폼 id는 지금처럼 중복 오류다.
  라우터는 대체된 라우트를 소유 context와 함께 그 경로에 붙인다.
- context 레이아웃: `BoundedContextRouteModule.loadLayout`(선택). 생성기는
  `src/contexts/<context>/context-layout.tsx`가 있으면 그 `CONTEXT_LAYOUT`을
  지연 import로 싣는다. 라우터는 그 context를 `AppShell` 형제인 `/` 레이아웃
  라우트 아래, 기능의 등록 경로마다 붙인다. 그래서 모르는 URL은 여전히
  `AppShell`의 NOT_FOUND로 간다. 선언이 없으면 지금처럼 `AppShell` 아래 루트에
  붙는다. 레이아웃 청크 실패는 라우트 청크와 같은 reload-once 복구를 받는다.
- 09-06 불변식을 레이아웃으로 넓힌다. 레이아웃 라우트는 모두 `/`의
  형제라서 루트는 레이아웃과 상관없이 그 아래 URL을 가진다. 그래서 기존
  루트 검사가 모든 레이아웃에 걸친다. 한 레이아웃 아래 루트 여럿(같은
  컴포넌트를 싣는 context들)은 허용한다. 대체된 플랫폼 라우트는 라우터가
  경로에 직접 붙이므로 루트 검사에서 뺀다(09-06 재검토 조건).
- tests/unit/product-features.test.ts의 "플랫폼 라우트는 소유자가 없다"
  검사가 대체 가능한 id는 건너뛴다. memento가 고쳤던 템플릿 테스트다.
- `ContextRouteModule`에 `featureIds`가 생겨서, `TEMPLATE_APP_MODULE`을
  손으로 mock하며 필수 필드 `features`를 빼먹은 두 테스트
  (context-route-gateway, context-boundary-diagnostics)에 `features: []`를
  넣었다.

버린 대안:
- (A) 현 상태: 제품마다 브리지를 넣고 동기화마다 병합한다.
- (C) `AppShell` 통째 교체: 레이아웃 그룹이 둘인 tech-log를 담지 못한다.
- 같은 레이아웃을 쓰는 context를 로더 함수로 묶어 레이아웃 라우트 하나에
  모으기: 만들었다가 지웠다. React 19는 같은 컴포넌트로 풀린 lazy 타입을 같은
  타입으로 맞춰 레이아웃 인스턴스를 그대로 둔다. 묶지 않은 변이로 테스트가
  그대로 통과해서 쓸모없는 코드였다.
- `CONTEXT_LAYOUT_ID` 리터럴로 다른 context의 레이아웃을 가리키기: 같은
  컴포넌트를 내보내는 파일 두 개로 같은 결과가 나와 선언을 하나 덜 둔다.
- 레이아웃 라우트를 `AppShell`보다 앞에 두기(memento 브리지 순서): 경로가
  같으면 기능이 플랫폼 라우트를 조용히 가린다. `AppShell`을 앞에 두어
  지금처럼 플랫폼이 이긴다.

위험·한계:
- 레이아웃이 skip link와 `<main id="main-content">` 하나를 그리는 것은
  계약(타입 주석, starter-experience.md)과 테스트 fixture로만 지킨다. 실행 중
  검사는 없다. 레이아웃 로딩·실패 화면에는 `<main>`이 없다(`AppShell`의
  errorElement와 같다).
- 레이아웃 렌더 결함(청크 실패가 아닌 것)은 라우트 errorElement로 가고
  진단을 남기지 않는다. `AppShell` 렌더 결함과 같다.
- 홈을 대신한 기능을 실행 중에 끄면 `/`는 비활성 기능 화면이 된다. 빌드에서
  빼면(`VITE_PRODUCT_FEATURES`) 플랫폼 홈이 돌아온다.
- tech-log의 PUBLIC 셸 안 NOT_FOUND는 표현하지 않는다. 모르는 URL은
  `AppShell`의 NOT_FOUND다. STUDIO의 `/studio/*` 라우트는 STUDIO 레이아웃
  아래에서 동작한다. tech-log는 기능 하나를 레이아웃 그룹별 기능 둘(context
  둘)로 나눠야 한다.
- 플랫폼 라우트와 기능 라우트의 같은 경로는 여전히 검사하지 않는다(7139c7c
  한계). 루트 `*` context에서 `APP_HOME`이 아닌 id로 `/`를 선언하면 플랫폼
  홈에 가려진다.
- 초기 JS gzip +349 B(204,586 -> 204,935 B). 예산 204,800 B를 135 B
  넘는다(이전 여유 214 B). boot 청크 +228(라우터·앱 모듈),
  installed-feature-contracts 청크 +121. 같은 worktree에서 HEAD 파일로
  `vite build`를 한 번 더 해서 청크별로 비교했다. 예산은 고치지 않았다.

검증:
- RED: tests/component/context-layouts.test.tsx는 파일 적재에서
  "Duplicate route registry key: APP_HOME"으로 실패.
  tests/architecture/context-route-roots.test.ts 15건 중 3건 실패(APP_HOME
  루트 예외 "not under the route root", 대체 함수가 없어 2건).
  tests/scripts/generate-product-feature-index.test.ts 새 1건이 HEAD 생성기로
  "expected ... to contain 'loadLayout: async () => (await import…'"로 실패.
- GREEN: 세 파일 37건 통과(생성기 15, 루트 16, context-layouts 6).
- 변이: 라우터가 `loadLayout`을 무시하면 context-layouts 6건 중 5건 실패.
  topics 레이아웃을 다른 컴포넌트로 바꾸면 "keeps one layout instance" 실패.
- 회귀: tests/{architecture,unit,features,platform,component,contract,
  runtime-schema,integration,scripts,scale}(pnpm을 띄우는 4개 제외)
  300 files, 3,451건 통과. check-registries, check-adapter-inventory,
  verify-documentation-readiness(PASS_SCOPED) 통과.
- tsc app·test·node 통과. 바꾼 파일 eslint 통과. 생성기 --check 통과.
- check:architecture는 pnpm이 필요해 돌리지 않았다.

Refs: docs/reviews/2026-11-01-maturity-review/09-app-core.md 09-03, 4.3
2026-11-03 01:52:18 +09:00

256 lines
15 KiB
Markdown

# Starter experience contract
The repository provides a runnable, domain-neutral application rather than
only infrastructure contracts. The starter experience is intentionally
replaceable at the page level while the shell, providers, boundaries,
primitives, and state surfaces remain reusable.
## Runtime composition
```text
validated config + coherent release manifest
-> concrete adapters
-> QueryClientProvider
-> ApplicationProvider
-> RouterProvider
-> ThemeProvider
-> SessionProvider
-> AppShell
-> lazy route boundary
```
Boot stops before product mount when configuration or release coherence fails.
Each lazy page renders inside Suspense and a telemetry-aware route boundary.
Route changes move focus to the new page heading; the skip link and landmarks
remain stable in the shell.
## Registered routes
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 platform overview page (`/examples/platform`) shows the
composed list at runtime, so this document does not keep a copy of it.
Navigation labels and order come from `ROUTE_REGISTRY`; the sidebar does not
maintain a second route list. The client access decision never claims to be
authorization.
## Authentication seam
The session port exposes state subscription, sign-in start, sign-out,
credential attachment, recovery, and unauthenticated notification. Credentials
remain opaque to the application and presentation layers.
- `demo`: local/development-only state transition with no credentials
- `external`: delegates to `globalThis.__CA_FRONTEND_AUTH_OWNER__`
- missing/invalid external owner: fails closed as `integration-failed`
An external owner implements `readState`, `readSubject`, `subscribe`,
`beginSignIn`, `signOut`, `attachCredential`, `recoverSession`, and
`notifyUnauthenticated`. It owns token acquisition and storage. An owner that
lacks any of these methods is rejected, and the session fails closed as
`integration-failed`.
`readSubject()` is required. The server-state cache is cleared only when the
session state or the subject changes, so a token refresh for the same user
keeps cached data. `readSubject()` must return:
- an opaque, non-empty string that stays the same for one user across token
refreshes and differs between users: the OIDC `sub` claim, Supabase
`session.user.id`, or Firebase `user.uid`
- `null` when nobody is signed in
- never an access token, refresh token, or any other credential
If `readSubject()` returns `null` or `""` while the owner reports
`authenticated`, the runtime cannot tell a refresh from an account switch. It
fails closed: every such notification clears server state, and each one records
the `cache.operation.failed` diagnostic with `operation: SCOPE_FENCE` and
`reason: SUBJECT_MISSING`. Seeing that diagnostic means the owner is not
reporting its subject. The `demo` adapter reports one fixed demo user as its
subject.
Migration: `readSubject()` used to be optional. An owner written for an earlier
release must add it; without it the owner is rejected at startup (the session
becomes `integration-failed`) and a TypeScript owner no longer compiles
against `ExternalSessionOwner`. A code path that implements `AuthSessionPort`
or `SessionGateway` directly must add `getSubject()` the same way.
## Extending the starter
New platform work should follow
[routing, page templates, and reusable patterns](./routing-pages-and-patterns.md)
and the
[TypeScript, state, and data-flow target](./typescript-state-and-data-flow.md)
rather than adding another independent route or data-loading convention.
### Replacing the starter screens
`/` (`src/presentation/pages/home-page.tsx`) and `/examples/*`
(`src/presentation/examples/`) are template content. Their own tests are the
`tests/component/starter-*.test.tsx` files; delete them together with the
screens. 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 when the starter screens
change. Browser-level checks of the starter screens stay in `tests/e2e` and
`tests/visual`.
### Ownership declarations
Features, contexts and apps are discovered by
`scripts/generate-product-feature-index.ts`. Each boundary declares only its
parent, as exported string or integer literals the generator reads:
| File | Exports |
| --- | --- |
| `src/apps/<app>/app-module.ts` | `APP_MODULE_ID`, `APP_MAX_CONTEXTS` |
| `src/contexts/<context>/context-module.ts` | `CONTEXT_MODULE_ID`, `CONTEXT_APP_ID`, `CONTEXT_ROUTE_PATH`, `CONTEXT_MAX_FEATURES` |
| `src/features/<feature>/feature-module.ts` | `FEATURE_MODULE_ID`, `FEATURE_CONTEXT_ID`, `FEATURE_MODULE` |
| `src/features/<feature>/feature-runtime.ts` | `FEATURE_RUNTIME` (imported only by `feature-module.ts`, dynamically) |
| `src/features/<feature>/context-routes.ts` | `FEATURE_CONTEXT_ROUTES` |
| `src/contexts/<context>/context-layout.tsx` (optional) | `CONTEXT_LAYOUT`, the context's own layout ("Product home and layouts") |
The generator writes `src/.generated/` (git-ignored): the feature index the
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_INSTALLED` marker file (`src/features/local-draft-feature/NOT_INSTALLED`
is the one intentional example);
- 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
variable narrows the installed set here, before anything is compiled.
### Adding a feature
1. Create `src/features/<feature>/feature-module.ts`. Build `FEATURE_MODULE`
with `defineFeatureModule` (`src/features/feature-module.ts`). This is the
feature's declaration, and it is in the initial chunk, so it holds data
only: the declaration contract (routes, route runtime contracts,
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.
2. Create `src/features/<feature>/feature-runtime.ts` with
`defineFeatureRuntime`: the API contract (operations, schema metadata,
runtime schemas, mappers), the adapter contributions
(`defineFeatureAdapterContribution`, with `needs` naming the platform
capabilities it receives) and the contract contributions. The router loads
it (`application.features.load`) when one of the feature's routes is
entered. Do not import it statically from anywhere: each feature would add
its whole executable code to the initial chunk again, about 3.9 KB gzip
(`tests/unit/feature-shape-growth.test.ts` bounds one feature at 1 KiB).
An HTTP API is written twice: its API contract operation (V2) is what
`check:registries` governs, and its contract contribution descriptor (V3)
is what executes. `tests/unit/http-operation-v2-v3-parity.test.ts` fails
when one exists without the other or when they disagree.
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.
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
`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`).
4. Name the owning context in `FEATURE_CONTEXT_ID`. Use an existing context or
add `src/contexts/<context>/context-module.ts` owned by the app.
Every route path in the feature contract must sit at or under that
context's `CONTEXT_ROUTE_PATH` and must not fall under another context's
identical or more specific root: the router renders feature routes only
inside the owning context. The app module refuses anything else when it
loads, naming the route, feature and context
(`src/apps/deployable-app-module.ts`). A route 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`).
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.
7. Run `corepack pnpm test:sample-removal -- --feature=<feature id>` to prove
the product still builds and passes its gates without the feature.
Files outside the feature directory. Everything else a feature needs is in
`src/features/<feature>/` and `tests/features/<feature>/`.
| File | When | What fails without it |
| --- | --- | --- |
| `src/.generated/*` | never by hand: every build and check script regenerates it | — |
| `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 |
| `tests/e2e/accessibility.spec.ts` | a route path has a parameter other than `:resourceId`, or a protected page cannot render while every API answers `[]` | `test:a11y` (FE-GATE-009): the spec fills in only `:resourceId` and answers every API with `[]` |
| `src/bootstrap/product-composition.ts` (product-owned) | `needs` names a capability the template does not build: augment `FeaturePlatformCapabilities` and return the capability here. `indexedDb` is built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts`. Credentials for a product auth profile are returned here too | `check:types`; at runtime `feature <id> needs <capability>, which the host did not provide` |
| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile or a product runtime-config key | auth profile: every gate that loads the operation, with `REST security profiles are incoherent for <operationId>: unknown authProfileId …`. Config key: `check:types` where it is read |
| `config/runtime/<profile>.json` | optional: a `FEATURE_OVERRIDES` entry switches the feature off | nothing |
| `package.json`, the lockfile, `config/security/dependency-change-evidence.json` | the contract contribution imports a generated `@org-contracts/*` package as a production dependency | `generate:supply-chain` (in `check:bundle`): `high-risk dependency missing review: add:<package>` |
The central catalogs (`src/features/installed-*.ts`) and the registry
governance file do not change: consumer directories there are globs over every
feature (`src/features/*/adapters`, `config/contracts/registry-governance.json`).
A route's params/search schema ids are checked against the schemas the feature
registers, and its `loadingSurface` only has to be a kebab-case name, so a
route with its own schema and loading surface needs no governance edit either.
The registry baseline does not change either. New routes, API operations,
schemas and invalidation topics, namespaces and edges are additive registry
changes; `update:registry-baseline` or breaking evidence is needed only to
remove or change a row or graph item.
`tests/unit/second-api-feature-registries.test.ts` adds such a feature (an API
operation, a route with its own search schema and loading surface, and an
invalidation topic) to a copy of the repository and runs `check:registries` on
it.
Schema, operation, mapper, route and chunk ids and invalidation topics are
global. Prefix them with the feature; `NoRequest` already belongs to the
sample. MSW scenarios for the feature's own operations come from
`createHttpScenarioHandler` (`tests/mocks/handlers/http-scenarios.ts`) with
the feature's installed contract; the shared scenario catalog does not change.
### Product home and layouts
A product whose home is a feature screen, or whose screens use a frame other
than `AppShell`, declares it. The router and the catalogs do not change.
- **Home.** A feature takes over the platform home by declaring a route with
the id `APP_HOME` in its contract. The platform names the routes a feature
may take over (`FEATURE_REPLACEABLE_PLATFORM_ROUTE_IDS` in
`src/contracts/routes.ts`); any other platform route id is still a
duplicate. Two features declaring `APP_HOME` fail when the catalogs load,
naming both. The router mounts the route at its own path with the owning
context, whatever that context's route root. Leaving the feature out of the
build (`VITE_PRODUCT_FEATURES`) brings the platform home back; switching it
off at runtime shows the disabled-feature page at its path.
- **Layout.** A context with `src/contexts/<context>/context-layout.tsx`
exporting `CONTEXT_LAYOUT` (a component) renders under that layout instead
of `AppShell`. The generated index loads the file lazily, when one of the
context's routes is entered. The router mounts the context at each
registered path of its features under the layout, so an unknown URL still
gets the not-found page in `AppShell`. Contexts whose layout files export the
same component keep one layout instance when the user moves between them,
so several route roots can share a layout.
- **Accessibility.** The layout renders a skip link to `#main-content` and
exactly one `<main id="main-content" tabIndex={-1}>` around `<Outlet />`.
The router moves focus there on every route change. Layout routes are
siblings of `AppShell`, never inside it.
- **Failures.** A layout chunk a deploy removed gets the reload-once recovery
of a route chunk. Route and feature boundaries work as they do in
`AppShell`.
- The route root rule of step 4 spans every layout: a root takes the URLs
under it whichever layout either context has.
`tests/component/context-layouts.test.tsx` installs a product declared this
way (`tests/helpers/fixture-layout-product.tsx`).
### Before shipping
- Use the semantic tokens, UI primitives, and state surfaces before adding a
project-specific variant.
- Add component behavior, all-engine E2E, automated axe, and signed manual
route evidence.
Theme preference is the public `COLOR_SCHEME` storage contract. Authentication
tokens and other secrets remain forbidden storage keys.