Files
clean-architecture-frontend…/docs/architecture/frontend-application-foundation.md
T
DongHyeonka 298201f3ee perf(features)!: 기능 실행부를 초기 청크에서 떼어 라우트 진입 때 적재한다 (15-01)
문제
초기 JS는 203,572 / 204,800 B(gzip)였다. 생성 인덱스가 각 기능의
feature-module.ts를 정적으로 import하고, 그 파일이 계약(zod 스키마·mapper
포함), HTTP 계약 contribution, application input 팩토리, route codec까지
모두 끌고 왔다. 참조 모양 기능 1개를 더하면 +3,922 B가 늘어 첫 기능에서
예산을 넘었다.

고른 방법
- 기능을 두 부분으로 나눈다. 선언(FeatureModule: route 표, route runtime
  계약, invalidation, 문구, 부팅 때 release manifest와 맞춰 볼
  contractPackages)은 초기 청크에 남는다. 실행부(FeatureRuntime: V2 API
  계약, adapter contribution, contract contribution)는 feature-runtime.ts로
  옮기고 loadRuntime이 동적 import한다. route codec은 context-routes.ts의
  route handle에 실어 route와 함께 적재한다.
- 적재 시점은 그 기능의 route에 들어갈 때다. ContextRouteGateway가 route
  모듈과 함께 application.features.load(featureId)를 부르고, 끝난 뒤에
  화면을 그린다(공개 포트에는 load만 추가). 들어온 URL의 기능은 route
  모듈과 병렬로 적재해 왕복을 늘리지 않는다. 런타임 설정으로 꺼진 기능은
  적재하지 않는다.
- 조립부는 기능별 로더를 만든다(installed-feature-adapters.ts). contract
  registry는 기능이 적재될 때마다 전체를 다시 합쳐 검증한다
  (installed-contract-contributions.ts). 선언하지 않은 contract package를
  적재하면 거절한다.
- 모든 실행부를 한꺼번에 읽는 registry(V2 API, contract contribution)는
  installed-feature-runtime-registries.ts의 async 함수로, Node·테스트·
  registry 거버넌스용 상수는 top-level await 모듈 loaded-feature-runtimes.ts로
  둔다. src에서 후자를 import하면 새 아키텍처 규칙
  boot-does-not-load-every-feature-runtime이 막는다. 플랫폼 구성 화면은
  route 로더에서 async 함수를 불러 결과를 prop으로 받는다.
- vite.config.ts에 청크 그룹 2개를 둔다. rolldown은 부팅 그래프와 lazy
  청크가 같이 쓰는 모듈을 importer 집합마다 따로 청크로 뗀다. 그대로 두면
  기능마다 선언 청크가 하나씩 늘고(기능당 +1,471 B), 실행부와 공유하는
  플랫폼 모듈(HTTP executor, contract runtime, zod)이 6개 청크로 쪼개져
  템플릿 자체가 +438 B 커졌다. feature-declarations는 모든 기능의 선언을,
  feature-platform은 실행부가 같이 쓰는 부팅 모듈을 한 청크로 묶는다.
  render-boot-failure.tsx가 쓰는 모듈은 feature-platform에서 뺀다(09-03:
  애플리케이션 그래프가 평가 중 던져도 실패 화면은 떠야 한다).

버린 대안
- 부팅 때 feature 청크를 미리 동적 import하고 기다린 뒤 렌더: 분류기는
  lazy로 세지만 첫 렌더 경로의 바이트는 그대로다. 예산을 속이는 것이라
  버렸다.
- 실행부 일부만 지연(adapter와 contribution만): 모두 같은 zod 스키마를
  공유해 줄지 않았다. 실측 +4,031 B로 오히려 늘었다.
- 선언과 실행부를 같은 lazy 청크(context-routes)에 두기: 기능당
  -60 B 수준이라 그룹 없이 목표에 못 미쳤다.
- 페이지 문구까지 실행부로 옮기기: 기능당 약 300~450 B를 더 줄이지만
  i18n catalog를 런타임 등록 구조로 바꿔야 해 이번 범위에서 뺐다.
- boot.tsx를 별도 진입점으로 추가: 분류기가 boot의 동적 import를 모두
  초기로 세어 218,303 B가 됐다.

위험·한계
- FeatureModule 모양이 바뀐다. 다운스트림 기능은 feature-runtime.ts로
  실행부를 옮겨야 한다(BREAKING CHANGE).
- 기능 계약 간 중복(operation, schema, contribution) 검사가 부팅이 아니라
  그 기능의 적재 시점과 Node 검사(loaded-feature-runtimes를 읽는 스크립트·
  테스트)로 옮겨 간다.
- 기능 route에 처음 들어갈 때 실행부 청크(약 5 KB gzip)를 받는다. 플랫폼
  구성 화면은 모든 기능의 실행부를 받은 뒤 그린다. lab 게이트(FE-GATE-026)가
  재는 화면이라 LCP가 조금 늘 수 있다. 측정하지 않았다.
- 청크 그룹은 rolldown 자동 분할을 일부 대신한다. feature-declarations가
  비면 기능당 증가 상한 테스트가 실패한다. feature-platform이 비면 템플릿
  총량(약 2 KB)만 늘고 번들 예산 검사가 잡는다.
- config/contracts/registry-baseline.json의 FE-REG-API/SCHEMA source는 아직
  installed-feature-contracts.ts다. 승인 digest가 걸려 있어 소유자 재승인
  때 고친다. check-registries는 통과한다.
- 예산 안에 들어가는 참조 모양 기능은 약 3개다. 플랫폼 자체가 예산의
  98.8%다.

수치 (vite build, classifyViteJavascript + gzipSync 기본 수준)
- 템플릿: 203,572 B(13파일) -> 202,361 B(16파일), -1,211 B
- 참조 복사본 +1: 207,494 B(+3,922) -> 203,102 B(+741)
- 참조 복사본 +2: 210,818 B(+3,324) -> 203,750 B(+648)
- 참조 복사본 +5: 205,629 B
- lazy JS: 23,516 B -> 28,204 B

검증
- RED: node scripts/run-vitest.ts run tests/unit/feature-shape-growth.test.ts
  "adds at most 1 KiB ... (15-01)" 실패: expected 3934 to be less than or
  equal to 1024
- GREEN: 같은 테스트 통과(+741 B)
- node scripts/run-vitest.ts run tests/unit: 168파일 2,383 통과
- node scripts/run-vitest.ts run tests/component tests/features
  tests/integration tests/contract tests/runtime-schema tests/architecture
  tests/platform tests/recipes (security-followup-archive 제외, pnpm 호출):
  109파일 787 통과
- npx tsc --noEmit: app, node, test, recipes, web-worker, service-worker 통과
- npx eslint 바뀐 파일 통과
- check-architecture.ts(pnpm exec 대신 eslint를 부르는 shim): PASS, 새 규칙이
  boot.tsx의 import를 거절하는 것 확인
- check-adapter-inventory, check-registries, verify-documentation-readiness,
  check-ci-contract: PASS
- e2e Chromium 전체(pnpm 없는 build-frontend + vite preview, 별도 포트):
  55 통과
- storybook build 성공
- 미실행: Firefox·WebKit e2e, 시각 회귀, lab 성능(FE-GATE-026),
  pnpm 경로의 check:bundle, test:system

BREAKING CHANGE: FeatureModule은 id, contracts(선언), routes, messages,
  loadRuntime만 가진다. adapters, contractContributions와 V2 API 계약
  (apiOperations, schemas, runtimeSchemas, mappers)은 defineFeatureRuntime으로
  만든 feature-runtime.ts로, route codec은 context-routes.ts의 route handle
  codecs로 옮긴다. contracts에는 contractPackages를 추가한다.
Refs: docs/reviews/2026-11-01-maturity-review/15-performance.md 15-01,
  16-structure-patterns.md 9절
2026-11-01 21:57:53 +09:00

11 KiB

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

Platform code is horizontal:

  • application: generic application inputs/policies/ports
  • contracts: genuinely cross-capability shared vocabulary and registries
  • adapters: reusable capability runtimes
  • presentation: generic UI/routing/query integration
  • bootstrap: concrete composition

Product business code is vertical:

  • 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 adds indexedDb to the feature capabilities in src/bootstrap/runtime-adapters.ts. Until it does, that object fails the app typecheck, and composeFeatureAdapterInputs() rejects the composition with feature <id> needs indexedDb, which the host did not provide.

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. Contract placement and the global-vs-owner-local audit are recorded in contract-ownership.md.

Verification paths

Product-development verification, capability verification and release assurance are intentionally separate. See docs/testing/taxonomy.md.

Host-level CI-runner tests belong to tests/system, not tests/unit. Reusable capability consumer contracts belong to tests/contract.