Files
clean-architecture-frontend…/tests/architecture/context-route-roots.test.ts
T
DongHyeonka 12f3bb7862 refactor(contracts)!: V2 API 행을 지우고 FE-REG-API를 HTTP descriptor에서 뽑는다
문제
기능 하나가 같은 HTTP API를 두 번 적는다. *-api-contract.ts의 V2 행
(defineRestOperation)은 check:registries(FE-REG-API)가 검사하는 선언이고,
contract contribution의 V3 descriptor가 실제로 실행된다. 둘이 어긋나지 않게
http-operation-v2-v3-parity 테스트를 따로 둔다. 048f490으로 V2 클라이언트가
없어져 V2 행을 읽는 실행 코드는 없고, 검사만 남은 두 번째 사본이다. V2 행을
위한 기능별 runtimeSchemas·mappers 레지스트리와 V2 보안 프로필 해석
(resolveRestSecurityProfiles)도 같이 남아 있다. 사용자 지시: 최신 경로 하나만
남기고, 레지스트리 기준선 재승인을 승인했다.

고른 방법
- src/contracts/api-operations.ts를 projectApiOperationRows 하나로 바꿨다.
  조립된 contribution의 descriptor마다 operationId, featureId, method, path,
  authProfileId, retrySemantics, requestBody, responseBody, responseEnvelope,
  request/response/problemSchema(검증기 schemaId) 행을 만든다. FE-REG-API는
  같은 export(API_OPERATIONS)를 읽고, governance 정의를 이 필드로 바꿨다.
  requestSchema·responseSchema는 그대로 FE-REG-SCHEMA를 참조한다.
- FeatureRuntime은 apiContract 대신 schemas(FE-REG-SCHEMA 행)만 받는다.
  installed-feature-runtime-registries는 schemas로 스키마 레지스트리를 만들고
  FE-REG-API 행을 descriptor에서 뽑는다. RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
  REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID를 지웠다.
- realtime snapshot 바인딩은 ApiOperationRow를 받고 method GET과
  retrySemantics SAFE·IDEMPOTENT를 본다(V2의 contractVersion·semantics·
  replayPolicy 대신).
- rest-profiles.ts에서 V2 행용 provider·CSRF 프로필 해석을 지웠다. V3는 조립
  때 auth profile을 검사하고 자격증명 헤더를 프로필로 거른다.
- 참조 기능: reference-api-contract.ts를 reference-schema-metadata.ts로
  바꾸고(스키마 행만), V2 runtime codec·operation mapper·레지스트리 mapper를
  지웠다. V3 descriptor가 쓰지 않는 NoRequest 스키마 행도 지웠다.
- create:feature: <base>-api-contract.ts 대신 <base>-schema-metadata.ts를
  만든다. codec·mapper 레지스트리 행과 그 테스트를 만들지 않는다.
- 레지스트리 기준선을 update:registry-baseline으로 다시 만들고 승인했다
  (digest 16f72742…, 승인자 DongHyeonka, 이유에 사용자 승인을 적음).
- 매뉴얼 01·02·reference, starter-experience, 계약 문서의 V2 설명을 지웠다.

버린 대안
- V2 행을 남기고 V3에서 생성하기: 생성 단계와 생성물이 하나 더 생긴다. 행은
  실행되지 않으므로 메모리에서 뽑아 검사하면 충분하다.
- 스키마 메타데이터(FE-REG-SCHEMA 행)도 검증기에서 뽑기: boundary·
  unknownFieldPolicy·owner는 검증기에 없고, 라우트 스키마도 같은 레지스트리를
  쓴다. 이 행은 V2가 아니라 스키마 레지스트리라 남겼다.

위험·한계
- BREAKING: FeatureRuntime 모양, contracts·rest-profiles·loaded-feature-runtimes
  의 이름이 바뀌거나 없어졌다. memento-frontend의 memento-web이 V2 행을 쓴다.
  옮기는 법은 CHANGELOG에 적는다.
- V2 보안 프로필 일관성 검사(auth "none"과 ANONYMOUS, 쿠키 프로필의 CSRF
  모드)가 사라졌다. V3 descriptor에는 그 칸이 없다.
- BoundedPollOperationContract(realtime polling recipe)는 contractVersion: 2
  필드를 갖지만 자체 계약이라 바꾸지 않았다.

검증
- check:types, lint, check:architecture, check:registries(11 registries PASS,
  compatibility=none), check:ci, check:diagnostics, check:adapter-inventory,
  verify:documentation 통과.
- test:unit 2,566(새 tests/unit/api-operation-rows.test.ts 3건 포함),
  test:integration 114, test:component 245, test:contract 23,
  test:runtime-schema 56, tests/features 99 통과.
- tests/unit/second-api-feature-registries.test.ts: V3 descriptor만 가진 두
  번째 기능을 복사본에 넣으면 기준선을 고치지 않고 check:registries가 통과한다.
- check:bundle 통과. 초기 JS 201,598 → 200,911 B.
- test:feature-scaffold 16개, test:sample-removal 23개 검사 통과.

BREAKING CHANGE: FeatureRuntime이 apiContract 대신 schemas를 받는다.
defineRestOperation, ApiOperation, RestOperationV2, composeApiOperations,
validateApiRuntimeBindings, getApiOperation, contracts의 API_OPERATIONS,
createRestProviderProfile, RestProviderProfile, resolveRestSecurityProfiles,
validateRestProfileBindings, REST_CSRF_PROFILES, RestCsrfProfile,
loaded-feature-runtimes의 RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID가 없어졌다. 기능은
operation을 contract contribution에만 적고, schemas 행을 feature-runtime에
넘긴다.
2026-11-03 21:37:48 +09:00

275 lines
9.2 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
import { withoutTakenOverPlatformRoutes } from "../../src/contracts/routes.ts";
import { defineFeatureModule } from "../../src/features/feature-module.ts";
/**
* 09-06. The router mounts one gateway per context at its route root and
* renders a feature route only inside it, while the registry and navigation
* list every feature route. A route its owning root does not reach is a menu
* link to NOT_FOUND, so composing the app has to refuse it.
*/
function feature(id: string, paths: Readonly<Record<string, string>>) {
const routes = Object.fromEntries(
Object.entries(paths).map(([routeId, path]) => [routeId, { routeId, path }]),
);
return defineFeatureModule({
id,
contracts: { featureId: id, routes },
routes,
messages: {},
loadRuntime: async () => ({
featureId: id,
schemas: {},
adapters: [],
contractContributions: [],
}),
});
}
function context(
id: string,
path: string,
features: readonly ReturnType<typeof feature>[],
loadLayout?: () => Promise<() => null>,
) {
return defineBoundedContextModule({
id,
features,
budget: { maxFeatures: 10 },
route: { path, loadRoutes: async () => [], ...(loadLayout ? { loadLayout } : {}) },
});
}
function app(...contexts: readonly ReturnType<typeof context>[]) {
return defineDeployableAppModule({
id: "shop-app",
contexts,
budget: { maxContexts: 10 },
});
}
describe("feature routes and their context route root", () => {
it("accepts routes at and under the owning context root", () => {
expect(() =>
app(
context("shop-context", "shop/*", [
feature("shop-feature", {
SHOP_ITEMS: "/shop",
SHOP_ITEM: "/shop/items/:itemId",
SHOP_NEW: "/shop/items/new",
}),
]),
),
).not.toThrow();
});
it("rejects a route outside the owning root, naming the feature, route and root", () => {
// E2: the menu would list /catalog and the URL would render NOT_FOUND.
expect(() =>
app(
context("shop-context", "shop/*", [
feature("shop-feature", {
SHOP_ITEMS: "/shop/items",
SHOP_CATALOG: "/catalog",
}),
]),
),
).toThrow(/SHOP_CATALOG.*\/catalog.*shop-feature.*shop-context.*shop\/\*/);
});
it("rejects a feature route at the platform home", () => {
expect(() =>
app(
context("shop-context", "shop/*", [
feature("shop-feature", { SHOP_HOME: "/" }),
]),
),
).toThrow(/SHOP_HOME/);
});
it("accepts the platform home a feature replaces whatever its root (09-03)", () => {
// The router mounts a replaced platform route at its own path.
expect(() =>
app(
context("home-context", "home/*", [
feature("home-feature", { APP_HOME: "/", HOME_FEED: "/home/feed" }),
]),
),
).not.toThrow();
});
it("rejects a route whose feature belongs to a context without a route root", () => {
expect(() =>
app(
defineBoundedContextModule({
id: "silent-context",
features: [feature("silent-feature", { SILENT: "/silent" })],
budget: { maxFeatures: 10 },
}),
),
).toThrow(/SILENT.*silent-feature.*silent-context/);
});
it("rejects a second context on the same root, which the router never reaches", () => {
// E5: the first context's gateway takes every URL under shop/*.
expect(() =>
app(
context("shop-a", "shop/*", [feature("feature-a", { A: "/shop/a" })]),
context("shop-b", "shop/*", [feature("feature-b", { B: "/shop/b" })]),
),
).toThrow(/B.*\/shop\/b.*feature-b.*shop-b.*shop-a/);
});
it("accepts nested roots when each route resolves to its own context", () => {
expect(() =>
app(
context("items", "fixture/items/*", [
feature("list", { LIST: "/fixture/items" }),
]),
context("status", "fixture/items/status/*", [
feature("status", { STATUS: "/fixture/items/status" }),
]),
),
).not.toThrow();
});
it("rejects a route a nested root of another context takes over", () => {
expect(() =>
app(
context("items", "fixture/items/*", [
feature("list", { DETAIL: "/fixture/items/status/detail" }),
]),
context("status", "fixture/items/status/*", [
feature("status", { STATUS: "/fixture/items/status" }),
]),
),
).toThrow(/DETAIL.*list.*items.*status/);
});
});
/**
* 09-03. Several context roots may sit under one layout, and layouts are
* siblings of AppShell at `/`: a root still takes the URLs under it whatever
* layout either context has, so the rule above spans every layout.
*/
describe("context route roots under layouts", () => {
const siteLayout = async () => () => null;
const studioLayout = async () => () => null;
it("accepts several roots under one layout and nested roots across layouts", () => {
expect(() =>
app(
context("site", "*", [feature("site", { APP_HOME: "/", EXPLORE: "/explore" })], siteLayout),
context("topics", "topics/*", [feature("topics", { TOPICS: "/topics" })], siteLayout),
context("studio", "studio/*", [feature("studio", { STUDIO: "/studio" })], studioLayout),
context("shop", "shop/*", [feature("shop", { SHOP: "/shop" })]),
),
).not.toThrow();
});
it("rejects a route another layout's root takes over", () => {
expect(() =>
app(
context("site", "*", [feature("site", { DRAFTS: "/studio/drafts" })], siteLayout),
context("studio", "studio/*", [feature("studio", { STUDIO: "/studio" })], studioLayout),
),
).toThrow(/DRAFTS.*site.*studio \(studio\/\*\)/);
});
});
/** 09-03. The platform names the routes a feature may take over; one feature may. */
describe("replaceable platform routes", () => {
const contract = (featureId: string, ...routeIds: string[]) => ({
featureId,
routes: Object.fromEntries(routeIds.map((routeId) => [routeId, {}])),
});
const platform = { APP_HOME: "platform home", NOT_FOUND: "platform not found" };
it("drops the platform routes a feature took over and keeps the rest", () => {
expect(
withoutTakenOverPlatformRoutes(platform, [contract("site", "APP_HOME", "EXPLORE")]),
).toEqual({ NOT_FOUND: "platform not found" });
expect(withoutTakenOverPlatformRoutes(platform, [contract("shop", "SHOP")])).toEqual(platform);
});
it("keeps a platform route the platform does not let features take over", () => {
// The registry composition then refuses the duplicate id as before.
expect(
withoutTakenOverPlatformRoutes(platform, [contract("shop", "NOT_FOUND")]),
).toEqual(platform);
});
it("rejects a second feature taking over the same platform route, naming both", () => {
expect(() =>
withoutTakenOverPlatformRoutes(platform, [
contract("site", "APP_HOME"),
contract("blog", "APP_HOME"),
]),
).toThrow(/APP_HOME.*site.*blog/);
});
});
/**
* 09-06 (3). The gateway renders the registered route a loaded route's handle
* names. A handle no feature of the context declares in its contract fails
* when the context's routes load, not later when that URL renders.
*/
describe("context route handles and their features' contract routes", () => {
function contextLoading(
features: readonly ReturnType<typeof feature>[],
handles: readonly unknown[],
) {
const loadRoutes = vi.fn(async () =>
handles.map((handle, index) => ({
id: `route-${index}`,
path: `/shop/${index}`,
handle,
})),
);
const module = defineBoundedContextModule({
id: "shop-context",
features,
budget: { maxFeatures: 10 },
route: { path: "shop/*", loadRoutes },
});
return { module, loadRoutes };
}
it("loads routes whose handles name the context's contract routes", async () => {
const { module } = contextLoading(
[
feature("shop-feature", { SHOP_ITEMS: "/shop/items" }),
feature("cart-feature", { CART: "/shop/cart" }),
],
[{ routeId: "SHOP_ITEMS" }, { routeId: "CART" }],
);
await expect(module.route?.loadRoutes()).resolves.toHaveLength(2);
});
it("rejects an unregistered handle at load, naming the feature and route ids", async () => {
// E7: a typo in context-routes.ts used to surface only as a context
// boundary failure when that URL rendered.
const { module, loadRoutes } = contextLoading(
[feature("shop-feature", { SHOP_ITEMS: "/shop/items" })],
[{ routeId: "SHOP_ITEMS" }, { routeId: "SHOP_ITEMSS" }],
);
// Defining the context still does not load its routes.
expect(loadRoutes).not.toHaveBeenCalled();
await expect(module.route?.loadRoutes()).rejects.toThrow(
/SHOP_ITEMSS.*shop-context.*shop-feature/,
);
});
it("rejects a handle without a route id", async () => {
const { module } = contextLoading(
[feature("shop-feature", { SHOP_ITEMS: "/shop/items" })],
[{ runtime: {} }],
);
await expect(module.route?.loadRoutes()).rejects.toThrow(/shop-feature/);
});
});