chore(review): 1103 예제 화면·시각·접근성 조치 브랜치를 합친다

Refs: docs/reviews/2026-11-03-maturity-review/README.md 09-04 15-01 12-01 11-01 16-03 11-02

# Conflicts:
#	docs/architecture/frontend-application-foundation.md
#	docs/architecture/starter-experience.md
#	docs/manual/03-outside-feature-folder.md
#	tests/unit/runtime-adapters.test.ts
This commit is contained in:
DongHyeonka
2026-11-04 23:04:17 +09:00
50 changed files with 1057 additions and 361 deletions
+6 -2
View File
@@ -67,7 +67,9 @@ jobs:
corepack pnpm install --frozen-lockfile --ignore-scripts
- name: Install Playwright browsers
if: ${{ matrix.browser }}
run: corepack pnpm exec playwright install --with-deps chromium firefox webkit
run: |
corepack pnpm exec playwright install --with-deps chromium firefox webkit
$(command -v sudo || true) apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation
- name: Run blocking gate
run: corepack pnpm ci:gate -- ${{ matrix.gate }}
- name: Upload merge gate evidence
@@ -104,7 +106,9 @@ jobs:
corepack pnpm install --frozen-lockfile --ignore-scripts
- name: Install Playwright browsers
if: ${{ matrix.browser }}
run: corepack pnpm exec playwright install --with-deps chromium firefox webkit
run: |
corepack pnpm exec playwright install --with-deps chromium firefox webkit
$(command -v sudo || true) apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation
- name: Run blocking gate
run: corepack pnpm ci:gate -- ${{ matrix.gate }}
- name: Upload release gate evidence
+7 -2
View File
@@ -68,8 +68,13 @@ What the automated run scans:
never lands on the app shell's loading surface
(`tests/e2e/accessibility.spec.ts`). A public route's `h1` must equal its
catalog title.
- Protected routes after the demo sign-in, never the sign-in prompt. Their API
calls answer an empty list there.
- Protected routes after the demo sign-in, never the sign-in prompt. A list
read answers an empty list in the frame its descriptor declares (inside the
Envelope for `responseEnvelope: "ENVELOPE_V1"`), and the scan runs only once
no alert box is on screen, so a list page is scanned in its empty state. A
read of one resource (a detail page) has no generic answer: that route is
scanned in its failure state and the run records an `a11y-data-state`
annotation.
- 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
@@ -70,9 +70,10 @@ route/form/failure 의미 값
- `check:i18n`은 catalog key와 placeholder parity, backend message JSX 렌더링을
검사한다. 검사 범위는 공통 UI 디렉터리, `src/presentation/pages`, 모든
`src/features/*/presentation`이다. 컴포넌트 갤러리 `src/presentation/examples`는
일부러 뺐다(`scripts/check-i18n.ts`의 `commonDirectories`,
`featurePresentationDirectories`).
`src/features/*/presentation`이다. 플랫폼 구성 화면
`src/presentation/examples`와 예제 화면
`src/features/platform-examples-feature/presentation`(1103/09-04)은 화면
문구 ESLint 규칙에서 일부러 뺐다(`eslint.config.ts`).
- 화면 문구가 catalog에서 오는지는 ESLint `no-restricted-syntax`가 본다
(`eslint.config.ts`의 `screenTextSelectors`, 0929/08-02). 대상은 글자가 든
`JSXText`와 표시·접근성 속성(`aria-label`, `title`, `placeholder`, `alt`,
@@ -119,8 +119,8 @@ Central installed catalogs are aggregation points only:
registry the HTTP executor resolves against, filled as features load
- `installed-feature-runtime-registries.ts`: loads every runtime half and
composes the contract contributions, the FE-REG-API rows projected from
them and the FE-REG-SCHEMA registry; the platform overview route calls it
before it renders, the boot never does
them and the FE-REG-SCHEMA registry; the platform overview page calls it
after it draws its title (1103/15-01), 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`)
+27 -9
View File
@@ -97,14 +97,32 @@ 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`.
`/` (`src/presentation/pages/home-page.tsx`) is the platform's `APP_HOME`; a
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 remove
it with `corepack pnpm test:sample-removal -- --feature=platform-examples-feature`
as the drill. Their routes then leave the registry, the navigation, the
bundle and the manual accessibility list (FE-GATE-028). Their component tests
are in `tests/features/platform-examples-feature/` and go with them.
The platform overview (`/examples/platform`,
`src/presentation/examples/platform-overview-page.tsx`) stays a platform
route. It describes the installed registries, and the lab gate (FE-GATE-026)
times entering it: a feature route's first entry also loads its context's
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.
### Ownership declarations
@@ -198,7 +216,7 @@ Files outside the feature directory. Everything else a feature needs is in
| `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 `[]` |
| `tests/e2e/accessibility.spec.ts` | never per feature (1103/16-03): it fills every path parameter with one value and answers each API request from the installed descriptor, a list read with an empty list in its `responseEnvelope` frame. Edit it only for a protected page that sends something other than an installed GET before it renders | `test:a11y` (FE-GATE-009): a request no installed GET declares fails the route; so does an alert box (`role="alert"`) on a page that read only lists |
| `src/features/product-capabilities.ts` (product-owned) | `needs` names a capability the template does not build: type it in `ProductFeaturePlatformCapabilities`. `FeaturePlatformCapabilities` extends it, so the app, scripts and tests typecheck programs all see the key (an augmentation inside `product-composition.ts` is not seen by the scripts' program) | `check:types`: `Type '"<capability>"' is not assignable to type 'keyof FeaturePlatformCapabilities'` in the feature |
| `src/bootstrap/product-composition.ts` (product-owned) | `needs` names a capability the template does not build: return the capability here, typed in `product-capabilities.ts`. `indexedDb` is built as in `recipes/frontend-capabilities/indexeddb-feature-capability.ts`. Credentials for a product auth profile are returned here too. A product that owns the session (a BFF's httpOnly cookie) returns its session owner from `composeProductSessionOwner` instead of installing it on the host global before boot | `check:types`; at runtime `feature <id> needs <capability>, which the host did not provide`. Without the session owner, `AUTH_MODE: "external"` boots with the session `integration-failed` |
| `src/contracts/product-contracts.ts` (product-owned) | a product auth profile, or a product runtime-config key and its FE-REG-ENV row (`PRODUCT_ENV_REGISTRY`) | auth profile: every gate that loads the operation, with `Installed contract contribution is not composable: <featureId>/<operationId>: unknown authProfileId <id>`. Config key: `check:types` where it is read. Give the key a `.default()` or make it `.optional()`: template tests build their config with `tests/helpers/runtime-config.ts`, which fills the product's defaults, and a required key without a default fails them. FE-REG-ENV row: `check:registries` checks its fields, and `tests/unit/env-registry-coverage.test.ts` (`test:unit`) requires a row for every key, with the schema's `required` and `defaultValue` |
+6 -14
View File
@@ -390,20 +390,12 @@ projectRequest: (input) => Object.freeze({
- 상세 경로는 목록 경로 뒤에 `/items/:<id 이름>`을 붙인다. 예: `/notice/items/:noticeId`. `/notice/:noticeId`로 두지 않는다.
- 라우터(React Router)는 같은 자리에서 정적 경로를 먼저 고른다. 작성 폼 `/notice/new`가 있으면 id가 `new`인 공지는 `/notice/:noticeId`로 열 수 없다.
- `items/`를 끼우면 정적 경로와 겹치지 않는다. 참조 기능도 이렇게 한다(`/examples/reference-resources/items/:resourceId`).
- 경로 파라미터 이름이 `:resourceId`가 아니면 `tests/e2e/accessibility.spec.ts`의 치환 줄에 `.replace`를 하나 잇는다.
```ts
// 지금
: definition.path.replace(":resourceId", "reference-1");
// 예: 공지 기능의 /notice/items/:noticeId
: definition.path.replace(":resourceId", "reference-1").replace(":noticeId", "notice-1");
```
- 이 spec은 등록된 모든 라우트를 열어 axe로 검사한다. 경로 파라미터는 `:resourceId`만 실제 값으로 바꾼다.
- 안 고치면 `:noticeId`라는 글자가 그대로 id로 들어간다. 파라미터 스키마가 그 값을 거부하면 기능 페이지 대신 잘못된 경로 화면을 검사한다.
- 값은 아무 문자열이나 된다. 이 spec은 모든 API에 `[]`로 답해서 상세 페이지는 실패 상태로 그려진다.
- `tests/e2e/accessibility.spec.ts`는 기능마다 고치지 않는다(1103/16-03).
- 이 spec은 등록된 모든 라우트를 열어 axe로 검사한다. 경로 파라미터는 이름과 상관없이 모두 `a11y-1`로 바꾼다. 파라미터 스키마가 이 값을 거부하면 기능 페이지 대신 잘못된 경로 화면을 검사하므로, id 스키마는 짧은 영문·숫자 문자열을 받게 둔다.
- API 요청은 설치된 descriptor에서 method와 `pathTemplate`으로 찾아 답한다. 목록 조회에는 빈 목록을 그 operation의 모양(`responseEnvelope: "ENVELOPE_V1"`이면 Envelope)으로 답한다. 그 뒤 경고 상자(`role="alert"`)가 없는지 본다. 그래서 목록 페이지는 빈 상태로 검사된다.
- 한 자원을 읽는 조회(경로 파라미터가 있고 빈 목록을 받지 않는 GET)에는 빈 목록 말고 답할 것이 없다. 그래서 상세 페이지는 실패 상태로 그려지고, 테스트 결과에 `a11y-data-state` annotation이 남는다.
- 설치된 GET이 아닌 요청을 그리기 전에 보내면 spec이 실패한다(`requests no installed list or single-resource read answers`).
- spec은 h1이 보일 때까지 기다린다. 그래서 상세 페이지는 데이터가 없을 때도 h1을 그린다. 예: `heading={{ title: notice?.title ?? message("notice.detail.titlePending") }}`처럼 데이터가 없으면 고정 제목("공지")을 쓴다.
- 이 줄은 기능 ID를 담지 않는다. 그래서 제거 드릴(11단계)이 잡지 못한다. 기능을 지울 때 손으로 지운다([03 문서](03-outside-feature-folder.md#기능을-지울-때)).
- 기능이 앱 홈(`/`)을 대신하려면 route ID `APP_HOME`을 쓴다. `docs/architecture/starter-experience.md`의 "Product home and layouts" 절을 본다.
③ **잡는 검사 / 못 잡는 것**
@@ -610,7 +602,7 @@ corepack pnpm test:sample-removal -- --feature=invoice-feature
- 남은 파일이 기능 ID나 폴더 이름을 담고 있으면 실패한다.
- 메시지: `<id> removal failed:` 다음 줄 `fixture-id-residue: residue: <files>`
- **못 잡음**: 기능 ID를 담지 않은 폴더 밖 파일. 예: route ID만 적은 e2e spec, `tests/e2e/accessibility.spec.ts`에 더한 파라미터 치환(6단계), `artifacts/tests/a11y-manual/<ROUTE_ID>.md`. 드릴은 `src`와 `tests`만 찾고, a11y 기록은 남아도 검사가 실패하지 않는다.
- **못 잡음**: 기능 ID를 담지 않은 폴더 밖 파일. 예: route ID만 적은 e2e spec, `artifacts/tests/a11y-manual/<ROUTE_ID>.md`. 드릴은 `src`와 `tests`만 찾고, a11y 기록은 남아도 검사가 실패하지 않는다.
④ **쓸 스킬**: `documentation-and-adrs`, `deprecation-and-migration`
+1 -3
View File
@@ -101,7 +101,7 @@ release admission refused for staging:
언제와 실패 메시지는 정본 표에 있다. 여기에는 무엇을 위해 고치는지만 적는다.
- `src/contexts/<context>/context-layout.tsx`: context가 `AppShell` 대신 자기 틀을 쓸 때. 예제: `tests/helpers/fixture-layout-product.tsx`.
- `tests/e2e/accessibility.spec.ts`: 경로 파라미터가 `:resourceId`가 아닐 때, 또는 모든 API가 `[]`를 답하면 그려지지 않는 보호 페이지일 때. 치환 줄 고치는 법은 [01 문서 6단계](01-add-a-feature.md#6단계-라우트).
- `tests/e2e/accessibility.spec.ts`: 기능마다 고치지 않는다. 경로 파라미터와 API 응답을 설치된 라우트·descriptor에서 만든다. 보호 페이지가 설치된 GET이 아닌 요청을 그리기 전에 보낼 때만 손본다. 자세한 동작은 [01 문서 6단계](01-add-a-feature.md#6단계-라우트).
- `src/features/product-capabilities.ts`: `needs`에 템플릿이 만들지 않는 capability를 적었을 때. 그 capability의 타입을 `ProductFeaturePlatformCapabilities`에 적는다.
- `product-composition.ts` 안에서 `FeaturePlatformCapabilities`를 보강(`declare module`)하면 `check:types:node`가 그 키를 보지 못한다.
- `src/bootstrap/product-composition.ts`: 위 capability의 값을 돌려줄 때. 제품 인증 프로필의 자격 증명도 여기서 준다.
@@ -177,8 +177,6 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE)
- `artifacts/tests/a11y-manual/<ROUTE_ID>.md` (라우트마다)
- 남아도 검사는 실패하지 않는다. 검사는 등록된 라우트의 기록만 읽는다. 그래서 잊기 쉽다.
- 기능 전용 `tests/e2e/` spec
- `tests/e2e/accessibility.spec.ts`에 더한 `.replace(":<파라미터>", "<값>")`
- 기능 ID를 담지 않아 제거 드릴이 잡지 못한다. 남아도 어떤 검사도 실패하지 않는다.
- `config/runtime/<profile>.json`의 `FEATURE_OVERRIDES` 키
- `config/testing/risk-coverage.json`에서 그 기능을 가리키는 행
- 그 기능만 쓰던 제품 capability, 제품 인증 프로필, 계약 패키지 의존성
+1 -1
View File
@@ -73,7 +73,7 @@ corepack pnpm create:feature <id> [--context <context id>] [--package @scope/nam
- GET 1개: `SAFE`, `EXTERNAL_BEARER`, 응답은 항목 배열.
- 쿼리 1개: `LIST_STANDARD` profile.
- 무효화 topic 1개, namespace 1개, edge 1개.
- 빈 배열 응답은 공유 빈 상태 화면으로 그린다. `tests/e2e/accessibility.spec.ts`가 모든 API에 `[]`를 답하기 때문이다.
- 빈 배열 응답은 공유 빈 상태 화면으로 그린다. `tests/e2e/accessibility.spec.ts`는 이 목록 조회에 빈 목록을 Envelope 모양으로 답하고, 경고 상자가 없는지 본 뒤 axe를 돌린다. 그래서 생성한 라우트는 빈 상태 화면으로 검사된다.
한도·마감 같은 숫자는 `scripts/create-feature.ts`의 템플릿이 정본이다.
@@ -955,7 +955,10 @@ Playwright `toHaveScreenshot()`을 사용한다.
- browser 버전과 viewport·scale은 `playwright.visual.config.ts`로, 글꼴은
`tests/visual/fonts.conf`로 고정(Linux 전용). 러너에는
`fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation`
패키지가 필요하고, 없으면 `visual-fonts` 검사가 설치 명령을 보여 주며 실패한다
패키지가 필요하고, 없으면 `visual-fonts` 검사가 설치 명령을 보여 주며 실패한다.
CI의 브라우저 설치 단계가 같은 패키지를 설치한다. 목록은
`scripts/lib/visual-test-fonts.ts` 한 곳에 있고 생성기와 `visual-fonts` 검사가
같이 읽는다(1103/11-02)
- animation/caret 비활성화
- clock/random/network fixture 고정
- 개인정보와 동적 ID mask
+10 -3
View File
@@ -458,8 +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 component gallery (src/presentation/examples) and
// stories are workshop code and stay out; tests are outside these folders.
// 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.
const screenTextDirectories = [
"src/presentation/boundaries",
"src/presentation/components",
@@ -911,7 +912,13 @@ export default [
`${directory}/**/*.tsx`,
`tests/fixtures/i18n/*/${directory}/**/*.tsx`,
]),
ignores: ["**/*.stories.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
// locale on purpose (08-07).
ignores: [
"**/*.stories.tsx",
"src/features/platform-examples-feature/presentation/**",
],
rules: {
"no-restricted-syntax": [
...commonSecurityRules["no-restricted-syntax"],
+3 -3
View File
@@ -10,9 +10,9 @@
"routeChunks": {
"route-home": "src/presentation/pages/home-page.tsx",
"route-examples-platform": "src/presentation/examples/platform-overview-page.tsx",
"route-examples-ui": "src/presentation/examples/ui-gallery-page.tsx",
"route-examples-states": "src/presentation/examples/state-gallery-page.tsx",
"route-examples-auth": "src/presentation/examples/auth-example-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",
+3 -2
View File
@@ -59,8 +59,9 @@ 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` is the component gallery and stays out of scope
// on purpose.
// `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.
const forbiddenFixtureRoot = "tests/fixtures/i18n/forbidden";
const allowedFixtureRoot = "tests/fixtures/i18n/allowed";
const sourceRoot = fixtureMode ? forbiddenFixtureRoot : ".";
+7 -1
View File
@@ -23,6 +23,7 @@ import {
assertSafePublishLeaf,
ensureSafePublishDirectory,
} from "./lib/ci-gate-log.ts";
import { VISUAL_TEST_FONT_INSTALL_ARGUMENTS } from "./lib/visual-test-fonts.ts";
export type GenerateCiWorkflowOptions = Readonly<{
root: string;
@@ -196,7 +197,12 @@ function renderStep(
return [
" - name: Install Playwright browsers",
...(job.kind === "gate-matrix" ? [" if: ${{ matrix.browser }}"] : []),
" run: corepack pnpm exec playwright install --with-deps chromium firefox webkit",
" run: |",
" corepack pnpm exec playwright install --with-deps chromium firefox webkit",
// 1103/11-02. The visual goldens' faces (tests/visual/fonts.conf) are
// not among Playwright's dependencies. `--with-deps` has refreshed the
// package lists; sudo only where the runner is not root.
` $(command -v sudo || true) ${VISUAL_TEST_FONT_INSTALL_ARGUMENTS}`,
];
case "run-gate": {
if (job.kind === "gate-matrix") {
+16
View File
@@ -0,0 +1,16 @@
/**
* 1103/11-02. The Debian/Ubuntu packages that hold the four faces the visual
* goldens were captured with. `tests/visual/fonts.conf` shows Chromium only
* their directories, Playwright's `--with-deps` does not install them, and
* `tests/visual/fonts.setup.ts` fails with this list when one is missing. The
* CI browser step (`scripts/generate-ci-workflow.ts`) installs the same list,
* so the hint and the runner cannot name different packages.
*/
export const VISUAL_TEST_FONT_PACKAGES = Object.freeze([
"fonts-noto-core",
"fonts-noto-cjk",
"fonts-noto-cjk-extra",
"fonts-liberation",
] as const);
export const VISUAL_TEST_FONT_INSTALL_ARGUMENTS = `apt-get install -y ${VISUAL_TEST_FONT_PACKAGES.join(" ")}`;
@@ -0,0 +1,12 @@
/**
* 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/*`;
* `reference-context` keeps the more specific `examples/reference-resources/*`.
*/
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;
-18
View File
@@ -23,24 +23,6 @@ export const PLATFORM_ROUTE_RUNTIME_CONTRACT = Object.freeze({
paramsCodec: "none",
searchCodec: "none",
}),
EXAMPLES_UI: runtime({
routeId: "EXAMPLES_UI",
moduleId: "ui-gallery-page",
paramsCodec: "none",
searchCodec: "none",
}),
EXAMPLES_STATES: runtime({
routeId: "EXAMPLES_STATES",
moduleId: "state-gallery-page",
paramsCodec: "none",
searchCodec: "none",
}),
EXAMPLES_AUTH: runtime({
routeId: "EXAMPLES_AUTH",
moduleId: "auth-example-page",
paramsCodec: "none",
searchCodec: "none",
}),
NOT_FOUND: runtime({
routeId: "NOT_FOUND",
moduleId: "not-found-page",
-39
View File
@@ -43,45 +43,6 @@ export const PLATFORM_ROUTE_REGISTRY = Object.freeze({
navigationLabel: "플랫폼 구성",
navigationOrder: 15,
}),
EXAMPLES_UI: route({
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: route({
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: route({
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,
}),
NOT_FOUND: route({
routeId: "NOT_FOUND",
path: "*",
@@ -22,8 +22,10 @@ import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.
*
* The app boot never calls this: at runtime the composition root loads one
* feature at a time when its routes are entered (`installed-feature-adapters.ts`).
* The platform overview route calls it before it renders, and Node scripts and
* tests read the same result through `loaded-feature-runtimes.ts`.
* The platform overview page calls it after it draws its title (1103/15-01:
* awaiting it in the route module added a request round to entering the
* route), and Node scripts and tests read the same result through
* `loaded-feature-runtimes.ts`.
*/
export async function loadInstalledFeatureRuntimeRegistries() {
const runtimes = Object.freeze(
@@ -0,0 +1,17 @@
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],
}),
}),
),
);
@@ -0,0 +1,82 @@
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);
@@ -0,0 +1,23 @@
/**
* 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);
@@ -0,0 +1,27 @@
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;
@@ -0,0 +1,13 @@
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,8 +1,8 @@
import { PageHeader } from "../design-system/index.ts";
import { PageHeader } from "../../../presentation/design-system/index.ts";
import {
useSession,
useSessionAction,
} from "../providers/session-provider.tsx";
} from "../../../presentation/providers/session-provider.tsx";
export default function AuthExamplePage() {
const { sessionState } = useSession();
@@ -0,0 +1,17 @@
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,7 +1,7 @@
import { useState } from "react";
import { deriveAsyncState } from "../../application/view-models/async-state.ts";
import { createFailure } from "../../contracts/errors.ts";
import { deriveAsyncState } from "../../../application/view-models/async-state.ts";
import { createFailure } from "../../../contracts/errors.ts";
import {
AsyncSurface,
EmptySurface,
@@ -13,7 +13,7 @@ import {
Button,
Card,
PageHeader,
} from "../design-system/index.ts";
} from "../../../presentation/design-system/index.ts";
export default function StateGalleryPage() {
const [lastAction, setLastAction] = useState(
@@ -19,7 +19,7 @@ import {
ToastProvider,
Tooltip,
useToast,
} from "../design-system/index.ts";
} from "../../../presentation/design-system/index.ts";
const COLOR_TOKENS = Object.freeze([
["Surface", "--color-surface"],
@@ -1,4 +1,4 @@
import { type ComponentType, useEffect, useState } from "react";
import { Suspense, use, useEffect, useState } from "react";
import {
HTTP_EXECUTION_CEILINGS,
@@ -11,7 +11,6 @@ import {
import { SERVER_STATE_PROFILES } from "../../contracts/server-state.ts";
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../features/installed-contract-contributions.ts";
import { ROUTE_REGISTRY } from "../../features/installed-feature-contracts.ts";
import { loadInstalledFeatureRuntimeRegistries } from "../../features/installed-feature-runtime-registries.ts";
import type {
RuntimeCapabilityId,
RuntimeCapabilityStatus,
@@ -21,6 +20,7 @@ import {
Card,
DataTable,
EmptySurface,
LoadingSurface,
PageHeader,
type DataTableColumn,
} from "../design-system/index.ts";
@@ -309,14 +309,71 @@ function buildOperationRows(
);
}
const CONTRACTS_LOADING = "기능 실행부를 불러오고 있습니다.";
/** The summary counts that only the features' runtime halves know. */
function ContractMetrics({
contracts,
}: Readonly<{ contracts: Promise<ComposedContractContributions> }>) {
const composed = use(contracts);
const fixtureContributions = composed.contributions.filter(
(contribution) => contribution.source.kind === "TEMPLATE_FIXTURE",
).length;
return (
<>
<Metric
label="HTTP 오퍼레이션"
value={`${buildOperationRows(composed).length}개`}
/>
<Metric
label="외부 계약 패키지"
value={`${EXPECTED_CONTRACT_SET_PACKAGES.length}개`}
hint={`템플릿 픽스처 ${fixtureContributions}개`}
/>
</>
);
}
function ContractTables({
contracts,
}: Readonly<{ contracts: Promise<ComposedContractContributions> }>) {
const composed = use(contracts);
return (
<>
<DataTable
caption="설치된 HTTP 오퍼레이션"
columns={OPERATION_COLUMNS}
rows={buildOperationRows(composed)}
rowKey={(row) => row.operationId}
empty={
<EmptySurface
title="설치된 HTTP 오퍼레이션이 없습니다."
description="계약 기여물을 추가하면 이 표에 나타납니다."
/>
}
/>
{/* 1101/07-03. Drawn only when a contract skips validation by name. */}
<DataTable
caption="런타임 검증을 생략한 계약"
columns={UNVALIDATED_COLUMNS}
rows={listUnvalidatedPayloads(composed)}
rowKey={(row) => `${row.contractId}.${row.validator}`}
empty={null}
/>
</>
);
}
/**
* 15-01. The page lists every installed HTTP operation, which lives in the
* features' runtime halves. Its route loads them all before it renders
* (`loadPlatformOverviewPage`); the boot never does.
* features' runtime halves; the boot never loads them. 1103/15-01: only the
* parts that read them wait (`contracts`). The title and everything the
* declarations know draw at once, so entering the route costs the page chunk
* alone, not a second request round for every feature's runtime.
*/
export function PlatformOverviewPage({
contracts,
}: Readonly<{ contracts: ComposedContractContributions }>) {
}: Readonly<{ contracts: Promise<ComposedContractContributions> }>) {
const runtime = useApplicationRuntime();
const [release, setRelease] = useState<
Awaited<ReturnType<typeof runtime.getReleaseSummary>> | "failed" | null
@@ -338,16 +395,11 @@ export function PlatformOverviewPage({
}, [runtime]);
const routes = Object.values(ROUTE_REGISTRY);
const operations = buildOperationRows(contracts);
const capabilities = runtime.getCapabilitySnapshot();
const features = runtime.getFeatureSnapshot();
const activeCapabilityCount = capabilities.filter(
(status) => status.active > 0,
).length;
const fixtureContributions =
contracts.contributions.filter(
(contribution) => contribution.source.kind === "TEMPLATE_FIXTURE",
).length;
return (
// 08-07. Example copy is Korean in every locale (outside the catalog).
@@ -413,12 +465,19 @@ export function PlatformOverviewPage({
</header>
<dl className="platform-metric-grid">
<Metric label="라우트" value={`${routes.length}개`} />
<Metric label="HTTP 오퍼레이션" value={`${operations.length}개`} />
<Metric
label="외부 계약 패키지"
value={`${EXPECTED_CONTRACT_SET_PACKAGES.length}개`}
hint={`템플릿 픽스처 ${fixtureContributions}개`}
/>
<Suspense
fallback={
<>
<Metric label="HTTP 오퍼레이션" value="확인 중" />
<Metric
label="외부 계약 패키지"
value={`${EXPECTED_CONTRACT_SET_PACKAGES.length}개`}
/>
</>
}
>
<ContractMetrics contracts={contracts} />
</Suspense>
<Metric
label="선택적 런타임 능력"
value={`${activeCapabilityCount} / ${capabilities.length}`}
@@ -464,26 +523,9 @@ export function PlatformOverviewPage({
포함되지 않습니다. 제품은 픽스처를 지우고 자기 패키지를 고정합니다.
</p>
</header>
<DataTable
caption="설치된 HTTP 오퍼레이션"
columns={OPERATION_COLUMNS}
rows={operations}
rowKey={(row) => row.operationId}
empty={
<EmptySurface
title="설치된 HTTP 오퍼레이션이 없습니다."
description="계약 기여물을 추가하면 이 표에 나타납니다."
/>
}
/>
{/* 1101/07-03. Drawn only when a contract skips validation by name. */}
<DataTable
caption="런타임 검증을 생략한 계약"
columns={UNVALIDATED_COLUMNS}
rows={listUnvalidatedPayloads(contracts)}
rowKey={(row) => `${row.contractId}.${row.validator}`}
empty={null}
/>
<Suspense fallback={<LoadingSurface description={CONTRACTS_LOADING} />}>
<ContractTables contracts={contracts} />
</Suspense>
</section>
<section
@@ -592,15 +634,31 @@ export function PlatformOverviewPage({
);
}
/** The route module: the page bound to the registries it reads. */
export async function loadPlatformOverviewPage(): Promise<
Readonly<{ default: ComponentType }>
> {
const registries = await loadInstalledFeatureRuntimeRegistries();
const contracts = registries.composedContractContributions;
return Object.freeze({
default: function InstalledPlatformOverviewPage() {
return <PlatformOverviewPage contracts={contracts} />;
},
});
let installedContracts: Promise<ComposedContractContributions> | undefined;
/**
* One load shared by both waiting parts and by later visits. The composer is
* imported here too, so its code is not in the page chunk the title waits
* for. A duplicate across features rejects here and reaches the route
* boundary, as it did when the route awaited it; a failed load is dropped so
* the next visit retries.
*/
function loadInstalledContracts(): Promise<ComposedContractContributions> {
if (installedContracts === undefined) {
const loading = import(
"../../features/installed-feature-runtime-registries.ts"
)
.then((module) => module.loadInstalledFeatureRuntimeRegistries())
.then((registries) => registries.composedContractContributions);
loading.catch(() => {
if (installedContracts === loading) installedContracts = undefined;
});
installedContracts = loading;
}
return installedContracts;
}
/** The route module: the page bound to the installed registries. */
export default function InstalledPlatformOverviewPage() {
return <PlatformOverviewPage contracts={loadInstalledContracts()} />;
}
+4 -20
View File
@@ -45,12 +45,6 @@ const PLATFORM_KO_MESSAGES = {
"route.APP_HOME.title": "Clean Architecture Frontend",
"route.EXAMPLES_PLATFORM.navigation": "플랫폼 구성",
"route.EXAMPLES_PLATFORM.title": "플랫폼 구성",
"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": "인증 연동",
"route.NOT_FOUND.navigation": "찾을 수 없음",
"route.NOT_FOUND.title": "페이지를 찾을 수 없습니다.",
"async.loading": "불러오는 중",
@@ -117,10 +111,8 @@ const PLATFORM_KO_MESSAGES = {
"home.runtime.summary": "빌드 {buildId} · 릴리스 {releaseId}",
"home.starter.title": "준비된 화면 살펴보기",
"home.starter.description":
"설치된 라우트와 계약, 런타임 능력은 플랫폼 구성 화면에서, 공통 구성요소와 비동기 화면 상태는 예제 라우트에서 확인하세요.",
"home.starter.platform": "플랫폼 구성 보기",
"home.starter.ui": "UI 구성요소 보기",
"home.starter.states": "화면 상태 보기",
"내비게이션의 첫 화면을 바로 엽니다. 템플릿에서는 설치된 라우트·계약·런타임 능력, 공통 구성요소, 비동기 화면 상태를 보여 주는 예제 화면입니다.",
"home.starter.open": "{title} 보기",
"page.notFound.title": "페이지를 찾을 수 없습니다.",
"page.notFound.description":
"주소를 확인하거나 준비된 시작 화면으로 돌아가세요.",
@@ -258,12 +250,6 @@ const PLATFORM_EN_MESSAGES = {
"route.APP_HOME.title": "Clean Architecture Frontend",
"route.EXAMPLES_PLATFORM.navigation": "Platform composition",
"route.EXAMPLES_PLATFORM.title": "Platform composition",
"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",
"route.NOT_FOUND.navigation": "Not found",
"route.NOT_FOUND.title": "Page not found",
"async.loading": "Loading",
@@ -329,10 +315,8 @@ const PLATFORM_EN_MESSAGES = {
"home.runtime.summary": "Build {buildId} · Release {releaseId}",
"home.starter.title": "Explore the prepared screens",
"home.starter.description":
"See installed routes, contracts and runtime capabilities on the platform composition page, and common components and async screen states on the example routes.",
"home.starter.platform": "View platform composition",
"home.starter.ui": "View UI components",
"home.starter.states": "View screen states",
"Open the first screens of the navigation. In the template these are the example screens for installed routes, contracts and runtime capabilities, common components and async screen states.",
"home.starter.open": "View {title}",
"page.notFound.title": "Page not found.",
"page.notFound.description": "Check the address or return to the start page.",
"template.breadcrumb": "Current location",
+35 -25
View File
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { routePath } from "../../features/installed-feature-contracts.ts";
import { NAVIGATION_ROUTES } from "../../features/installed-feature-contracts.ts";
import { PageHeader } from "../design-system/index.ts";
import { useLocale } from "../i18n/index.ts";
import { useApplicationRuntime } from "../providers/application-provider.tsx";
@@ -12,9 +12,19 @@ const READINESS_ITEMS = Object.freeze([
"accessibility",
] as const);
/**
* 1103/09-04. The first screens of the navigation after this page. In the
* template those are its example screens, a removable feature; a
* product that leaves them out gets its own screens here, and the page names
* no feature's route.
*/
const STARTER_ROUTES = Object.freeze(
NAVIGATION_ROUTES.filter((route) => route.routeId !== "APP_HOME").slice(0, 3),
);
export default function HomePage() {
const runtime = useApplicationRuntime();
const { message } = useLocale();
const { message, resolve } = useLocale();
const [release, setRelease] = useState<
Awaited<ReturnType<typeof runtime.getReleaseSummary>> | "failed" | null
>(null);
@@ -59,29 +69,29 @@ export default function HomePage() {
})
: message("home.runtime.checking")}
</p>
<section className="ui-panel starter-actions" aria-labelledby="starter-title">
<div>
<h2 id="starter-title">{message("home.starter.title")}</h2>
<p>{message("home.starter.description")}</p>
</div>
<div className="button-row">
<Link className="ui-button" to={routePath("EXAMPLES_PLATFORM")}>
{message("home.starter.platform")}
</Link>
<Link
className="ui-button ui-button--secondary"
to={routePath("EXAMPLES_UI")}
>
{message("home.starter.ui")}
</Link>
<Link
className="ui-button ui-button--secondary"
to={routePath("EXAMPLES_STATES")}
>
{message("home.starter.states")}
</Link>
</div>
</section>
{STARTER_ROUTES.length > 0 ? (
<section className="ui-panel starter-actions" aria-labelledby="starter-title">
<div>
<h2 id="starter-title">{message("home.starter.title")}</h2>
<p>{message("home.starter.description")}</p>
</div>
<div className="button-row">
{STARTER_ROUTES.map((route, index) => (
<Link
key={route.routeId}
className={
index === 0 ? "ui-button" : "ui-button ui-button--secondary"
}
to={route.path}
>
{message("home.starter.open", {
title: resolve(`route.${route.routeId}.navigation`),
})}
</Link>
))}
</div>
</section>
) : null}
</section>
);
}
+3 -16
View File
@@ -24,22 +24,9 @@ function runtime(
export const PLATFORM_ROUTE_RUNTIME = {
APP_HOME: runtime("APP_HOME", () => import("../pages/home-page.tsx")),
EXAMPLES_PLATFORM: runtime("EXAMPLES_PLATFORM", () =>
import("../examples/platform-overview-page.tsx").then((module) =>
module.loadPlatformOverviewPage(),
),
),
EXAMPLES_UI: runtime(
"EXAMPLES_UI",
() => import("../examples/ui-gallery-page.tsx"),
),
EXAMPLES_STATES: runtime(
"EXAMPLES_STATES",
() => import("../examples/state-gallery-page.tsx"),
),
EXAMPLES_AUTH: runtime(
"EXAMPLES_AUTH",
() => import("../examples/auth-example-page.tsx"),
EXAMPLES_PLATFORM: runtime(
"EXAMPLES_PLATFORM",
() => import("../examples/platform-overview-page.tsx"),
),
NOT_FOUND: runtime(
"NOT_FOUND",
@@ -193,10 +193,10 @@ describe("feature routes and platform routes", () => {
expect(() =>
app(
context("examples", "examples/*", [
feature("examples-feature", { EXAMPLES_UI_COPY: "/examples/ui" }),
feature("examples-feature", { EXAMPLES_PLATFORM_COPY: "/examples/platform" }),
]),
),
).toThrow(/EXAMPLES_UI_COPY.*\/examples\/ui.*examples-feature.*examples.*EXAMPLES_UI/);
).toThrow(/EXAMPLES_PLATFORM_COPY.*\/examples\/platform.*examples-feature.*examples.*EXAMPLES_PLATFORM/);
});
it("rejects the same path under a layout of its own", () => {
@@ -204,10 +204,10 @@ describe("feature routes and platform routes", () => {
expect(() =>
app(
context("examples", "examples/*", [
feature("examples-feature", { EXAMPLES_UI_COPY: "/examples/ui" }),
feature("examples-feature", { EXAMPLES_PLATFORM_COPY: "/examples/platform" }),
], layout),
),
).toThrow(/EXAMPLES_UI_COPY.*EXAMPLES_UI/);
).toThrow(/EXAMPLES_PLATFORM_COPY.*EXAMPLES_PLATFORM/);
});
it("rejects two feature routes with the same path, naming both", () => {
+6 -39
View File
@@ -3,10 +3,8 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import { createAnonymousSessionAdapter } from "../../src/adapters/auth/external-session-adapter.ts";
import StateGalleryPage from "../../src/presentation/examples/state-gallery-page.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import HomePage from "../../src/presentation/pages/home-page.tsx";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
@@ -15,10 +13,11 @@ import { AppRouter } from "../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
/**
* The starter screens (`/` and `/examples/*`) are the template's content, not
* the platform (0929/10-02). A product that replaces them deletes the
* `starter-*.test.tsx` files with them; the platform tests run on the
* test-only feature's pages and keep passing.
* The starter screens (`/` and `/examples/platform`) are the template's
* content, not the platform (0929/10-02). A product that replaces them deletes
* the `starter-*.test.tsx` files with them; the platform tests run on the
* test-only feature's pages and keep passing. 1103/09-04: the other example
* screens are a removable feature, tested in its own test folder.
*/
function renderApp(
@@ -83,35 +82,3 @@ describe("starter home page", () => {
).not.toBeInTheDocument();
});
});
describe("starter example pages", () => {
it("returns to the current URL with its hash from the auth example page", async () => {
const user = userEvent.setup();
const beginSignIn = vi.fn(async () => {});
renderApp(
"/examples/auth#session",
createTestApplication({
session: { ...createAnonymousSessionAdapter(), beginSignIn },
}),
);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
expect(beginSignIn).toHaveBeenCalledWith("/examples/auth#session");
});
it("nests the state gallery's titles under the card and section around them (08-05)", () => {
render(<StateGalleryPage />);
expect(
screen.getByRole("heading", { name: "아직 표시할 항목이 없습니다.", level: 4 }),
).toBeVisible();
expect(screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent))
.toEqual(expect.arrayContaining(["빈 화면", "복구 가능한 오류"]));
// Access states sit directly under the section's h2.
expect(
screen.queryAllByRole("heading", { level: 2 }).map((h) => h.textContent),
).toEqual(["비동기 데이터 상태", "접근과 탐색 상태"]);
});
});
@@ -1,9 +1,12 @@
// @vitest-environment jsdom
import { render, screen, waitFor, within } from "@testing-library/react";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { composeContractContributions } from "../../src/contracts/external-contract-runtime.ts";
import {
composeContractContributions,
type ComposedContractContributions,
} from "../../src/contracts/external-contract-runtime.ts";
import { unvalidatedPayload } from "../../src/contracts/unvalidated-payload.ts";
import { SERVER_STATE_PROFILES } from "../../src/contracts/server-state.ts";
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts";
@@ -24,14 +27,31 @@ import { createRuntimeCapabilitiesStub } from "../helpers/runtime-capabilities-s
* template that removes its sample feature still satisfies this suite.
*/
function renderPage() {
return render(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<PlatformOverviewPage contracts={COMPOSED_CONTRACT_CONTRIBUTIONS} />
</LocaleProvider>
</ApplicationProvider>,
);
/**
* 1103/15-01. The contract tables wait for the features' runtime halves
* behind their own Suspense boundary; `act` lets the given promise settle.
*/
async function renderPage(
options: Readonly<{
application?: ReturnType<typeof createTestApplication>;
contracts?: ComposedContractContributions;
}> = {},
) {
await act(async () => {
render(
<ApplicationProvider
application={options.application ?? createTestApplication()}
>
<LocaleProvider>
<PlatformOverviewPage
contracts={Promise.resolve(
options.contracts ?? COMPOSED_CONTRACT_CONTRIBUTIONS,
)}
/>
</LocaleProvider>
</ApplicationProvider>,
);
});
}
function tableByCaption(caption: string): HTMLElement {
@@ -48,8 +68,8 @@ function metricByLabel(scope: HTMLElement, label: string): HTMLElement {
}
describe("platform overview page", () => {
it("renders one route row per installed route registry entry", () => {
renderPage();
it("renders one route row per installed route registry entry", async () => {
await renderPage();
const table = tableByCaption("설치된 라우트 목록");
const dataRows = within(table).getAllByRole("row").slice(1);
@@ -62,11 +82,11 @@ describe("platform overview page", () => {
}
});
it("renders one operation row per installed HTTP contract", () => {
it("renders one operation row per installed HTTP contract", async () => {
const operationIds = [
...COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.keys(),
];
renderPage();
await renderPage();
if (operationIds.length === 0) {
expect(
@@ -87,7 +107,7 @@ describe("platform overview page", () => {
});
// 1101/07-03. A skipped validation is shown, not just composed.
it("lists the operations that skip runtime validation, with the reason", () => {
it("lists the operations that skip runtime validation, with the reason", async () => {
const [listRow, ...rest] = TEST_CONTRACT_CONTRIBUTION.http;
const contracts = composeContractContributions([
Object.freeze({
@@ -107,13 +127,7 @@ describe("platform overview page", () => {
]),
}),
]);
render(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<PlatformOverviewPage contracts={contracts} />
</LocaleProvider>
</ApplicationProvider>,
);
await renderPage({ contracts });
const table = tableByCaption("런타임 검증을 생략한 계약");
const [row, ...others] = within(table).getAllByRole("row").slice(1);
@@ -122,16 +136,16 @@ describe("platform overview page", () => {
expect(within(row!).getByText("typed by the package")).toBeVisible();
});
it("shows no skipped-validation list when every operation validates", () => {
renderPage();
it("shows no skipped-validation list when every operation validates", async () => {
await renderPage();
expect(
screen.queryByRole("table", { name: "런타임 검증을 생략한 계약" }),
).toBeNull();
});
it("renders every fixed server-state profile with its own budget", () => {
renderPage();
it("renders every fixed server-state profile with its own budget", async () => {
await renderPage();
const table = tableByCaption("서버 상태 프로파일");
for (const profile of Object.values(SERVER_STATE_PROFILES)) {
@@ -142,8 +156,8 @@ describe("platform overview page", () => {
);
});
it("labels a capability that was never selected as unselected", () => {
renderPage();
it("labels a capability that was never selected as unselected", async () => {
await renderPage();
const region = screen.getByRole("region", { name: "선택적 런타임 능력" });
@@ -151,21 +165,15 @@ describe("platform overview page", () => {
expect(within(region).queryByText("운영자가 비활성화함")).toBeNull();
});
it("separates an operator disable from a capability that was never selected", () => {
render(
<ApplicationProvider
application={createTestApplication({
runtimeCapabilities: createRuntimeCapabilitiesStub({
SERVICE_WORKER: { selected: 1, active: 0, override: "DISABLED" },
OFFLINE_COMMANDS: { selected: 1, active: 1 },
}),
})}
>
<LocaleProvider>
<PlatformOverviewPage contracts={COMPOSED_CONTRACT_CONTRIBUTIONS} />
</LocaleProvider>
</ApplicationProvider>,
);
it("separates an operator disable from a capability that was never selected", async () => {
await renderPage({
application: createTestApplication({
runtimeCapabilities: createRuntimeCapabilitiesStub({
SERVICE_WORKER: { selected: 1, active: 0, override: "DISABLED" },
OFFLINE_COMMANDS: { selected: 1, active: 1 },
}),
}),
});
const region = screen.getByRole("region", { name: "선택적 런타임 능력" });
@@ -174,11 +182,11 @@ describe("platform overview page", () => {
expect(within(region).getAllByText("미선택")).toHaveLength(2);
});
it("counts installed contract packages separately from template fixtures", () => {
it("counts installed contract packages separately from template fixtures", async () => {
const fixtures = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.filter(
(contribution) => contribution.source.kind === "TEMPLATE_FIXTURE",
).length;
renderPage();
await renderPage();
const summary = screen.getByRole("region", { name: "설치 요약" });
const packages = metricByLabel(summary, "외부 계약 패키지");
@@ -199,7 +207,7 @@ describe("platform overview page", () => {
});
it("renders the verified release identity once the runtime resolves it", async () => {
renderPage();
await renderPage();
const region = screen.getByRole("region", { name: "릴리스 신원" });
await waitFor(() =>
@@ -213,24 +221,18 @@ describe("platform overview page", () => {
});
it("stops the release metrics from loading forever", async () => {
render(
<ApplicationProvider
application={createTestApplication({
releaseInfo: {
getCurrent: async () => {
throw new Error("manifest unavailable");
},
refresh: async () => {
throw new Error("manifest unavailable");
},
await renderPage({
application: createTestApplication({
releaseInfo: {
getCurrent: async () => {
throw new Error("manifest unavailable");
},
})}
>
<LocaleProvider>
<PlatformOverviewPage contracts={COMPOSED_CONTRACT_CONTRIBUTIONS} />
</LocaleProvider>
</ApplicationProvider>,
);
refresh: async () => {
throw new Error("manifest unavailable");
},
},
}),
});
await waitFor(() =>
expect(
screen.getByText("런타임 정보를 확인하지 못했습니다."),
@@ -0,0 +1,54 @@
// @vitest-environment jsdom
import { render, screen, within } from "@testing-library/react";
import { Suspense } from "react";
import { describe, expect, it, vi } from "vitest";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
import { PLATFORM_ROUTE_RUNTIME } from "../../src/presentation/routes/route-runtime.tsx";
import { createTestApplication } from "../helpers/create-test-application.ts";
// The feature runtimes never arrive: the route must not wait for them.
vi.mock("../../src/features/installed-feature-runtime-registries.ts", () => ({
loadInstalledFeatureRuntimeRegistries: () => new Promise(() => {}),
}));
/**
* 1103/15-01. The lab gate (FE-GATE-026) times this route from the click to
* its heading. Its route module used to await every installed feature's
* runtime half first, which added a second request round to the click.
*/
describe("platform overview route module", () => {
it("draws the title and the declared routes before the feature runtimes load", async () => {
const Page = PLATFORM_ROUTE_RUNTIME.EXAMPLES_PLATFORM.Component;
render(
<ApplicationProvider application={createTestApplication()}>
<LocaleProvider>
<Suspense fallback={<p>route chunk</p>}>
<Page />
</Suspense>
</LocaleProvider>
</ApplicationProvider>,
);
expect(
await screen.findByRole("heading", { level: 1, name: "플랫폼 구성" }),
).toBeVisible();
const routes = screen.getByRole("table", { name: "설치된 라우트 목록" });
expect(within(routes).getAllByRole("row").slice(1)).toHaveLength(
Object.keys(ROUTE_REGISTRY).length,
);
// Only the part read from the runtime halves waits.
const contracts = screen.getByRole("region", {
name: "계약과 HTTP 오퍼레이션",
});
expect(
within(contracts).getByLabelText("기능 실행부를 불러오고 있습니다."),
).toBeVisible();
expect(
screen.queryByRole("table", { name: "설치된 HTTP 오퍼레이션" }),
).toBeNull();
});
});
+44 -5
View File
@@ -1,8 +1,13 @@
import AxeBuilder from "@axe-core/playwright";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts";
import type { RouteDefinition } from "../../src/contracts/routes.ts";
import { KO_MESSAGES } from "../../src/presentation/i18n/catalog.ts";
import {
answerInstalledApiRequest,
type InstalledApiAnswer,
} from "./support/installed-api-answers.ts";
const WCAG_TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"];
const SIGN_IN_TITLE = KO_MESSAGES["route.auth.required.title"];
@@ -22,25 +27,59 @@ async function blockingViolations(page: Page) {
// Widened: without an installed feature every route is public, and the
// `session-required` branch must still typecheck (sample removal).
const ROUTES: readonly RouteDefinition[] = Object.values(ROUTE_REGISTRY);
// 1103/16-03. Every path parameter gets one value: a feature with its own
// parameter names needs no edit here.
const PATH_PARAMETER_VALUE = "a11y-1";
const API_ORIGIN = "http://localhost:8080";
for (const definition of ROUTES) {
const route =
definition.path === "*"
? "/not-found"
: definition.path.replace(":resourceId", "reference-1");
: definition.path.replace(/:[A-Za-z][A-Za-z0-9_]*/gu, PATH_PARAMETER_VALUE);
test(`@a11y ${route} has no critical or serious axe violations`, async ({
page,
}) => {
const heading = page.getByRole("heading", { level: 1 });
if (definition.access === "session-required") {
// Feature data is not this spec's subject: any API answers an empty list.
await page.route("http://localhost:8080/api/**", (request) =>
request.fulfill({ json: [] }),
);
// 1103/11-01. Feature data is not this spec's subject: a list read gets
// an empty list in the frame its descriptor declares, so the page is
// scanned in its empty state, not on a response-shape error.
const answers: InstalledApiAnswer[] = [];
await page.route(`${API_ORIGIN}/**`, (request) => {
const answer = answerInstalledApiRequest(
COMPOSED_CONTRACT_CONTRIBUTIONS,
request.request().method(),
new URL(request.request().url()).pathname,
);
answers.push(answer);
return answer.kind === "unanswerable"
? request.fulfill({ status: 501, body: answer.reason ?? answer.request })
: request.fulfill({ json: answer.body });
});
await page.goto(route);
await expect(heading).toHaveText(SIGN_IN_TITLE);
await page.getByRole("button", { name: "로그인 시작" }).click();
await expect(heading).toBeVisible();
await expect(heading).not.toHaveText(SIGN_IN_TITLE);
await expect(page.locator("[aria-busy='true']")).toHaveCount(0);
expect(
answers.filter((answer) => answer.kind === "unanswerable"),
"requests no installed list or single-resource read answers",
).toEqual([]);
const singleResourceReads = answers.flatMap((answer) =>
answer.kind === "single-resource" ? [answer.operationId] : [],
);
if (singleResourceReads.length === 0) {
// A shape the page does not read fails here, before axe passes it.
await expect(page.getByRole("alert")).toHaveCount(0);
} else {
// No generic body answers a read of one resource: a detail page is
// scanned in its failure state, and the report says which.
test.info().annotations.push({
type: "a11y-data-state",
description: `failure state: ${singleResourceReads.join(", ")} reads one resource`,
});
}
} else {
await page.goto(route);
const title = CATALOG[`route.${definition.routeId}.title`];
+79 -20
View File
@@ -1,7 +1,11 @@
import { appendFile, readFile } from "node:fs/promises";
import path from "node:path";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import type { RouteDefinition } from "../../src/contracts/routes.ts";
import {
ROUTE_REGISTRY,
ROUTE_RUNTIME_CONTRACT,
} from "../../src/features/installed-feature-contracts.ts";
import { expect, test } from "../support/browser/strict-browser-test.ts";
import {
prepareFixtureBuilds,
@@ -19,11 +23,60 @@ import { startBuildServer } from "./support/service-worker-builds.ts";
* recovery failure instead.
*/
const PLATFORM = ROUTE_REGISTRY.EXAMPLES_PLATFORM;
const UI = ROUTE_REGISTRY.EXAMPLES_UI;
const PLATFORM_PAGE = "src/presentation/examples/platform-overview-page.tsx";
const UI_PAGE = "src/presentation/examples/ui-gallery-page.tsx";
const PAGES = [PLATFORM_PAGE, UI_PAGE] as const;
// 1103/09-04. The platform overview is a platform route; the UI gallery is
// a feature route now, reached through its context gateway. Route ids only:
// the page sources are read from build A's Vite manifest, so this spec names
// no feature folder.
const installedRoutes: Readonly<Record<string, RouteDefinition>> = ROUTE_REGISTRY;
const runtimeContracts: Readonly<Record<string, { moduleId: string }>> =
ROUTE_RUNTIME_CONTRACT;
function installedRoute(routeId: string): RouteDefinition {
const definition = installedRoutes[routeId];
if (!definition) throw new Error(`${routeId} is not installed.`);
return definition;
}
const PLATFORM = installedRoute("EXAMPLES_PLATFORM");
const UI = installedRoute("EXAMPLES_UI");
type ViteManifest = Record<
string,
{
file: string;
name?: string;
isDynamicEntry?: boolean;
imports?: string[];
dynamicImports?: string[];
}
>;
async function viteManifest(dist: string): Promise<ViteManifest> {
return JSON.parse(
await readFile(path.join(dist, ".vite/manifest.json"), "utf8"),
) as ViteManifest;
}
/** The source of a route's page: the dynamic entry named by its module id. */
function pageSource(manifest: ViteManifest, route: RouteDefinition): string {
const moduleId = runtimeContracts[route.routeId]?.moduleId;
const sources = Object.entries(manifest)
.filter(([, entry]) => entry.isDynamicEntry && entry.name === moduleId)
.map(([source]) => source);
if (sources.length !== 1) {
throw new Error(`Expected one page chunk for ${route.routeId}: ${sources.join(", ")}`);
}
return sources[0]!;
}
/** The context routes module that lazy-loads `page`. */
function routesSource(manifest: ViteManifest, page: string): string {
const sources = Object.entries(manifest)
.filter(([, entry]) => entry.isDynamicEntry && entry.dynamicImports?.includes(page))
.map(([source]) => source);
if (sources.length !== 1) {
throw new Error(`Expected one routes module for ${page}: ${sources.join(", ")}`);
}
return sources[0]!;
}
let builds: FixtureBuilds<"a" | "b"> | undefined;
@@ -34,9 +87,10 @@ test.beforeAll(async () => {
{
name: "b",
edit: async (root) => {
for (const page of PAGES) {
const manifest = await viteManifest(path.join(root, "dist-a"));
for (const route of [PLATFORM, UI]) {
await appendFile(
path.join(root, page),
path.join(root, pageSource(manifest, route)),
'\n(globalThis as Record<string, unknown>).__caFixtureBuild = "b";\n',
);
}
@@ -56,11 +110,13 @@ async function routeChunk(dist: string, chunkId: string): Promise<string> {
return `/${manifest.routeChunks[chunkId]}`;
}
// Each missing page chunk fails its request and the dynamic import. Chromium
// may also log the 404 itself (without its URL), Firefox logs the error
// object React caught, and WebKit logs its own import error without the URL.
// Nothing else is allowed, but for the WebKit warning below.
const MISSING_PAGE = String.raw`/assets/(?:platform-overview|ui-gallery)-page-[\w-]+\.js`;
// Each missing chunk fails its request and the dynamic import. Chromium may
// also log the 404 itself (without its URL), Firefox logs the error object
// React caught, and WebKit logs its own import error without the URL. Nothing
// else is allowed, but for the WebKit warning below. 1103/09-04: the B tab
// misses the UI gallery's context routes module before its page: that module
// names B's new page chunk, so its hash changed too.
const MISSING_PAGE = String.raw`/assets/(?:platform-overview-page|ui-gallery-page|context-routes)-[\w-]+\.js`;
const MISSING_PAGE_FAILURES = [
String.raw`^requestfailed:GET:${MISSING_PAGE}:`,
String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`,
@@ -72,9 +128,7 @@ const MISSING_PAGE_FAILURES = [
/** The chunks Vite preloads with `page`: its static imports in `dist`. */
async function preloadedWith(dist: string, page: string): Promise<string[]> {
const manifest = JSON.parse(
await readFile(path.join(dist, ".vite/manifest.json"), "utf8"),
) as Record<string, { file: string; imports?: string[] }>;
const manifest = await viteManifest(dist);
if (!manifest[page]) throw new Error(`${page} is not in ${dist}'s manifest.`);
const files = new Set<string>();
const pending = [...(manifest[page].imports ?? [])];
@@ -89,10 +143,10 @@ async function preloadedWith(dist: string, page: string): Promise<string[]> {
// WebKit only. Three seconds after a document's load event, WebKit warns once
// for each link-preloaded resource the document has not used yet. Vite
// preloads a page chunk together with the chunks it imports, so a missing page
// preloads a chunk together with the chunks it imports, so a missing chunk
// leaves the chunks preloaded with it unused: in the A tab those of A's
// platform page (the tab is still on A while recovery reads the release
// manifest), in the B tab those of B's UI page. Whether that check runs before
// manifest), in the B tab those of B's context routes module for the UI page. Whether that check runs before
// the reload, or before the test ends, is timing, so the warnings come and go.
// They are the provoked failure's own effect; only those chunks are allowed.
test.use({
@@ -100,9 +154,14 @@ test.use({
const patterns = [...MISSING_PAGE_FAILURES];
if (browserName === "webkit") {
if (!builds) throw new Error("Fixture builds were not prepared.");
const aManifest = await viteManifest(builds.dist.a);
const bManifest = await viteManifest(builds.dist.b);
const files = [
...(await preloadedWith(builds.dist.a, PLATFORM_PAGE)),
...(await preloadedWith(builds.dist.b, UI_PAGE)),
...(await preloadedWith(builds.dist.a, pageSource(aManifest, PLATFORM))),
...(await preloadedWith(
builds.dist.b,
routesSource(bManifest, pageSource(bManifest, UI)),
)),
].map((file) => file.replaceAll(".", String.raw`\.`));
patterns.push(
String.raw`^console:warning:The resource http://127\.0\.0\.1:\d+/(?:${files.join("|")}) was preloaded using link preload but not used within a few seconds from the window's load event\. Please make sure it wasn't preloaded for nothing\.$`,
@@ -0,0 +1,63 @@
import type { ComposedContractContributions } from "../../../src/contracts/external-contract-runtime.ts";
import { successEnvelope } from "../../mocks/handlers/http-scenarios.ts";
/**
* 1103/11-01, 16-03. What `tests/e2e/accessibility.spec.ts` answers a
* protected page's API request with. Feature data is not that spec's subject,
* so a list read gets an empty list, framed the way the operation's own
* descriptor declares: inside the paired backend's Envelope for
* `responseEnvelope: "ENVELOPE_V1"`, bare otherwise. A global bare `[]` put
* every Envelope feature on the mismatch error screen and still passed.
*
* The request is matched to an installed GET by method and `pathTemplate`, so
* a new feature needs no edit here. A read with a path parameter whose payload
* is not a list (a detail page) cannot be answered with an empty list: the
* spec renders it in its failure state and says so. Any other request fails
* the spec instead of drawing an error screen that passes.
*/
export type InstalledApiAnswer =
| Readonly<{ kind: "empty-list"; operationId: string; body: unknown }>
| Readonly<{ kind: "single-resource"; operationId: string; body: unknown }>
| Readonly<{ kind: "unanswerable"; request: string; reason?: string }>;
const EMPTY_LIST: readonly never[] = Object.freeze([]);
function templatePattern(pathTemplate: string): RegExp {
const pattern = pathTemplate
.split(/\{[^}]+\}/u)
.map((part) => part.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"))
.join("[^/]+");
return new RegExp(`^${pattern}$`, "u");
}
export function answerInstalledApiRequest(
contracts: ComposedContractContributions,
method: string,
pathname: string,
): InstalledApiAnswer {
const request = `${method} ${pathname}`;
for (const { contract } of contracts.httpByOperationId.values()) {
if (contract.method !== method || contract.method !== "GET") continue;
if (!templatePattern(contract.pathTemplate).test(pathname)) continue;
const body =
contract.responseEnvelope === "ENVELOPE_V1"
? successEnvelope([])
: EMPTY_LIST;
if (contract.outputValidator.safeParse(EMPTY_LIST).success) {
return Object.freeze({ kind: "empty-list", operationId: contract.operationId, body });
}
if (contract.pathTemplate.includes("{")) {
return Object.freeze({
kind: "single-resource",
operationId: contract.operationId,
body,
});
}
return Object.freeze({
kind: "unanswerable",
request,
reason: `${contract.operationId} reads no single resource and rejects an empty list`,
});
}
return Object.freeze({ kind: "unanswerable", request });
}
@@ -0,0 +1,80 @@
// @vitest-environment jsdom
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { createAnonymousSessionAdapter } from "../../../src/adapters/auth/external-session-adapter.ts";
import StateGalleryPage from "../../../src/features/platform-examples-feature/presentation/state-gallery-page.tsx";
import { ApplicationProvider } from "../../../src/presentation/providers/application-provider.tsx";
import { PreferenceProviders } from "../../../src/presentation/providers/preference-providers.tsx";
import { AppRouter } from "../../../src/presentation/routes/app-router.tsx";
import { createTestApplication } from "../../helpers/create-test-application.ts";
/**
* The example screens (`/examples/ui`, `/examples/states`, `/examples/auth`)
* are the template's content, not the platform (0929/10-02). 1103/09-04:
* they are `platform-examples-feature`, and this folder goes with it; the
* platform tests run on the test-only feature's pages and keep passing.
*/
function renderApp(
url: string,
application = createTestApplication(),
) {
window.history.pushState({}, "", url);
return render(
<ApplicationProvider application={application}>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
);
}
describe("example pages", () => {
it("reaches the UI gallery from the home page's starter actions", async () => {
const user = userEvent.setup();
renderApp("/");
await user.click(
await screen.findByRole("link", { name: "UI 구성요소 보기" }),
);
await waitFor(() =>
expect(
screen.getByRole("heading", { name: "UI 구성요소", level: 1 }),
).toHaveFocus(),
);
});
it("returns to the current URL with its hash from the auth example page", async () => {
const user = userEvent.setup();
const beginSignIn = vi.fn(async () => {});
renderApp(
"/examples/auth#session",
createTestApplication({
session: { ...createAnonymousSessionAdapter(), beginSignIn },
}),
);
await user.click(
await screen.findByRole("button", { name: "로그인 시작" }),
);
expect(beginSignIn).toHaveBeenCalledWith("/examples/auth#session");
});
it("nests the state gallery's titles under the card and section around them (08-05)", () => {
render(<StateGalleryPage />);
expect(
screen.getByRole("heading", { name: "아직 표시할 항목이 없습니다.", level: 4 }),
).toBeVisible();
expect(screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent))
.toEqual(expect.arrayContaining(["빈 화면", "복구 가능한 오류"]));
// Access states sit directly under the section's h2.
expect(
screen.queryAllByRole("heading", { level: 2 }).map((h) => h.textContent),
).toEqual(["비동기 데이터 상태", "접근과 탐색 상태"]);
});
});
@@ -4,12 +4,12 @@ import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import UiGalleryPage from "../../src/presentation/examples/ui-gallery-page.tsx";
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
import UiGalleryPage from "../../../src/features/platform-examples-feature/presentation/ui-gallery-page.tsx";
import { LocaleProvider } from "../../../src/presentation/i18n/index.ts";
/**
* A starter screen (0929/10-02): `/examples/ui` is template content, so a
* product that replaces it deletes this file with it. The primitives have
* A starter screen (0929/10-02): `/examples/ui` is template content
* (`platform-examples-feature`, 1103/09-04), and this file goes with it. The primitives have
* their own suites; this one checks what the page wires them to — the
* validation rule, the shared notice line and the show/hide state.
*/
+2 -1
View File
@@ -169,7 +169,8 @@ const ENVELOPE_META = Object.freeze({
traceId: "0af7651916cd43dd8448eb211c80319c",
});
function successEnvelope(data: JsonBodyType) {
/** Also the accessibility e2e's answer (`tests/e2e/support/installed-api-answers.ts`). */
export function successEnvelope(data: JsonBodyType) {
return Object.freeze({
success: true,
...(data === null ? {} : { data }),
@@ -70,7 +70,9 @@ jobs:
corepack pnpm install --frozen-lockfile --ignore-scripts
- name: Install Playwright browsers
if: \${{ matrix.browser }}
run: corepack pnpm exec playwright install --with-deps chromium firefox webkit
run: |
corepack pnpm exec playwright install --with-deps chromium firefox webkit
$(command -v sudo || true) apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation
- name: Run blocking gate
run: corepack pnpm ci:gate -- \${{ matrix.gate }}
- name: Upload merge gate evidence
@@ -107,7 +109,9 @@ jobs:
corepack pnpm install --frozen-lockfile --ignore-scripts
- name: Install Playwright browsers
if: \${{ matrix.browser }}
run: corepack pnpm exec playwright install --with-deps chromium firefox webkit
run: |
corepack pnpm exec playwright install --with-deps chromium firefox webkit
$(command -v sudo || true) apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation
- name: Run blocking gate
run: corepack pnpm ci:gate -- \${{ matrix.gate }}
- name: Upload release gate evidence
+103
View File
@@ -0,0 +1,103 @@
import { describe, expect, it } from "vitest";
import { readSuccessEnvelope } from "../../src/adapters/http/backend-envelope.ts";
import { composeContractContributions } from "../../src/contracts/external-contract-runtime.ts";
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts";
import { answerInstalledApiRequest } from "../e2e/support/installed-api-answers.ts";
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
/**
* 1103/11-01, 16-03. The accessibility e2e answers a protected page's API
* requests from the installed descriptors: an empty list in the frame the
* operation declares. A global bare `[]` put every Envelope feature on the
* mismatch error screen and still passed.
*/
const [LIST, GET, CREATE] = TEST_CONTRACT_CONTRIBUTION.http;
function composed(responseEnvelope?: "ENVELOPE_V1") {
return composeContractContributions([
Object.freeze({
...TEST_CONTRACT_CONTRIBUTION,
http: Object.freeze(
[LIST!, GET!, CREATE!].map((installed) =>
responseEnvelope === undefined
? installed
: Object.freeze({
...installed,
contract: Object.freeze({ ...installed.contract, responseEnvelope }),
}),
),
),
}),
]);
}
describe("accessibility e2e API answers", () => {
it("answers a DTO list read with a bare empty list", () => {
expect(answerInstalledApiRequest(composed(), "GET", "/api/test-entities")).toEqual({
kind: "empty-list",
operationId: "TEST_LIST_ENTITIES",
body: [],
});
});
it("answers an Envelope list read with an empty list inside the Envelope", () => {
const answer = answerInstalledApiRequest(
composed("ENVELOPE_V1"),
"GET",
"/api/test-entities",
);
expect(answer.kind).toBe("empty-list");
if (answer.kind !== "empty-list") return;
// What the executor reads out of the frame is what the operation accepts.
expect(readSuccessEnvelope(answer.body)).toEqual({ ok: true, value: [] });
expect(LIST!.contract.outputValidator.safeParse([]).success).toBe(true);
});
it("names a single-resource read, which no empty list can answer", () => {
expect(
answerInstalledApiRequest(composed("ENVELOPE_V1"), "GET", "/api/test-entities/a11y-1"),
).toMatchObject({ kind: "single-resource", operationId: "TEST_GET_ENTITY" });
});
it("refuses a request no installed read declares", () => {
expect(
answerInstalledApiRequest(composed(), "POST", "/api/test-entities"),
).toEqual({ kind: "unanswerable", request: "POST /api/test-entities" });
expect(
answerInstalledApiRequest(composed(), "GET", "/api/elsewhere"),
).toEqual({ kind: "unanswerable", request: "GET /api/elsewhere" });
});
it("refuses a parameterless read whose payload is not a list", () => {
const pagedOnly = composeContractContributions([
Object.freeze({
...TEST_CONTRACT_CONTRIBUTION,
http: Object.freeze([
Object.freeze({
...GET!,
contract: Object.freeze({
...GET!.contract,
operationId: "TEST_PAGED_ENTITIES",
pathTemplate: "/api/paged-entities",
}),
}),
]),
}),
]);
expect(answerInstalledApiRequest(pagedOnly, "GET", "/api/paged-entities")).toEqual({
kind: "unanswerable",
request: "GET /api/paged-entities",
reason: "TEST_PAGED_ENTITIES reads no single resource and rejects an empty list",
});
});
it("can answer every parameterless read the installed features declare", () => {
for (const { contract } of COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.values()) {
if (contract.method !== "GET" || contract.pathTemplate.includes("{")) continue;
expect(
answerInstalledApiRequest(COMPOSED_CONTRACT_CONTRIBUTIONS, "GET", contract.pathTemplate),
).toMatchObject({ kind: "empty-list", operationId: contract.operationId });
}
});
});
+27
View File
@@ -28,6 +28,7 @@ import {
validateInstallScriptPolicy,
validatePackageScriptGraph,
} from "../../scripts/lib/package-script-graph.ts";
import { VISUAL_TEST_FONT_PACKAGES } from "../../scripts/lib/visual-test-fonts.ts";
const temporaryRoots: string[] = [];
const npmPostScriptForeignScopeCommands = [
@@ -1646,6 +1647,32 @@ describe("CI workflow generation", () => {
expect(actionUses.every((uses) => /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+@[0-9a-f]{40}$/u.test(uses!))).toBe(true);
});
// 1103/11-02. tests/visual/fonts.conf reads the goldens' faces from OS
// packages that Playwright's own dependencies do not include, so a clean
// runner failed FE-GATE-008 at `visual-fonts`. Every browser step installs
// them, after `--with-deps` has refreshed the package lists.
it("installs the visual-test font packages in every browser step", async () => {
const workflow = renderCiWorkflow(await loadCiGateContract(process.cwd()));
const browserSteps = workflow
.split(" - name: ")
.filter((step) => step.startsWith("Install Playwright browsers"));
expect(browserSteps).toHaveLength(2);
for (const step of browserSteps) {
const playwright = step.indexOf("playwright install --with-deps");
const fonts = step.indexOf(
`apt-get install -y ${VISUAL_TEST_FONT_PACKAGES.join(" ")}`,
);
expect(playwright).toBeGreaterThan(0);
expect(fonts).toBeGreaterThan(playwright);
}
expect(VISUAL_TEST_FONT_PACKAGES).toEqual([
"fonts-noto-core",
"fonts-noto-cjk",
"fonts-noto-cjk-extra",
"fonts-liberation",
]);
});
// 12-01: main is the integration branch; a push there must run the gates.
it("runs on pushes to main", async () => {
const workflow = renderCiWorkflow(await loadCiGateContract(process.cwd()));
+18 -3
View File
@@ -4,7 +4,8 @@ import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { createBrowserMutationIntentFactory } from "../../src/adapters/platform/browser-mutation-intent-factory.ts";
import { createApplication } from "../../src/application/create-application.ts";
import type { ApplicationFeatureId } from "../../src/application/ports/in/application-api.ts";
import { INSTALLED_PRODUCT_FEATURE_IDS } from "../../src/features/installed-product-manifest.ts";
import { loadFeatureRuntime } from "../../src/features/feature-module.ts";
import { INSTALLED_PRODUCT_FEATURE_MODULES } from "../../src/features/installed-product-manifest.ts";
import { testRuntimeConfig } from "../helpers/runtime-config.ts";
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
@@ -54,6 +55,20 @@ const release: Release = {
routeChunks: { "route-home": "assets/home.js" },
};
/**
* 1103/09-04. The installed features that contribute an application API. The
* template's example screens call none: loading them
* installs no input.
*/
const API_FEATURE_IDS: readonly string[] = (
await Promise.all(
INSTALLED_PRODUCT_FEATURE_MODULES.map(async (module) =>
(await loadFeatureRuntime(module)).adapters.length > 0 ? [module.id] : [],
),
)
).flat();
describe("runtime adapter composition", () => {
it("creates validated intent and idempotency identities with independent UUID calls", () => {
const randomUUID = vi
@@ -362,7 +377,7 @@ describe("runtime adapter composition", () => {
});
it("gives a feature switched off by FEATURE_OVERRIDES no application API (Q-6.9-5)", async () => {
const [disabledId, ...activeIds] = INSTALLED_PRODUCT_FEATURE_IDS;
const [disabledId, ...activeIds] = API_FEATURE_IDS;
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
@@ -402,7 +417,7 @@ describe("runtime adapter composition", () => {
adapters.featureLoaders,
);
for (const featureId of INSTALLED_PRODUCT_FEATURE_IDS) {
for (const featureId of API_FEATURE_IDS) {
// 15-01. Not loaded until the router asks for the feature's routes.
expect(() =>
application.features.get(featureId as ApplicationFeatureId),
Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 446 KiB

After

Width:  |  Height:  |  Size: 183 KiB

+3 -1
View File
@@ -3,6 +3,7 @@ import {
test,
type Page,
} from "../support/browser/strict-browser-test.ts";
import { VISUAL_TEST_FONT_INSTALL_ARGUMENTS } from "../../scripts/lib/visual-test-fonts.ts";
// 11-02. The goldens were captured with these four faces. `fonts.conf` shows
// Chromium only the directories that hold them; this check runs before the
@@ -18,7 +19,8 @@ const expectedFaces = {
const installHint = [
"Visual tests must draw with the fonts the goldens were captured with.",
"Debian/Ubuntu: sudo apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-cjk-extra fonts-liberation",
// 1103/11-02. The CI browser step installs the same list.
`Debian/Ubuntu: sudo ${VISUAL_TEST_FONT_INSTALL_ARGUMENTS}`,
"tests/visual/fonts.conf reads them from the Debian/Ubuntu font directories; other OSes have no Linux goldens.",
].join("\n");
+54
View File
@@ -3,6 +3,10 @@ import {
test,
type Page,
} from "../support/browser/strict-browser-test.ts";
import {
ROUTE_FEATURE_OWNER,
ROUTE_REGISTRY,
} from "../../src/features/installed-feature-contracts.ts";
// 11-02. `main` is drawn before the route chunk arrives; a screenshot taken
// then pins the loading surface instead of the page.
@@ -10,10 +14,50 @@ async function expectRouteHeading(page: Page, title: string) {
await expect(page.getByRole("heading", { level: 1 })).toHaveText(title);
}
/** `toHaveScreenshot` takes a stylesheet only as a file; a tag does the same. */
async function hide(page: Page, css: string) {
if (css !== "") await page.addStyleTag({ content: css });
}
/**
* 1103/12-01. These goldens are the template's own drawing: the shell, the
* home page and the platform overview. Those screens also draw whatever
* features are installed, so one `create:feature` failed this merge gate and
* only re-capturing template-owned PNGs made it pass. The screenshots leave
* the installed features' parts out (`display: none`, so a longer list does
* not move the rest): every link to a feature route, with its list item, and
* the overview sections that count or list the installed features. Their
* number and order are the component tests' subject; the shell's own CSS
* still fails here.
*/
const FEATURE_ROUTE_PATHS = Object.values(ROUTE_REGISTRY)
.filter((route) => ROUTE_FEATURE_OWNER[route.routeId] !== undefined)
.map((route) => route.path);
const WITHOUT_FEATURE_LINKS =
FEATURE_ROUTE_PATHS.length === 0
? ""
: `${FEATURE_ROUTE_PATHS.flatMap((path) => [
`li:has(> a[href="${path}"])`,
`a[href="${path}"]`,
]).join(",\n")} { display: none !important; }`;
const WITHOUT_INSTALLED_FEATURE_SECTIONS = `${[
"platform-summary-title",
"platform-routes-title",
"platform-contracts-title",
"platform-features-title",
]
.map((id) => `section[aria-labelledby="${id}"]`)
.join(",\n")} { display: none !important; }
section[aria-labelledby="platform-release-title"] .platform-metric:nth-child(4) dd {
/* The contract-set digest: a feature's contract package changes it. */
visibility: hidden !important;
}`;
test("wide application shell visual contract", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto("/");
await expectRouteHeading(page, "Clean Architecture Frontend");
await hide(page, WITHOUT_FEATURE_LINKS);
await expect(page).toHaveScreenshot("app-shell-wide-light.png", {
fullPage: true,
});
@@ -26,6 +70,7 @@ test("compact drawer and pseudo-locale visual contract", async ({ page }) => {
await page.locator("#locale-preference").selectOption("en-XA");
await page.locator(".app-shell__menu-button").click();
await expect(page.locator(".ui-drawer")).toHaveJSProperty("open", true);
await hide(page, WITHOUT_FEATURE_LINKS);
await expect(page).toHaveScreenshot("app-shell-compact-pseudo-drawer.png", {
fullPage: true,
});
@@ -59,6 +104,15 @@ test("platform composition overview visual contract", async ({ page }) => {
await expect(
page.locator("section[aria-labelledby='platform-capabilities-title']"),
).toBeVisible();
// 1103/15-01. The contract tables fill in after the title; wait for them so
// the hidden sections are drawn in their final state either way.
await expect(page.locator("main [aria-busy='true']")).toHaveCount(0);
await expect(
page
.locator("section[aria-labelledby='platform-release-title'] dt")
.filter({ hasText: "계약 집합 다이제스트" }),
).toBeVisible();
await hide(page, WITHOUT_INSTALLED_FEATURE_SECTIONS);
await expect(page.getByRole("main")).toHaveScreenshot(
"platform-overview-light.png",
);