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에
넘긴다.
This commit is contained in:
DongHyeonka
2026-11-03 21:37:48 +09:00
parent 048f490ada
commit 12f3bb7862
44 changed files with 560 additions and 1702 deletions
+46 -215
View File
@@ -1,226 +1,57 @@
export type ApiOperation = Readonly<{
method: string;
path: string;
import type {
HttpMethod,
InstalledContractContribution,
InstalledHttpContract,
ResponseEnvelope,
RetrySemantics,
} from "./external-contract-runtime.ts";
/**
* FE-REG-API. The governed row of one installed HTTP operation, projected
* from its V3 descriptor (`InstalledHttpContract`). A feature writes the
* operation once, in its contract contribution; `check:registries` compares
* these rows with the approved baseline.
*/
export type ApiOperationRow = Readonly<{
operationId: string;
auth: "none" | "external-session";
timeoutMs: number | null;
idempotency: "safe" | "keyed" | "none";
retry: "runtime" | "never";
requestSource: "search" | "body" | "none";
featureId: string;
method: HttpMethod;
path: string;
authProfileId: string;
retrySemantics: RetrySemantics;
requestBody: InstalledHttpContract<unknown, unknown, unknown>["contract"]["requestBody"];
responseBody: InstalledHttpContract<unknown, unknown, unknown>["contract"]["responseBody"];
responseEnvelope: ResponseEnvelope;
requestSchema: string;
responseSchema: string;
owner: string;
contractVersion?: 2;
protocol?: "REST";
semantics?: "QUERY" | "COMMAND";
replayPolicy?: "SAFE" | "IDEMPOTENT" | "KEYED_COMMAND" | "NON_REPLAYABLE";
idempotencyKeyPolicy?: "NONE" | "REQUIRED";
mapperId?: string;
successStatuses?: readonly number[];
responseMediaTypes?: readonly string[];
maxResponseBytes?: number;
providerId?: string;
authProfileId?: string;
csrfProfileId?: string;
pathSchema?: string;
pathParameterNames?: readonly string[];
maxEncodedSearchBytes?: number;
problemSchema: string;
}>;
/**
* 07-02. A V2 row is the declaration `check:registries` (FE-REG-API) governs;
* it is not what executes. The executed copy of the same HTTP API is the V3
* descriptor (`InstalledHttpContract`) in the feature's contract contribution.
* A feature writes both, and `tests/unit/http-operation-v2-v3-parity.test.ts`
* checks they name the same operations, method, path, statuses, limits, auth
* profile, replay and write semantics, request body and schema ids. The
* deadline is not compared: V2 `timeoutMs` is `null` while V3 always has one.
* Pass composed contributions (`composeContractContributions`): composition
* already refused duplicate operation ids and snapshotted every row.
*/
export type RestOperationV2 = ApiOperation &
Readonly<{
contractVersion: 2;
protocol: "REST";
semantics: "QUERY" | "COMMAND";
replayPolicy:
| "SAFE"
| "IDEMPOTENT"
| "KEYED_COMMAND"
| "NON_REPLAYABLE";
idempotencyKeyPolicy: "NONE" | "REQUIRED";
mapperId: string;
successStatuses: readonly number[];
responseMediaTypes: readonly string[];
maxResponseBytes: number;
providerId: string;
authProfileId: string;
csrfProfileId: string;
pathSchema: string;
pathParameterNames: readonly string[];
maxEncodedSearchBytes: number;
}>;
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
const OPERATION_ID = /^[A-Z][A-Z0-9_]{2,79}$/;
const MEDIA_TYPE = /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/;
export function defineRestOperation(
operation: RestOperationV2,
): RestOperationV2 {
validateRestOperation(operation);
return Object.freeze({
...operation,
successStatuses: Object.freeze([...operation.successStatuses]),
responseMediaTypes: Object.freeze([...operation.responseMediaTypes]),
pathParameterNames: Object.freeze([...operation.pathParameterNames]),
});
}
export function composeApiOperations(
contributions: readonly Readonly<Record<string, ApiOperation>>[],
): Readonly<Record<string, ApiOperation>> {
const result: Record<string, ApiOperation> = Object.create(null);
export function projectApiOperationRows(
contributions: readonly InstalledContractContribution[],
): Readonly<Record<string, ApiOperationRow>> {
const rows: Record<string, ApiOperationRow> = {};
for (const contribution of contributions) {
for (const [registryId, operation] of Object.entries(contribution)) {
if (registryId !== operation.operationId) {
throw new TypeError("API operation registry key does not match operationId.");
}
if (Object.hasOwn(result, registryId)) {
throw new TypeError(`Duplicate API operation: ${registryId}`);
}
if (operation.contractVersion === 2) {
validateRestOperation(operation as RestOperationV2);
}
result[registryId] = operation;
for (const { contract, frontend } of contribution.http) {
rows[contract.operationId] = Object.freeze({
operationId: contract.operationId,
featureId: contribution.featureId,
method: contract.method,
path: contract.pathTemplate,
authProfileId: frontend.authProfileId,
retrySemantics: contract.retrySemantics,
requestBody: contract.requestBody,
responseBody: contract.responseBody,
responseEnvelope: contract.responseEnvelope ?? "NONE",
requestSchema: contract.inputValidator.schemaId,
responseSchema: contract.outputValidator.schemaId,
problemSchema: contract.problemValidator.schemaId,
});
}
}
return Object.freeze(result);
}
export function validateApiRuntimeBindings(
operations: Readonly<Record<string, ApiOperation>>,
schemaMetadata: Readonly<Record<string, Readonly<{ schemaId: string }>>>,
schemaCodecs: Readonly<Record<string, Readonly<{ schemaId: string }>>>,
mappers: Readonly<
Record<
string,
Readonly<{ mapperId: string; inputSchemaId: string; maxOutputItems: number }>
>
>,
): true {
for (const operation of Object.values(operations)) {
if (operation.contractVersion !== 2) continue;
for (const schemaId of [
operation.pathSchema,
operation.requestSchema,
operation.responseSchema,
]) {
if (
!schemaId ||
schemaMetadata[schemaId]?.schemaId !== schemaId ||
schemaCodecs[schemaId]?.schemaId !== schemaId
) {
throw new TypeError(
`Unresolved API schema binding: ${operation.operationId}`,
);
}
}
const mapper = mappers[operation.mapperId ?? ""];
if (
!mapper ||
mapper.mapperId !== operation.mapperId ||
mapper.inputSchemaId !== operation.responseSchema ||
mapper.maxOutputItems < 1
) {
throw new TypeError(
`Unresolved API mapper binding: ${operation.operationId}`,
);
}
}
return true;
}
function validateRestOperation(operation: RestOperationV2): void {
if (
operation.protocol !== "REST" ||
!OPERATION_ID.test(operation.operationId) ||
!operation.owner ||
!operation.mapperId ||
!operation.providerId ||
!operation.authProfileId ||
!operation.csrfProfileId ||
!operation.pathSchema ||
!operation.path.startsWith("/") ||
operation.path.startsWith("//") ||
operation.path.includes("?") ||
operation.path.includes("#") ||
!Number.isSafeInteger(operation.maxResponseBytes) ||
operation.maxResponseBytes < 1 ||
operation.maxResponseBytes > MAX_RESPONSE_BYTES ||
!Number.isSafeInteger(operation.maxEncodedSearchBytes) ||
operation.maxEncodedSearchBytes < 0 ||
operation.maxEncodedSearchBytes > 32_768 ||
operation.successStatuses.length === 0 ||
operation.successStatuses.some(
(status) => !Number.isInteger(status) || status < 200 || status > 299,
) ||
new Set(operation.successStatuses).size !== operation.successStatuses.length ||
operation.responseMediaTypes.length === 0 ||
operation.responseMediaTypes.some(
(value) => !MEDIA_TYPE.test(value) || value !== value.toLowerCase(),
)
) {
throw new TypeError(`Invalid REST operation contract: ${operation.operationId}`);
}
const placeholders = [
...operation.path.matchAll(
/:([A-Za-z][A-Za-z0-9_]*)|\{([A-Za-z][A-Za-z0-9_]*)\}/g,
),
]
.map((match) => match[1] ?? match[2] ?? "")
.sort();
const codecKeys = [...operation.pathParameterNames].sort();
if (
new Set(codecKeys).size !== codecKeys.length ||
placeholders.length !== codecKeys.length ||
placeholders.some((name, index) => name !== codecKeys[index])
) {
throw new TypeError(
`REST path codec does not match its template: ${operation.operationId}`,
);
}
const isQuery = operation.semantics === "QUERY";
// R-7.4. CSRF need is decided from the method (rest-profiles), so a COMMAND
// must use an unsafe method. Same binding as browser-rpc and the V3 runtime.
if (
!["QUERY", "COMMAND"].includes(operation.semantics) ||
!["SAFE", "IDEMPOTENT", "KEYED_COMMAND", "NON_REPLAYABLE"].includes(
operation.replayPolicy,
) ||
(!isQuery && !["POST", "PUT", "PATCH", "DELETE"].includes(operation.method)) ||
(isQuery && !["GET", "HEAD"].includes(operation.method)) ||
(isQuery && !["SAFE", "IDEMPOTENT"].includes(operation.replayPolicy)) ||
(operation.replayPolicy === "KEYED_COMMAND" &&
(operation.idempotencyKeyPolicy !== "REQUIRED" ||
operation.idempotency !== "keyed")) ||
(operation.replayPolicy === "NON_REPLAYABLE" &&
(operation.retry !== "never" || operation.idempotency !== "none"))
) {
throw new TypeError(`Incoherent REST replay contract: ${operation.operationId}`);
}
}
export const API_OPERATIONS: Readonly<Record<string, ApiOperation>> =
Object.freeze({});
export function getApiOperation(
operationId: string,
operations: Readonly<Record<string, ApiOperation>> = API_OPERATIONS,
): ApiOperation {
const selected = Object.hasOwn(operations, operationId)
? operations[operationId]
: undefined;
if (!selected) {
throw new Error(`Unregistered API operation: ${operationId}`);
}
return selected;
return Object.freeze(rows);
}
+5 -7
View File
@@ -1,4 +1,4 @@
import type { ApiOperation } from "./api-operations.ts";
import type { ApiOperationRow } from "./api-operations.ts";
import type { InstalledBoundaryMapper } from "./boundary-mapper.ts";
import type { RuntimeSchemaCodec } from "./schema-registry.ts";
import {
@@ -105,7 +105,7 @@ export type RealtimeEventTypeRegistration = Readonly<{
export type RealtimePolicyRegistryBindings = Readonly<{
schemaCodecs: Readonly<Record<string, RuntimeSchemaCodec>>;
mappers: Readonly<Record<string, InstalledBoundaryMapper>>;
apiOperations: Readonly<Record<string, ApiOperation>>;
apiOperations: Readonly<Record<string, ApiOperationRow>>;
endpointIds: readonly RealtimeEndpointId[];
effectProfileIds: readonly ExternalEventEffectProfileId[];
killSwitchIds: readonly KillSwitchId[];
@@ -467,11 +467,9 @@ function validSnapshotBindings(
OWNED_ID.test(input.checkpointCodecId) &&
bindings.schemaCodecs[input.checkpointCodecId]?.schemaId ===
input.checkpointCodecId &&
operation?.contractVersion === 2 &&
operation.protocol === "REST" &&
operation.semantics === "QUERY" &&
(operation.replayPolicy === "SAFE" ||
operation.replayPolicy === "IDEMPOTENT")
operation?.method === "GET" &&
(operation.retrySemantics === "SAFE" ||
operation.retrySemantics === "IDEMPOTENT")
);
}
+1 -182
View File
@@ -3,19 +3,10 @@ import {
type ReadOnlyRegistry,
} from "./read-only-registry.ts";
import { snapshotExactArray, snapshotExactObject } from "./exact-snapshot.ts";
import { isLoopbackHostname } from "./deployment-admission.ts";
import { PRODUCT_REST_AUTH_PROFILES } from "./product-contracts.ts";
export type FetchCredentialsMode = "omit" | "same-origin" | "include";
export type RestProviderProfile = Readonly<{
providerId: string;
baseUrl: string;
allowedCredentialsModes: readonly FetchCredentialsMode[];
redirect: "error";
referrerPolicy: "no-referrer";
}>;
/**
* VD-23. The complete closed set of headers a credential owner may contribute.
* Transport-owned headers (`accept`, `content-type`, `idempotency-key`) and
@@ -57,12 +48,6 @@ export type InstalledRestAuthProfiles = ReadOnlyRegistry<
RestAuthProfile
>;
export type RestCsrfProfile = Readonly<{
csrfProfileId: string;
mode: "NONE" | "HEADER";
headerName: "x-csrf-token" | null;
}>;
const EXTERNAL_BEARER = Object.freeze({
authProfileId: "EXTERNAL_BEARER",
transport: "BEARER_HEADER",
@@ -213,35 +198,7 @@ export function installRestAuthProfileRegistry(
if (installed.size === 0) {
throw new TypeError("REST auth profile registry cannot be empty.");
}
const registry = createReadOnlyRegistry(installed);
INSTALLED_REGISTRIES.add(registry);
return registry;
}
/** Registries this module installed, as opposed to look-alike objects. */
const INSTALLED_REGISTRIES = new WeakSet<object>();
/**
* REST auth profiles as accepted by resolve: the installed registry, or a raw
* record that is installed (validated) before any lookup.
*/
export type RestAuthProfileSource =
| InstalledRestAuthProfiles
| Readonly<Record<string, RestAuthProfile>>;
/**
* Q-6.7-9. Composition, the V3 executor and V2 resolve answer from one
* validated registry. A raw record never reaches a lookup unvalidated, so a
* profile installation would refuse cannot be resolved either.
*/
function installedAuthProfiles(
profiles: RestAuthProfileSource,
): InstalledRestAuthProfiles {
return INSTALLED_REGISTRIES.has(profiles)
? (profiles as InstalledRestAuthProfiles)
: installRestAuthProfileRegistry(
profiles as Readonly<Record<string, RestAuthProfile>>,
);
return createReadOnlyRegistry(installed);
}
function withProductProfiles(): Readonly<Record<string, RestAuthProfile>> {
@@ -263,141 +220,3 @@ function withProductProfiles(): Readonly<Record<string, RestAuthProfile>> {
*/
export const INSTALLED_REST_AUTH_PROFILES: InstalledRestAuthProfiles =
installRestAuthProfileRegistry(withProductProfiles());
export const REST_CSRF_PROFILES = Object.freeze({
NO_CSRF_BEARER: Object.freeze({
csrfProfileId: "NO_CSRF_BEARER",
mode: "NONE",
headerName: null,
}),
} satisfies Readonly<Record<string, RestCsrfProfile>>);
export function createRestProviderProfile(
providerId: string,
baseUrl: string,
allowedCredentialsModes: readonly FetchCredentialsMode[] = ["omit"],
): RestProviderProfile {
const parsed = new URL(baseUrl);
const localHttp =
parsed.protocol === "http:" &&
isLoopbackHostname(parsed.hostname);
if (
!providerId ||
(parsed.protocol !== "https:" && !localHttp) ||
parsed.username ||
parsed.password ||
parsed.search ||
parsed.hash ||
allowedCredentialsModes.length === 0 ||
new Set(allowedCredentialsModes).size !== allowedCredentialsModes.length
) {
throw new TypeError("Invalid REST provider profile.");
}
return Object.freeze({
providerId,
baseUrl: parsed.href,
allowedCredentialsModes: Object.freeze([...allowedCredentialsModes]),
redirect: "error",
referrerPolicy: "no-referrer",
});
}
export function resolveRestSecurityProfiles(
operation: Readonly<{
operationId?: string;
method: string;
auth: "none" | "external-session";
authProfileId?: string;
csrfProfileId?: string;
}>,
provider: RestProviderProfile,
authProfiles: RestAuthProfileSource = INSTALLED_REST_AUTH_PROFILES,
csrfProfiles: Readonly<Record<string, RestCsrfProfile>> = REST_CSRF_PROFILES,
): Readonly<{ auth: RestAuthProfile; csrf: RestCsrfProfile }> {
const authProfileId = operation.authProfileId ?? "";
const auth = installedAuthProfiles(authProfiles).get(authProfileId);
const csrfProfileId = operation.csrfProfileId ?? "";
const csrf = Object.hasOwn(csrfProfiles, csrfProfileId)
? csrfProfiles[csrfProfileId]
: undefined;
const unsafe = !["GET", "HEAD", "OPTIONS"].includes(operation.method);
// 16-03. Every broken condition is named, with the operation and profile
// ids, so a renamed or missing profile does not have to be found by
// comparing each rule by hand.
const broken = [
!auth && `unknown authProfileId ${authProfileId || "(none)"}`,
!csrf && `unknown csrfProfileId ${csrfProfileId || "(none)"}`,
auth &&
!provider.allowedCredentialsModes.includes(auth.credentials) &&
`provider ${provider.providerId} does not allow credentials "${auth.credentials}" of ${authProfileId}`,
auth &&
operation.auth === "none" &&
auth.transport !== "ANONYMOUS" &&
`auth "none" needs an ANONYMOUS profile, ${authProfileId} is ${auth.transport}`,
auth &&
operation.auth === "external-session" &&
auth.transport === "ANONYMOUS" &&
`auth "external-session" cannot use the ANONYMOUS profile ${authProfileId}`,
auth?.transport === "BEARER_HEADER" &&
csrf &&
csrf.mode !== "NONE" &&
`bearer profile ${authProfileId} cannot use CSRF mode ${csrf.mode} of ${csrfProfileId}`,
unsafe &&
auth?.transport === "SAME_ORIGIN_COOKIE" &&
csrf &&
csrf.mode !== "HEADER" &&
`${operation.method} with cookie profile ${authProfileId} needs a HEADER CSRF profile, ${csrfProfileId} is ${csrf.mode}`,
].filter((condition): condition is string => typeof condition === "string");
if (!auth || !csrf || broken.length > 0) {
throw new TypeError(
`REST security profiles are incoherent for ${operation.operationId ?? "an operation"}: ${broken.join("; ")}.`,
);
}
return Object.freeze({ auth, csrf });
}
export function validateRestProfileBindings(
operations: Readonly<
Record<
string,
Readonly<{
contractVersion?: number;
operationId: string;
method: string;
auth: "none" | "external-session";
providerId?: string;
authProfileId?: string;
csrfProfileId?: string;
}>
>
>,
providerCredentialModes: Readonly<
Record<string, readonly FetchCredentialsMode[]>
>,
authProfiles: RestAuthProfileSource = INSTALLED_REST_AUTH_PROFILES,
csrfProfiles: Readonly<Record<string, RestCsrfProfile>> = REST_CSRF_PROFILES,
): true {
const installed = installedAuthProfiles(authProfiles);
for (const operation of Object.values(operations)) {
if (operation.contractVersion !== 2) continue;
const allowed = providerCredentialModes[operation.providerId ?? ""];
if (!allowed) {
throw new TypeError(
`Unregistered REST provider binding: ${operation.operationId}`,
);
}
resolveRestSecurityProfiles(
operation,
Object.freeze({
providerId: operation.providerId ?? "",
baseUrl: "https://contract.invalid/",
allowedCredentialsModes: allowed,
redirect: "error",
referrerPolicy: "no-referrer",
}),
installed,
csrfProfiles,
);
}
return true;
}
+7 -9
View File
@@ -42,13 +42,6 @@ type EmptyFeatureMessageCatalogs = Readonly<
Record<string, Readonly<Record<never, never>>>
>;
/** The V2 API contract: operations, schema metadata, runtime codecs, mappers. */
export type EmptyFeatureApiContract = Readonly<{
apiOperations: EmptyRecord;
schemas: EmptyRecord;
runtimeSchemas: EmptyRecord;
mappers: EmptyRecord;
}>;
/**
* The executable half. `featureId` must equal the declaring module's id; the
@@ -56,12 +49,17 @@ export type EmptyFeatureApiContract = Readonly<{
* it belongs to that feature.
*/
export type FeatureRuntime<
ApiContract = EmptyFeatureApiContract,
Schemas = EmptyRecord,
Adapter = never,
ContractContribution = never,
> = Readonly<{
featureId: string;
apiContract: ApiContract;
/**
* FE-REG-SCHEMA rows (`SchemaDefinition`) for the feature's route and API
* schemas. The HTTP operations themselves are the V3 descriptors in
* `contractContributions`; FE-REG-API rows are projected from them.
*/
schemas: Schemas;
adapters: readonly Adapter[];
contractContributions: readonly ContractContribution[];
}>;
@@ -1,15 +1,9 @@
import {
composeApiOperations,
validateApiRuntimeBindings,
} from "../contracts/api-operations.ts";
import { composeBoundaryMapperRegistry } from "../contracts/boundary-mapper.ts";
import { projectApiOperationRows } from "../contracts/api-operations.ts";
import {
composeContractContributions,
type InstalledContractContribution,
} from "../contracts/external-contract-runtime.ts";
import { validateRestProfileBindings } from "../contracts/rest-profiles.ts";
import {
composeRuntimeSchemaCodecs,
composeSchemaRegistry,
PLATFORM_SCHEMA_REGISTRY,
} from "../contracts/schema-registry.ts";
@@ -22,9 +16,9 @@ import { INSTALLED_PRODUCT_FEATURE_MODULES } from "./installed-product-manifest.
/**
* 15-01. Loads every installed feature's runtime half and composes the
* registries that need all of them: the V2 API registries and the contract
* contributions. Duplicates across features throw here, as they did at boot
* before 15-01.
* registries that need all of them: the schema registry, the contract
* contributions, and the FE-REG-API rows projected from those contributions.
* Duplicates across features throw here, as they did at boot before 15-01.
*
* 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`).
@@ -35,34 +29,10 @@ export async function loadInstalledFeatureRuntimeRegistries() {
const runtimes = Object.freeze(
await Promise.all(INSTALLED_PRODUCT_FEATURE_MODULES.map(loadFeatureRuntime)),
);
type LoadedApiContract = (typeof runtimes)[number]["apiContract"];
const apiContracts: readonly LoadedApiContract[] = runtimes.map(
(runtime) => runtime.apiContract,
);
const apiOperations = composeApiOperations(
apiContracts.map((contract) => contract.apiOperations),
);
const restProfileBindingsValid = validateRestProfileBindings(
apiOperations,
Object.freeze({ PRIMARY_API: Object.freeze(["omit"] as const) }),
);
const schemaRegistry = composeSchemaRegistry([
PLATFORM_SCHEMA_REGISTRY,
...apiContracts.map((contract) => contract.schemas),
...runtimes.map((runtime) => runtime.schemas),
]);
const runtimeSchemaCodecs = composeRuntimeSchemaCodecs(
apiContracts.map((contract) => contract.runtimeSchemas),
);
const mapperRegistry = composeBoundaryMapperRegistry(
apiContracts.map((contract) => contract.mappers),
);
const apiRuntimeBindingsValid = validateApiRuntimeBindings(
apiOperations,
schemaRegistry,
runtimeSchemaCodecs,
mapperRegistry,
);
const contractContributions: readonly InstalledContractContribution[] =
Object.freeze(
@@ -94,12 +64,10 @@ export async function loadInstalledFeatureRuntimeRegistries() {
return Object.freeze({
runtimes,
apiOperations,
restProfileBindingsValid,
apiOperations: projectApiOperationRows(
composedContractContributions.contributions,
),
schemaRegistry,
runtimeSchemaCodecs,
mapperRegistry,
apiRuntimeBindingsValid,
contractContributions,
composedContractContributions,
});
-4
View File
@@ -17,11 +17,7 @@ const registries = await loadInstalledFeatureRuntimeRegistries();
export const LOADED_FEATURE_RUNTIMES = registries.runtimes;
export const API_OPERATIONS = registries.apiOperations;
export const REST_PROFILE_BINDINGS_VALID = registries.restProfileBindingsValid;
export const SCHEMA_REGISTRY = registries.schemaRegistry;
export const RUNTIME_SCHEMA_CODECS = registries.runtimeSchemaCodecs;
export const MAPPER_REGISTRY = registries.mapperRegistry;
export const API_RUNTIME_BINDINGS_VALID = registries.apiRuntimeBindingsValid;
export const INSTALLED_CONTRACT_CONTRIBUTIONS = registries.contractContributions;
export const COMPOSED_CONTRACT_CONTRIBUTIONS =
registries.composedContractContributions;
+2 -2
View File
@@ -57,8 +57,8 @@ feature가 실제 contribution을 소유한다.
- 선언(초기 청크, `feature-module.ts`): route 표와 invalidation은
`reference-feature-contract.ts`, 문구는 `reference-message-catalog.ts`
- 실행부(`feature-runtime.ts`, reference route에 들어갈 때 적재): API 계약
`reference-api-contract.ts`, bootstrap input
- 실행부(`feature-runtime.ts`, reference route에 들어갈 때 적재): 스키마 메타데이터
`reference-schema-metadata.ts`, bootstrap input
`REFERENCE_FEATURE_ADAPTER_CONTRIBUTION`, HTTP contract contribution
- route codec과 page component: `REFERENCE_FEATURE_ROUTE_CODECS`,
`REFERENCE_FEATURE_ROUTE_RUNTIME` (`context-routes.ts`가 route handle에 실어
@@ -1,155 +0,0 @@
import { defineRestOperation } from "../../../contracts/api-operations.ts";
import { REFERENCE_RUNTIME_SCHEMA_CODECS } from "./reference-schemas.ts";
import { REFERENCE_BOUNDARY_MAPPERS } from "./reference-mapper.ts";
/**
* 15-01. The V2 API contract of the reference feature: operations, schema
* metadata, runtime schema codecs and boundary mappers. Runtime half only
* (`feature-runtime.ts`); the app boot never imports it.
*/
export const REFERENCE_API_CONTRACT = Object.freeze({
runtimeSchemas: REFERENCE_RUNTIME_SCHEMA_CODECS,
mappers: REFERENCE_BOUNDARY_MAPPERS,
schemas: Object.freeze({
ReferenceResourceParams: Object.freeze({
schemaId: "ReferenceResourceParams",
boundary: "route-params",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
ReferenceResourceListQuery: Object.freeze({
schemaId: "ReferenceResourceListQuery",
boundary: "route-search-api-request",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
CreateReferenceResourceCommand: Object.freeze({
schemaId: "CreateReferenceResourceCommand",
boundary: "api-request",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
NoRequest: Object.freeze({
schemaId: "NoRequest",
boundary: "api-request",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
ReferenceResourceListPayload: Object.freeze({
schemaId: "ReferenceResourceListPayload",
boundary: "api-response",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
ReferenceResourcePayload: Object.freeze({
schemaId: "ReferenceResourcePayload",
boundary: "api-response",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
}),
apiOperations: Object.freeze({
LIST_REFERENCE_RESOURCES: defineRestOperation({
method: "GET",
path: "/api/reference-resources",
operationId: "LIST_REFERENCE_RESOURCES",
auth: "external-session",
timeoutMs: null,
idempotency: "safe",
retry: "runtime",
requestSource: "search",
requestSchema: "ReferenceResourceListQuery",
responseSchema: "ReferenceResourceListPayload",
owner: "feature-frontend-reference-feature-vertical-slice",
contractVersion: 2,
protocol: "REST",
semantics: "QUERY",
replayPolicy: "SAFE",
idempotencyKeyPolicy: "NONE",
mapperId: "ReferenceResourceListMapper",
successStatuses: [200],
responseMediaTypes: ["application/json"],
maxResponseBytes: 262_144,
providerId: "PRIMARY_API",
authProfileId: "EXTERNAL_BEARER",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "NoRequest",
pathParameterNames: [],
maxEncodedSearchBytes: 4_096,
}),
CREATE_REFERENCE_RESOURCE: defineRestOperation({
method: "POST",
path: "/api/reference-resources",
operationId: "CREATE_REFERENCE_RESOURCE",
auth: "external-session",
timeoutMs: null,
idempotency: "keyed",
retry: "runtime",
requestSource: "body",
requestSchema: "CreateReferenceResourceCommand",
responseSchema: "ReferenceResourcePayload",
owner: "feature-frontend-reference-feature-vertical-slice",
contractVersion: 2,
protocol: "REST",
semantics: "COMMAND",
replayPolicy: "KEYED_COMMAND",
idempotencyKeyPolicy: "REQUIRED",
mapperId: "ReferenceResourceMapper",
successStatuses: [200, 201],
responseMediaTypes: ["application/json"],
maxResponseBytes: 32_768,
providerId: "PRIMARY_API",
authProfileId: "EXTERNAL_BEARER",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "NoRequest",
pathParameterNames: [],
maxEncodedSearchBytes: 0,
}),
GET_REFERENCE_RESOURCE: defineRestOperation({
method: "GET",
path: "/api/reference-resources/{resourceId}",
operationId: "GET_REFERENCE_RESOURCE",
auth: "external-session",
timeoutMs: null,
idempotency: "safe",
retry: "runtime",
requestSource: "none",
requestSchema: "NoRequest",
responseSchema: "ReferenceResourcePayload",
owner: "feature-frontend-reference-feature-vertical-slice",
contractVersion: 2,
protocol: "REST",
semantics: "QUERY",
replayPolicy: "SAFE",
idempotencyKeyPolicy: "NONE",
mapperId: "ReferenceResourceMapper",
successStatuses: [200],
responseMediaTypes: ["application/json"],
maxResponseBytes: 32_768,
providerId: "PRIMARY_API",
authProfileId: "EXTERNAL_BEARER",
csrfProfileId: "NO_CSRF_BEARER",
pathSchema: "ReferenceResourceParams",
pathParameterNames: ["resourceId"],
maxEncodedSearchBytes: 0,
}),
}),
} as const);
@@ -11,9 +11,10 @@ export const REFERENCE_RESOURCE_INVALIDATION_TOPIC =
/**
* 15-01. The declaration half: what the shell reads before a reference route
* is entered. It is in the initial chunk, so it holds data only. The API
* contract with its runtime schemas and mappers is
* `reference-api-contract.ts`, loaded with `feature-runtime.ts`.
* is entered. It is in the initial chunk, so it holds data only. The schema
* metadata is `reference-schema-metadata.ts` and the HTTP operations are
* `reference-feature-contract-contribution.ts`, both loaded with
* `feature-runtime.ts`.
*/
export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
featureId: REFERENCE_FEATURE_ID,
@@ -5,7 +5,6 @@ import {
import {
mappingFailure,
mappingSuccess,
type InstalledBoundaryMapper,
type BoundaryMappingResult,
} from "../../../contracts/boundary-mapper.ts";
import type { ReferenceResourceDto } from "./reference-schemas.ts";
@@ -49,83 +48,6 @@ export function mapReferenceResourceListPayload(
return mappingSuccess(Object.freeze(output));
}
function isReferenceResourceDto(value: unknown): value is ReferenceResourceDto {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const dto = value as Record<string, unknown>;
return (
typeof dto.id === "string" &&
typeof dto.name === "string" &&
(dto.createdAt === undefined || typeof dto.createdAt === "string")
);
}
function mapUnknownReferenceResourcePayload(
value: unknown,
): BoundaryMappingResult<ReferenceResource> {
return isReferenceResourceDto(value)
? mapReferenceResourcePayload(value)
: mappingFailure("MAPPING_INVARIANT_REJECTED");
}
function mapUnknownReferenceResourceListPayload(
value: unknown,
): BoundaryMappingResult<readonly ReferenceResource[]> {
if (
!Array.isArray(value) ||
value.length > 100 ||
!value.every(isReferenceResourceDto)
) {
return mappingFailure(
Array.isArray(value) && value.length > 100
? "OUTPUT_LIMIT_EXCEEDED"
: "MAPPING_INVARIANT_REJECTED",
);
}
return mapReferenceResourceListPayload(value);
}
/**
* Registry-facing compatibility projection. The registry is intentionally
* untyped, so its adapter performs the defensive shape check. Feature HTTP
* bindings use the typed operation-specific mappers above.
*/
export function mapReferenceOperation(
operationId: string,
payload: unknown,
): BoundaryMappingResult<ReferenceResource | readonly ReferenceResource[]> {
if (operationId === "LIST_REFERENCE_RESOURCES") {
return mapUnknownReferenceResourceListPayload(payload);
}
if (
operationId === "CREATE_REFERENCE_RESOURCE" ||
operationId === "GET_REFERENCE_RESOURCE"
) {
return mapUnknownReferenceResourcePayload(payload);
}
return mappingFailure("MAPPING_INVARIANT_REJECTED");
}
export const REFERENCE_BOUNDARY_MAPPERS = Object.freeze({
ReferenceResourceListMapper: Object.freeze({
mapperId: "ReferenceResourceListMapper",
mapperVersion: 1,
inputSchemaId: "ReferenceResourceListPayload",
outputContractId: "ReferenceResourceList",
owner: "feature-frontend-reference-feature-vertical-slice",
maxOutputItems: 100,
map: mapUnknownReferenceResourceListPayload,
}),
ReferenceResourceMapper: Object.freeze({
mapperId: "ReferenceResourceMapper",
mapperVersion: 1,
inputSchemaId: "ReferenceResourcePayload",
outputContractId: "ReferenceResource",
owner: "feature-frontend-reference-feature-vertical-slice",
maxOutputItems: 1,
map: mapUnknownReferenceResourcePayload,
}),
} satisfies Readonly<Record<string, InstalledBoundaryMapper>>);
export function toReferenceView(
resource: ReferenceResource,
): ReferenceResourceView {
@@ -0,0 +1,53 @@
/**
* FE-REG-SCHEMA rows of the reference feature's route and API schemas.
* Runtime half only (`feature-runtime.ts`); the app boot never imports it.
* The HTTP operations are the V3 descriptors in
* `reference-feature-contract-contribution.ts`; FE-REG-API reads them.
*/
export const REFERENCE_SCHEMA_METADATA = Object.freeze({
ReferenceResourceParams: Object.freeze({
schemaId: "ReferenceResourceParams",
boundary: "route-params",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
ReferenceResourceListQuery: Object.freeze({
schemaId: "ReferenceResourceListQuery",
boundary: "route-search-api-request",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
CreateReferenceResourceCommand: Object.freeze({
schemaId: "CreateReferenceResourceCommand",
boundary: "api-request",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "REQUEST",
unknownFieldPolicy: "REJECT_UNKNOWN",
}),
ReferenceResourceListPayload: Object.freeze({
schemaId: "ReferenceResourceListPayload",
boundary: "api-response",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
ReferenceResourcePayload: Object.freeze({
schemaId: "ReferenceResourcePayload",
boundary: "api-response",
owner: "feature-frontend-reference-feature-vertical-slice",
runtime: "zod",
schemaVersion: 1,
direction: "RESPONSE",
unknownFieldPolicy: "STRIP_UNKNOWN",
}),
});
@@ -1,6 +1,4 @@
import { z } from "../../../contracts/zod.ts";
import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
import { zodValidator } from "../../../contracts/zod-validator.ts";
export const referenceResourceListQuerySchema = z
.object({
@@ -67,69 +65,3 @@ export const createReferenceResourceCommandSchema = z
note: z.string().trim().max(500).optional(),
})
.strict();
const payloadSchemas = {
ReferenceResourceListPayload: z.array(referenceResourceDtoSchema).max(100),
ReferenceResourcePayload: referenceResourceDtoSchema,
} satisfies Record<string, z.ZodType>;
const requestSchemas = {
ReferenceResourceParams: referenceResourceParamsSchema,
ReferenceResourceListQuery: referenceResourceListQuerySchema,
NoRequest: z.object({}).strict(),
CreateReferenceResourceCommand: createReferenceResourceCommandSchema,
} satisfies Record<string, z.ZodType>;
const codec = (schemaId: string, schema: z.ZodType) =>
runtimeSchemaCodecFromValidator(zodValidator(schemaId, schema));
export const REFERENCE_RUNTIME_SCHEMA_CODECS = Object.freeze({
ReferenceResourceParams: codec(
"ReferenceResourceParams",
referenceResourceParamsSchema,
),
ReferenceResourceListQuery: codec(
"ReferenceResourceListQuery",
referenceResourceListQuerySchema,
),
NoRequest: codec("NoRequest", requestSchemas.NoRequest),
CreateReferenceResourceCommand: codec(
"CreateReferenceResourceCommand",
requestSchemas.CreateReferenceResourceCommand,
),
ReferenceResourceListPayload: codec(
"ReferenceResourceListPayload",
payloadSchemas.ReferenceResourceListPayload,
),
ReferenceResourcePayload: codec(
"ReferenceResourcePayload",
payloadSchemas.ReferenceResourcePayload,
),
});
const NOT_REGISTERED = Object.freeze({
success: false as const,
issues: Object.freeze([
Object.freeze({ path: "", code: "SCHEMA_NOT_REGISTERED" }),
]),
});
function validateOwned(
owned: Readonly<Record<string, z.ZodType>>,
schemaId: string,
value: unknown,
) {
return Object.hasOwn(owned, schemaId)
? REFERENCE_RUNTIME_SCHEMA_CODECS[
schemaId as keyof typeof REFERENCE_RUNTIME_SCHEMA_CODECS
].parse(value)
: NOT_REGISTERED;
}
export function validateReferencePayload(schemaId: string, value: unknown) {
return validateOwned(payloadSchemas, schemaId, value);
}
export function validateReferenceRequest(schemaId: string, value: unknown) {
return validateOwned(requestSchemas, schemaId, value);
}
@@ -1,8 +1,8 @@
import { defineFeatureRuntime } from "../feature-module.ts";
import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-reference-feature-input.ts";
import { REFERENCE_API_CONTRACT } from "./contracts/reference-api-contract.ts";
import { REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION } from "./contracts/reference-feature-contract-contribution.ts";
import { REFERENCE_FEATURE_ID } from "./contracts/reference-feature-contract.ts";
import { REFERENCE_SCHEMA_METADATA } from "./contracts/reference-schema-metadata.ts";
/**
* 15-01. The executable half of the reference feature. `feature-module.ts`
@@ -12,7 +12,7 @@ import { REFERENCE_FEATURE_ID } from "./contracts/reference-feature-contract.ts"
*/
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: REFERENCE_FEATURE_ID,
apiContract: REFERENCE_API_CONTRACT,
schemas: REFERENCE_SCHEMA_METADATA,
adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION],
contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION],
} as const);