Files
clean-architecture-frontend…/docs/architecture/starter-experience.md
T
DongHyeonka 7139c7c61e fix(apps): 소유 context 루트가 닿지 않는 기능 라우트를 조립 때 막는다 (09-06)
문제: 라우터는 context마다 gateway 하나를 그 루트 경로에 붙이고 기능
라우트를 그 안에서만 렌더한다. 레지스트리와 탐색 메뉴는 경로와 상관없이
모든 기능 라우트를 싣는다. 그래서 루트 `shop/*` context의 `/catalog`
라우트는 메뉴 링크로 나오고 그 URL은 NOT_FOUND가 된다. 같은 루트를 쓰는
context가 둘이면 id가 늦은 쪽 전체가 닿지 않는다. 어떤 게이트도 경로와
루트를 비교하지 않았다.

고른 방법: `defineDeployableAppModule`이 context별 기능 계약 라우트를
React Router `matchRoutes`로 전체 context 루트에 맞춰 보고, 그 라우트를
받는 context가 소유 context가 아니면 라우트 id·경로·기능 id·context
id·루트를 담아 throw한다. 앱 모듈은 부트 정적 그래프에서 평가되므로
부트 실패 화면과 라우터를 거치는 모든 테스트에서 드러난다. 라우터와 같은
매칭 규칙을 쓰므로 루트 밖 경로, `/`, 루트 없는 context, 같은 루트, 더
구체적인 다른 루트에 먹히는 경로를 한 검사로 잡는다. 중첩 루트 자체는
허용한다(`tests/component/context-route-gateway.test.tsx`가 쓰는 모양).
starter-experience.md 기능 추가 4단계에 규칙을 적었다.

버린 대안:
- 생성기에서 검사: 생성기는 정규식으로 리터럴만 읽어 라우트 경로를 모른다.
- `defineBoundedContextModule`에서 검사: 다른 context의 루트를 모른다.
  같은 루트·중첩 루트를 앱 단위에서 따로 또 봐야 해서 검사가 두 곳이 된다.
- 루트 문자열 접두어 비교: `:param`·splat 규칙을 다시 구현하게 된다.

위험·한계:
- 리뷰 09-06의 (3) "context 라우트 핸들의 route id가 레지스트리에 있는가"는
  넣지 않았다. 핸들은 `context-routes.ts`를 읽어야 보이는데 이 파일은 늦게
  읽어야 한다. 헬퍼 제공과 적재 시 검사 중 고르는 설계 선택이라 남긴다.
  그 실패의 진단 누락은 09-09에서 다룬다.
- 플랫폼 라우트와 기능 라우트의 경로 충돌은 검사하지 않는다.
- 초기 JS +239 B gzip(202,509 → 202,748 B, 여유 2,291 → 2,052 B).
  같은 worktree에서 `vite build` 두 번으로 쟀다.

검증:
- RED: tests/architecture/context-route-roots.test.ts 7건 중 거절 5건이
  "expected [Function] to throw an error"로 실패(수정 전, 298201f 기준).
- GREEN: 같은 파일 7건 통과.
- 회귀: tests/{architecture,platform,component,features,scripts,contract}
  94 files / 588 tests, tests/unit(pnpm을 띄우는 5개 제외) 164 files /
  1,929 tests 통과. tsc app·test·node 통과. 바꾼 파일 eslint 통과.
  check-architecture.ts(pnpm exec를 node_modules/.bin으로 넘기는 shim)
  통과.
2026-11-01 22:56:29 +09:00

182 lines
9.3 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.
### 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` |
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`).
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`).
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:
| File | Change |
| --- | --- |
| `src/.generated/*` | regenerated automatically |
| `src/contexts/<context>/context-module.ts` | only when the feature needs a new context |
| `config/runtime/<profile>.json` | optional `FEATURE_OVERRIDES` entry to switch the feature off |
| `src/bootstrap/runtime-adapters.ts` | only when `needs` includes `indexedDb`: add the capability, built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts` |
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`).
### 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.