Files
clean-architecture-frontend…/docs/architecture/frontend-application-foundation.md
T
DongHyeonka da1e128999 feat(bootstrap): 제품 capability·자격증명·설정 키를 제품 소유 파일로 받는다 (1101/09-02)
문제
제품이 http·telemetry·indexedDb 밖의 capability, 세션 밖 자격증명(BFF
쿠키 XSRF, Studio CSRF), 제품 런타임 설정 키를 넣으려면
runtime-adapters.ts, feature-adapter-contribution.ts, rest-profiles.ts,
release-artifacts.ts, runtime-config-schema.ts를 직접 고쳐야 한다. 이
파일들은 템플릿이 보안·계약 수정을 자주 넣는 곳이라, 동기화 때마다
fail-closed 코드를 손으로 병합한다(memento +61줄, tech-log +118줄).

고른 방법 (리뷰 09 4.2의 (B))
- FeaturePlatformCapabilities를 interface로 바꾼다. 제품은 이 repo의
  FeatureIndexedDbRepositories·ApplicationFeatureInputs와 같은
  declaration merging으로 capability를 더한다.
- 제품 소유 파일 둘을 빈 구현으로 둔다.
  - src/bootstrap/product-composition.ts: 추가 capability와 "인증 프로필
    id → 자격증명 제공자" 표. 계약 타입은 템플릿 소유
    product-composition-contract.ts에 둔다.
  - src/contracts/product-contracts.ts: 제품 인증 프로필과 런타임 설정
    zod 조각. 프로필 레지스트리와 strict 설정 스키마는 contracts 층에
    있고 빌드 스크립트도 읽는다. contracts는 bootstrap을 import할 수
    없어서 파일을 하나로 합치지 못했다.
- 판단 순서는 조립 루트가 쥔다: scope fence → ANONYMOUS 프로필 → 제품
  제공자 → 세션 → 응답 뒤 fence 재확인. 제공자가 throw하면 executor가
  CREDENTIAL_OWNER_FAILED로 닫는다. 나가는 헤더는 여전히 프로필 허용
  목록이 정한다.
- 제공자 계약은 기존 attachCredentials 시그니처를 그대로 쓴다.
- 제품 composition은 http capability가 생긴 뒤에 부른다. tech-log가
  두었던 전방 참조 stub이 필요 없다.
- 제품에 host 전체를 넘기지 않고 readCookie(name)만 넘긴다. host를 객체에
  담으면 browser-data-boundary/no-capability-alias가 막는다.
- http·telemetry는 spread 뒤에 둬서 제품이 바꿀 수 없다(타입에서도 뺀다).
  제품 프로필 id나 설정 키가 템플릿 이름과 겹치면 모듈 로드 때 throw한다.

버린 대안
- (A) 현 상태: 템플릿 비용은 0이지만 제품마다 동기화 비용이 반복된다.
- (C) 기능 계약 기여가 인증 프로필과 제공자를 함께 가져온다: 인증
  정책이 기능마다 흩어져 보안 리뷰 범위가 넓어진다.
- 제공자에 응답 관찰 훅 추가: tech-log의 401/403 토큰 폐기는 제품
  capability가 http를 감싸서 표현된다(픽스처). 제공자 계약을 작게 둔다.

위험·한계
- memento의 x-xsrf-token은 닫힌 자격증명 헤더 목록(VD-23,
  CREDENTIAL_HEADER_NAMES)에 없다. 그 이름을 쓰려면 여전히
  rest-profiles.ts를 고치거나 백엔드가 x-csrf-token을 받아야 한다.
  픽스처는 x-csrf-token으로 표현했다.
- 제품 설정 키의 FE-REG-ENV 행(src/contracts/env.ts)은 이 변경 밖이다.
  그 행을 요구하는 검사는 없다.
- tech-log가 부트 전에 BFF 세션 owner를 설치하는 코드
  (create-runtime-composition.ts)는 이 확장 지점 밖이다.
- 제공자 응답 뒤 fence 재확인은 executor가 같은 fence로 먼저 전송을
  끊어서 조립 루트 경유 테스트로는 따로 보이지 않는다. 세션 경로와 같은
  이중 방어로 둔다.
- V1 설정 문서도 제품 키를 받는다(없으면 기본값). V1은 한 릴리스 동안만
  쓰는 리더다.
- 초기 JS gzip 203,818 → 204,178 B(+360, 예산 204,800).

검증
- RED: tests/unit/runtime-adapters-credential-order.test.ts 7행 중 제품
  제공자를 기대하는 4행 실패(세션이 먼저 답해 UNAUTHENTICATED, owner가
  먼저 답해 SUCCESS). fence·ANONYMOUS·세션 3행은 통과.
- GREEN: 같은 파일 7/7. tests/unit/product-composition-fixture.test.ts
  9/9(가짜 제품 파일 두 개로 offsetUpload, runtime, BFF 쿠키 XSRF 읽기·
  쓰기, Studio CSRF 발급·403 폐기, 제품 설정 키, 이름 충돌 거절). 09-01
  tests/unit/runtime-adapters-auth-profile.test.ts 12/12.
- 회귀: tests/unit·contract·runtime-schema 182 files 2590 tests 통과.
  integration·component 47 files 386 tests 통과(pnpm을 띄우는
  security-followup-archive 제외). tsc app·test·node·recipes·web-worker·
  service-worker 통과. 바꾼 파일 eslint 통과. check:registries PASS
  (compatibility=breaking은 기존 route·storage 행). verify:documentation
  PASS_SCOPED. check:adapter-inventory PASS. check:architecture는 pnpm 대신
  exec 전용 shim으로 그래프·fixture PASS. 템플릿 런타임 설정 JSON
  schema는 baseline과 같다.
2026-11-03 00:56:40 +09:00

296 lines
12 KiB
Markdown

# Frontend Application Foundation
This repository is not treated as a minimal React project template and it is not
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
problems such as HTTP execution, Server State, authentication boundaries,
IndexedDB/OPFS, Cache Storage, realtime, browser RPC, transfer and diagnostics.
The cost of a sophisticated capability is acceptable only when product features
do not have to understand that internal sophistication.
## Hybrid architecture
`src/` has nine top-level folders. The descriptions match the table in
[the layer contract](./layers.md), which also names every import rule.
Platform code is horizontal:
- `src/bootstrap` — the composition root: runtime configuration, concrete adapter construction and the React mount
- `src/presentation` — generic UI and the inbound adapter: routes, layouts, the design system, pages and providers
- `src/adapters` — reusable capability runtimes that implement application ports: HTTP, auth, storage, query cache, telemetry, workers and more
- `src/application` — generic use cases, ports, policies and view-models
- `src/contracts` — shared vocabulary and registries read by several layers, the workers and the build and release scripts
- `src/platform` — product-neutral primitives any folder may use: budgets, execution context, resilience, the telemetry pipeline, error envelopes and release coherence
Ownership declarations group features into deployable units:
- `src/apps` — deployable apps: each `app-module.ts` declares an app and its context budget; `template-app.ts` is the app this build produces
- `src/contexts` — bounded contexts: each `context-module.ts` declares its app, route root and feature budget
Product business code is vertical:
- `src/features` — removable vertical slices (`src/features/<id>/{domain,application,contracts,adapters,presentation}`) and the installed-feature catalogs (`src/features/*.ts`)
Inside one feature:
- `features/<feature>/domain`
- `features/<feature>/application`
- `features/<feature>/contracts`
- `features/<feature>/adapters`
- `features/<feature>/presentation`
The dependency model is:
Domain / Use case
|
| owns
v
Business port
^
| implements / binds
|
Feature-owned adapter binding
|
| generic type + mapper/codec + policy
v
Reusable capability runtime
|
v
Browser / network / native API
A use case never imports a platform adapter. Generic binding happens in the
feature adapter/composition seam.
## Capability-specific typed bindings
Do not introduce one universal `Repository<TKey, TValue>` abstraction for HTTP,
storage, realtime and transfer. Their lifecycle and failure semantics differ.
A reusable capability boundary is composed from:
- generic input/output types,
- feature-owned mapper or codec,
- feature-selected policy,
- one capability-specific runtime.
The HTTP reference path is the first concrete example.
`src/adapters/http/feature-http-binding.ts` owns transport/outcome
normalization. The reference feature contributes only:
- operation ID,
- route ID,
- exact request input type,
- exact success value type,
- wire-to-domain mapper.
The feature gateway therefore does not reimplement timeout, cancellation,
transport failure, authentication failure or contract-violation projection.
Storage, realtime and transfer may gain their own typed binders only after
actual feature repetition demonstrates the need. They must not be forced
through the HTTP abstraction.
## Custom adapter escape hatch
A product feature uses a reusable capability when the capability preserves the
business requirement.
If a platform contract would require changing or weakening the business model,
the feature implements a custom outbound adapter behind the same application
port. The architecture boundary remains stable; platform reuse is optional.
## Feature installation
A feature owns its contract, runtime and adapter contributions.
Central installed catalogs are aggregation points only:
- `installed-product-manifest.ts`: which product features are compiled/selected
- `installed-feature-contracts.ts`: boot-time contract aggregation (routes,
route runtime contracts, invalidation) from the feature declarations
- `installed-feature-adapters.ts`: application-input loaders, one per active
feature, run when the router enters the feature's routes (15-01)
- `installed-contract-contributions.ts`: declared contract packages and the
registry the HTTP executor resolves against, filled as features load
- `installed-feature-runtime-registries.ts`: loads every runtime half and
composes the V2 API registries and contract contributions; the platform
overview route calls it before it renders, the boot never does
- `loaded-feature-runtimes.ts`: the same registries as module constants (top-
level await) for Node scripts, tests and registry governance; nothing under
`src` may import it (`boot-does-not-load-every-feature-runtime`)
Feature-specific composition belongs under the feature itself. Central
catalogs must not grow feature-specific branching logic.
Adapter contributions declare the platform capabilities they consume through
`needs`. The generic contribution seam in
`src/features/feature-adapter-contribution.ts` derives the context from that
list, so an HTTP-only feature cannot reach IndexedDB and an IndexedDB-only
feature does not receive the HTTP executor. It also binds
`featureId -> ApplicationFeatureInputs[featureId]` at the contribution
definition site instead of recovering that relationship with a final catalog
cast.
A contribution becomes composable only through
`defineFeatureAdapterContribution()`. That factory adds the private
contribution brand required by `composeFeatureAdapterInputs()`; a raw object
with the same visible fields is rejected by TypeScript and checked again at
runtime. The negative type fixture
`invalid-direct-feature-composition.ts` is part of FE-GATE-003 so this
authority cannot be bypassed by calling the composer directly.
For IndexedDB-backed features, `createIndexedDbRepositoryProvider()` is the
composition helper that maps feature-owned repository identities to typed
`IndexedDbRepositoryPort` instances. It does not create a universal storage
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"]`
Local Draft is a compiled architecture consumer used to prove the second
capability shape; it is not added to the default product manifest. 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.
The bootstrap does not build `indexedDb`: IndexedDB is an opt-in reference
runtime (`productionComposition: false` in
`config/recipes/frontend-capability-recipes.json`). The composition example is
`recipes/frontend-capabilities/indexeddb-feature-capability.ts`
(`createLocalDraftIndexedDbCapability`, exercised by
`tests/recipes/indexeddb-feature-capability.test.ts`). A product that installs a
feature with `needs: ["indexedDb"]` copies it and returns `indexedDb` from the
product-owned `src/bootstrap/product-composition.ts`. Until it does, the feature
capabilities in `src/bootstrap/runtime-adapters.ts` fail the app typecheck, and
`composeFeatureAdapterInputs()` rejects the composition with
`feature <id> needs indexedDb, which the host did not provide`.
The same file is where a product adds any other capability (it augments
`FeaturePlatformCapabilities`) and the credential provider for a product auth
profile. The composition root keeps the order: scope fence, `ANONYMOUS`
profile, product provider, session, scope fence again
(`tests/unit/runtime-adapters-credential-order.test.ts`). Product auth profiles
and runtime-config keys go in `src/contracts/product-contracts.ts`; both join
the template's registries under the same checks
(`tests/unit/product-composition-fixture.test.ts`).
## Presentation consumer surface
`ApplicationProvider` remains the composition root for presentation, but new
consumers should not navigate a root `ApplicationApi` service locator.
Use the narrow hooks in
`src/presentation/providers/application-provider.tsx`:
- `useApplicationSession`
- `useApplicationPreferences`
- `useApplicationDiagnostics`
- `useApplicationRuntime`
- `useApplicationRecovery`
- `useApplicationFeature`
`useApplication` exists only as a deprecated compatibility escape hatch.
## Canonical imports
New feature code should use capability public entry points rather than deep
runtime modules. For HTTP the canonical path is
`src/adapters/http/index.ts`.
Compatibility re-exports may exist during a migration window, but they must be
marked as compatibility/deprecated paths and should not expand into an
unbounded public barrel.
## Policy ownership
Duplication is judged by ownership, not by syntax percentage.
Small local validators can remain duplicated when locality improves auditing.
Business or concurrency policy must have one owner. For example the reference
create mutation keeps definition ID, idempotency requirement, duplicate policy
and invalidation policy in one feature-owned definition and binds only
`scope` and `execute` per usage site.
## Runtime decomposition rule
Large runtime files are not split by line count.
Extract a boundary when it has its own state machine, lifecycle owner, failure
model or compensation/recovery responsibility. Candidate seams include:
- connection/open/upgrade lifecycle,
- transaction ownership,
- migration state machine,
- reconnect/backoff and heartbeat,
- subscription ownership,
- retry/deadline/cancellation ownership,
- settlement/reconciliation/cleanup.
A cohesive 2,000-line state machine can remain together. A 300-line file with
multiple lifecycle owners is a better extraction candidate.
### Current runtime boundary audit
The current large-runtime inventory was reviewed using that rule.
- IndexedDB remains large, but connection, transaction, migration, maintenance
and failure translation already have separate owners/modules.
- resumable upload already separates runtime policy, checkpoint persistence,
HTTP control-plane transport, part execution, cancellation and mutation
locking.
- realtime already separates reconnect policy/coordinator, event codec/consumer
and stream coordination.
- OPFS is separated into browser runtime, journal, byte-store, policy and worker
protocol/runtime responsibilities.
- HTTP V3 still owned retry eligibility/backoff inside the execution state
machine, so that responsibility moved to
`src/adapters/http/http-retry-lifecycle.ts`.
No other runtime is split merely because of its line count.
## Consumer quality metrics
Before adding another abstraction, implement or model multiple real feature
uses and measure:
- feature-owned adapter LOC,
- repeated platform glue,
- number of platform-internal types exposed to the feature,
- central catalog edits,
- files changed for one normal query/command,
- whether native browser/network APIs leak into the feature.
The target feature-development path is:
1. domain type and invariant,
2. use case,
3. port,
4. transport/storage schema plus mapper/codec,
5. capability binding,
6. presentation controller/page.
A product feature should not need to know the retry scheduler, abort ownership,
effect-certainty machinery, transaction leases, reconnect coordinator, OPFS
journal or provider lifecycle.
The executable REST and IndexedDB consumer baselines are recorded in
[`capability-consumer-experience.md`](./capability-consumer-experience.md).
Contract placement and the global-vs-owner-local audit are recorded in
[`contract-ownership.md`](./contract-ownership.md).
## Verification paths
Product-development verification, capability verification and release assurance
are intentionally separate. See
[`docs/testing/taxonomy.md`](../testing/taxonomy.md).
Host-level CI-runner tests belong to `tests/system`, not `tests/unit`.
Reusable capability consumer contracts belong to `tests/contract`.