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:
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"snapshotDigest": "3c3702b55ad8849f399833206ea4515808eda6ab6d1fd5c49e90f8579e644170",
|
"snapshotDigest": "16f727424579279e0ef810620f672a8a9d74de6b71e3e9ce37ab07a82f645588",
|
||||||
"owner": "DongHyeonka",
|
"owner": "DongHyeonka",
|
||||||
"reason": "2026-11-03 사용자가 결정을 위임함: 0929/07-03, 1101/16-03, 15-01 source 경로. 승인 뒤 쌓인 0925/08-13·1101/05-01(증거로 유지), VITE_BUILD_ID 기본값·service-worker.start.failed 행(증거 불필요)도 함께 흡수",
|
"reason": "2026-11-03 사용자 승인('둘 다 지워'): V2 API 행 제거. FE-REG-API 행은 V3 descriptor에서 뽑은 projection(operationId·featureId·method·path·authProfileId·retrySemantics·requestBody·responseBody·responseEnvelope·request/response/problemSchema)이다. V3 descriptor가 쓰지 않는 참조 기능 NoRequest 스키마 행 제거",
|
||||||
"approvedAt": "2026-11-02T15:53:54.852Z"
|
"approvedAt": "2026-11-03T12:22:21.004Z"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -330,30 +330,32 @@
|
|||||||
"rowCount": 3,
|
"rowCount": 3,
|
||||||
"contract": {
|
"contract": {
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
|
"operationId",
|
||||||
|
"featureId",
|
||||||
"method",
|
"method",
|
||||||
"path",
|
"path",
|
||||||
"operationId",
|
"authProfileId",
|
||||||
"auth",
|
"retrySemantics",
|
||||||
"timeoutMs",
|
"requestBody",
|
||||||
"idempotency",
|
"responseBody",
|
||||||
"retry",
|
"responseEnvelope",
|
||||||
"requestSource",
|
|
||||||
"requestSchema",
|
"requestSchema",
|
||||||
"responseSchema",
|
"responseSchema",
|
||||||
"owner"
|
"problemSchema"
|
||||||
],
|
],
|
||||||
"fieldTypes": {
|
"fieldTypes": {
|
||||||
|
"operationId": "string",
|
||||||
|
"featureId": "string",
|
||||||
"method": "string",
|
"method": "string",
|
||||||
"path": "string",
|
"path": "string",
|
||||||
"operationId": "string",
|
"authProfileId": "string",
|
||||||
"auth": "string",
|
"retrySemantics": "string",
|
||||||
"timeoutMs": "integer|null",
|
"requestBody": "string",
|
||||||
"idempotency": "string",
|
"responseBody": "string",
|
||||||
"retry": "string",
|
"responseEnvelope": "string",
|
||||||
"requestSource": "string",
|
|
||||||
"requestSchema": "string",
|
"requestSchema": "string",
|
||||||
"responseSchema": "string",
|
"responseSchema": "string",
|
||||||
"owner": "string"
|
"problemSchema": "string"
|
||||||
},
|
},
|
||||||
"uniqueFields": [
|
"uniqueFields": [
|
||||||
"operationId"
|
"operationId"
|
||||||
@@ -361,28 +363,30 @@
|
|||||||
"allowedValues": {
|
"allowedValues": {
|
||||||
"method": [
|
"method": [
|
||||||
"GET",
|
"GET",
|
||||||
|
"HEAD",
|
||||||
"POST",
|
"POST",
|
||||||
"PUT",
|
"PUT",
|
||||||
"PATCH",
|
"PATCH",
|
||||||
"DELETE"
|
"DELETE"
|
||||||
],
|
],
|
||||||
"auth": [
|
"retrySemantics": [
|
||||||
"none",
|
"SAFE",
|
||||||
"external-session"
|
"IDEMPOTENT",
|
||||||
|
"KEYED",
|
||||||
|
"NEVER"
|
||||||
],
|
],
|
||||||
"idempotency": [
|
"requestBody": [
|
||||||
"safe",
|
"NONE",
|
||||||
"keyed",
|
"JSON"
|
||||||
"none"
|
|
||||||
],
|
],
|
||||||
"retry": [
|
"responseBody": [
|
||||||
"runtime",
|
"REQUIRED_JSON",
|
||||||
"never"
|
"OPTIONAL_JSON",
|
||||||
|
"NONE"
|
||||||
],
|
],
|
||||||
"requestSource": [
|
"responseEnvelope": [
|
||||||
"none",
|
"NONE",
|
||||||
"search",
|
"ENVELOPE_V1"
|
||||||
"body"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"references": [
|
"references": [
|
||||||
@@ -399,115 +403,60 @@
|
|||||||
],
|
],
|
||||||
"keyField": "operationId",
|
"keyField": "operationId",
|
||||||
"breakingFields": [
|
"breakingFields": [
|
||||||
|
"operationId",
|
||||||
"method",
|
"method",
|
||||||
"path",
|
"path",
|
||||||
"operationId",
|
"authProfileId",
|
||||||
"auth",
|
"retrySemantics",
|
||||||
"idempotency",
|
"requestBody",
|
||||||
"requestSource",
|
"responseBody",
|
||||||
|
"responseEnvelope",
|
||||||
"requestSchema",
|
"requestSchema",
|
||||||
"responseSchema"
|
"responseSchema"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"rows": {
|
"rows": {
|
||||||
"CREATE_REFERENCE_RESOURCE": {
|
"CREATE_REFERENCE_RESOURCE": {
|
||||||
"auth": "external-session",
|
|
||||||
"authProfileId": "EXTERNAL_BEARER",
|
"authProfileId": "EXTERNAL_BEARER",
|
||||||
"contractVersion": 2,
|
"featureId": "reference-feature",
|
||||||
"csrfProfileId": "NO_CSRF_BEARER",
|
|
||||||
"idempotency": "keyed",
|
|
||||||
"idempotencyKeyPolicy": "REQUIRED",
|
|
||||||
"mapperId": "ReferenceResourceMapper",
|
|
||||||
"maxEncodedSearchBytes": 0,
|
|
||||||
"maxResponseBytes": 32768,
|
|
||||||
"method": "POST",
|
"method": "POST",
|
||||||
"operationId": "CREATE_REFERENCE_RESOURCE",
|
"operationId": "CREATE_REFERENCE_RESOURCE",
|
||||||
"owner": "feature-frontend-reference-feature-vertical-slice",
|
|
||||||
"path": "/api/reference-resources",
|
"path": "/api/reference-resources",
|
||||||
"pathParameterNames": [],
|
"problemSchema": "ReferenceProblem",
|
||||||
"pathSchema": "NoRequest",
|
"requestBody": "JSON",
|
||||||
"protocol": "REST",
|
|
||||||
"providerId": "PRIMARY_API",
|
|
||||||
"replayPolicy": "KEYED_COMMAND",
|
|
||||||
"requestSchema": "CreateReferenceResourceCommand",
|
"requestSchema": "CreateReferenceResourceCommand",
|
||||||
"requestSource": "body",
|
"responseBody": "REQUIRED_JSON",
|
||||||
"responseMediaTypes": [
|
"responseEnvelope": "NONE",
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"responseSchema": "ReferenceResourcePayload",
|
"responseSchema": "ReferenceResourcePayload",
|
||||||
"retry": "runtime",
|
"retrySemantics": "KEYED"
|
||||||
"semantics": "COMMAND",
|
|
||||||
"successStatuses": [
|
|
||||||
200,
|
|
||||||
201
|
|
||||||
],
|
|
||||||
"timeoutMs": null
|
|
||||||
},
|
},
|
||||||
"GET_REFERENCE_RESOURCE": {
|
"GET_REFERENCE_RESOURCE": {
|
||||||
"auth": "external-session",
|
|
||||||
"authProfileId": "EXTERNAL_BEARER",
|
"authProfileId": "EXTERNAL_BEARER",
|
||||||
"contractVersion": 2,
|
"featureId": "reference-feature",
|
||||||
"csrfProfileId": "NO_CSRF_BEARER",
|
|
||||||
"idempotency": "safe",
|
|
||||||
"idempotencyKeyPolicy": "NONE",
|
|
||||||
"mapperId": "ReferenceResourceMapper",
|
|
||||||
"maxEncodedSearchBytes": 0,
|
|
||||||
"maxResponseBytes": 32768,
|
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"operationId": "GET_REFERENCE_RESOURCE",
|
"operationId": "GET_REFERENCE_RESOURCE",
|
||||||
"owner": "feature-frontend-reference-feature-vertical-slice",
|
|
||||||
"path": "/api/reference-resources/{resourceId}",
|
"path": "/api/reference-resources/{resourceId}",
|
||||||
"pathParameterNames": [
|
"problemSchema": "ReferenceProblem",
|
||||||
"resourceId"
|
"requestBody": "NONE",
|
||||||
],
|
"requestSchema": "ReferenceResourceParams",
|
||||||
"pathSchema": "ReferenceResourceParams",
|
"responseBody": "REQUIRED_JSON",
|
||||||
"protocol": "REST",
|
"responseEnvelope": "NONE",
|
||||||
"providerId": "PRIMARY_API",
|
|
||||||
"replayPolicy": "SAFE",
|
|
||||||
"requestSchema": "NoRequest",
|
|
||||||
"requestSource": "none",
|
|
||||||
"responseMediaTypes": [
|
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"responseSchema": "ReferenceResourcePayload",
|
"responseSchema": "ReferenceResourcePayload",
|
||||||
"retry": "runtime",
|
"retrySemantics": "SAFE"
|
||||||
"semantics": "QUERY",
|
|
||||||
"successStatuses": [
|
|
||||||
200
|
|
||||||
],
|
|
||||||
"timeoutMs": null
|
|
||||||
},
|
},
|
||||||
"LIST_REFERENCE_RESOURCES": {
|
"LIST_REFERENCE_RESOURCES": {
|
||||||
"auth": "external-session",
|
|
||||||
"authProfileId": "EXTERNAL_BEARER",
|
"authProfileId": "EXTERNAL_BEARER",
|
||||||
"contractVersion": 2,
|
"featureId": "reference-feature",
|
||||||
"csrfProfileId": "NO_CSRF_BEARER",
|
|
||||||
"idempotency": "safe",
|
|
||||||
"idempotencyKeyPolicy": "NONE",
|
|
||||||
"mapperId": "ReferenceResourceListMapper",
|
|
||||||
"maxEncodedSearchBytes": 4096,
|
|
||||||
"maxResponseBytes": 262144,
|
|
||||||
"method": "GET",
|
"method": "GET",
|
||||||
"operationId": "LIST_REFERENCE_RESOURCES",
|
"operationId": "LIST_REFERENCE_RESOURCES",
|
||||||
"owner": "feature-frontend-reference-feature-vertical-slice",
|
|
||||||
"path": "/api/reference-resources",
|
"path": "/api/reference-resources",
|
||||||
"pathParameterNames": [],
|
"problemSchema": "ReferenceProblem",
|
||||||
"pathSchema": "NoRequest",
|
"requestBody": "NONE",
|
||||||
"protocol": "REST",
|
|
||||||
"providerId": "PRIMARY_API",
|
|
||||||
"replayPolicy": "SAFE",
|
|
||||||
"requestSchema": "ReferenceResourceListQuery",
|
"requestSchema": "ReferenceResourceListQuery",
|
||||||
"requestSource": "search",
|
"responseBody": "REQUIRED_JSON",
|
||||||
"responseMediaTypes": [
|
"responseEnvelope": "NONE",
|
||||||
"application/json"
|
|
||||||
],
|
|
||||||
"responseSchema": "ReferenceResourceListPayload",
|
"responseSchema": "ReferenceResourceListPayload",
|
||||||
"retry": "runtime",
|
"retrySemantics": "SAFE"
|
||||||
"semantics": "QUERY",
|
|
||||||
"successStatuses": [
|
|
||||||
200
|
|
||||||
],
|
|
||||||
"timeoutMs": null
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -515,7 +464,7 @@
|
|||||||
"registryId": "FE-REG-SCHEMA",
|
"registryId": "FE-REG-SCHEMA",
|
||||||
"owner": "feature-frontend-contract-schema-registry",
|
"owner": "feature-frontend-contract-schema-registry",
|
||||||
"source": "src/features/loaded-feature-runtimes.ts",
|
"source": "src/features/loaded-feature-runtimes.ts",
|
||||||
"rowCount": 8,
|
"rowCount": 7,
|
||||||
"contract": {
|
"contract": {
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
"schemaId",
|
"schemaId",
|
||||||
@@ -568,15 +517,6 @@
|
|||||||
"runtime": "zod",
|
"runtime": "zod",
|
||||||
"schemaId": "none"
|
"schemaId": "none"
|
||||||
},
|
},
|
||||||
"NoRequest": {
|
|
||||||
"boundary": "api-request",
|
|
||||||
"direction": "REQUEST",
|
|
||||||
"owner": "feature-frontend-reference-feature-vertical-slice",
|
|
||||||
"runtime": "zod",
|
|
||||||
"schemaId": "NoRequest",
|
|
||||||
"schemaVersion": 1,
|
|
||||||
"unknownFieldPolicy": "REJECT_UNKNOWN"
|
|
||||||
},
|
|
||||||
"NotFoundSplat": {
|
"NotFoundSplat": {
|
||||||
"boundary": "route-params",
|
"boundary": "route-params",
|
||||||
"owner": "feature-frontend-routing-release-recovery-runtime",
|
"owner": "feature-frontend-routing-release-recovery-runtime",
|
||||||
|
|||||||
@@ -138,38 +138,64 @@
|
|||||||
"owner": "feature-frontend-api-client-response-envelope-contract",
|
"owner": "feature-frontend-api-client-response-envelope-contract",
|
||||||
"keyField": "operationId",
|
"keyField": "operationId",
|
||||||
"requiredFields": [
|
"requiredFields": [
|
||||||
|
"operationId",
|
||||||
|
"featureId",
|
||||||
"method",
|
"method",
|
||||||
"path",
|
"path",
|
||||||
"operationId",
|
"authProfileId",
|
||||||
"auth",
|
"retrySemantics",
|
||||||
"timeoutMs",
|
"requestBody",
|
||||||
"idempotency",
|
"responseBody",
|
||||||
"retry",
|
"responseEnvelope",
|
||||||
"requestSource",
|
|
||||||
"requestSchema",
|
"requestSchema",
|
||||||
"responseSchema",
|
"responseSchema",
|
||||||
"owner"
|
"problemSchema"
|
||||||
],
|
],
|
||||||
"fieldTypes": {
|
"fieldTypes": {
|
||||||
|
"operationId": "string",
|
||||||
|
"featureId": "string",
|
||||||
"method": "string",
|
"method": "string",
|
||||||
"path": "string",
|
"path": "string",
|
||||||
"operationId": "string",
|
"authProfileId": "string",
|
||||||
"auth": "string",
|
"retrySemantics": "string",
|
||||||
"timeoutMs": "integer|null",
|
"requestBody": "string",
|
||||||
"idempotency": "string",
|
"responseBody": "string",
|
||||||
"retry": "string",
|
"responseEnvelope": "string",
|
||||||
"requestSource": "string",
|
|
||||||
"requestSchema": "string",
|
"requestSchema": "string",
|
||||||
"responseSchema": "string",
|
"responseSchema": "string",
|
||||||
"owner": "string"
|
"problemSchema": "string"
|
||||||
},
|
},
|
||||||
"uniqueFields": ["operationId"],
|
"uniqueFields": [
|
||||||
|
"operationId"
|
||||||
|
],
|
||||||
"allowedValues": {
|
"allowedValues": {
|
||||||
"method": ["GET", "POST", "PUT", "PATCH", "DELETE"],
|
"method": [
|
||||||
"auth": ["none", "external-session"],
|
"GET",
|
||||||
"idempotency": ["safe", "keyed", "none"],
|
"HEAD",
|
||||||
"retry": ["runtime", "never"],
|
"POST",
|
||||||
"requestSource": ["none", "search", "body"]
|
"PUT",
|
||||||
|
"PATCH",
|
||||||
|
"DELETE"
|
||||||
|
],
|
||||||
|
"retrySemantics": [
|
||||||
|
"SAFE",
|
||||||
|
"IDEMPOTENT",
|
||||||
|
"KEYED",
|
||||||
|
"NEVER"
|
||||||
|
],
|
||||||
|
"requestBody": [
|
||||||
|
"NONE",
|
||||||
|
"JSON"
|
||||||
|
],
|
||||||
|
"responseBody": [
|
||||||
|
"REQUIRED_JSON",
|
||||||
|
"OPTIONAL_JSON",
|
||||||
|
"NONE"
|
||||||
|
],
|
||||||
|
"responseEnvelope": [
|
||||||
|
"NONE",
|
||||||
|
"ENVELOPE_V1"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"references": [
|
"references": [
|
||||||
{
|
{
|
||||||
@@ -189,12 +215,14 @@
|
|||||||
"src/features/*/application"
|
"src/features/*/application"
|
||||||
],
|
],
|
||||||
"breakingFields": [
|
"breakingFields": [
|
||||||
|
"operationId",
|
||||||
"method",
|
"method",
|
||||||
"path",
|
"path",
|
||||||
"operationId",
|
"authProfileId",
|
||||||
"auth",
|
"retrySemantics",
|
||||||
"idempotency",
|
"requestBody",
|
||||||
"requestSource",
|
"responseBody",
|
||||||
|
"responseEnvelope",
|
||||||
"requestSchema",
|
"requestSchema",
|
||||||
"responseSchema"
|
"responseSchema"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -546,12 +546,12 @@ query invalidate hint로만 쓸지 operation별 reducer contract가 필요하다
|
|||||||
같은 이름의 정책이라도 전송마다 동작이 다르다. operation을 다른 전송으로 옮기면
|
같은 이름의 정책이라도 전송마다 동작이 다르다. operation을 다른 전송으로 옮기면
|
||||||
이 표로 동작 변화를 확인한다.
|
이 표로 동작 변화를 확인한다.
|
||||||
|
|
||||||
| 규칙 | V3 contract executor (기본 경로) | V2 client (기본 조합에 없음) | Browser RPC |
|
| 규칙 | V3 contract executor | Browser RPC |
|
||||||
|---|---|---|---|
|
|---|---|---|
|
||||||
| KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답(5xx·429)으로는 재시도하지 않는다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`) | 네트워크·타임아웃·429·408/425/502/503/504 뒤 같은 키로 다시 보낸다. 전송 여부를 보지 않는다 (`src/adapters/http/retry-policy.ts` `shouldRetry`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) |
|
| KEYED 명령 자동 재시도 | 전송 전 실패만 재시도한다. 전송 뒤 실패는 재시도하지 않고 `MAYBE_APPLIED`다. 응답(5xx·429)으로는 재시도하지 않는다 (`src/adapters/http/http-retry-lifecycle.ts` `canRetryTransport`, `isRetryableSemantics`) | `KEYED_COMMAND`는 유효한 키가 있고 profile `retryOwner`가 `FRONTEND_ADAPTER`면 `retryableFailures`에서 같은 키로 다시 보낸다 (`src/adapters/browser-rpc/browser-rpc-runtime.ts` `shouldRetry`) |
|
||||||
| 재시도 횟수 상한 | min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2) (`http-execution-v3.ts` `retryCeiling`) | `MAX_RETRY_ATTEMPTS`, 기본 2 (`client.ts` `maxRetryAttempts`) | profile `maxAttempts`(시도 횟수), 하드 상한 4 (`src/contracts/browser-rpc.ts` `BROWSER_RPC_HARD_LIMITS`) |
|
| 재시도 횟수 상한 | min(계약 `retryBudget`, `MAX_RETRY_ATTEMPTS`, 2) (`http-execution-v3.ts` `retryCeiling`) | profile `maxAttempts`(시도 횟수), 하드 상한 4 (`src/contracts/browser-rpc.ts` `BROWSER_RPC_HARD_LIMITS`) |
|
||||||
| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | 30초를 넘으면 재시도하지 않는다. 이하면 max(backoff, hint)만큼 기다린다 (`retry-policy.ts`) | profile `maxRetryAfterMs`로 잘라 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `retryDelay`) |
|
| `Retry-After` | 5초를 넘으면 재시도하지 않는다. 이하면 hint에 jitter를 더해 기다린다 (`http-retry-lifecycle.ts` `retryDelayFor`) | profile `maxRetryAfterMs`로 잘라 max(backoff, hint)만큼 기다린다. 하드 상한 60초 (`browser-rpc-runtime.ts` `retryDelay`) |
|
||||||
| `REQUEST_TIMEOUT_MS` | 상한이다. 계약 `totalDeadlineMs`를 줄이기만 한다 (`runtime-adapters.ts` `requestDeadlineCeilingMs`) | 기본값이다. operation `timeoutMs`가 있으면 그 값을 쓰고, 더 길 수도 있다 (`client.ts` `defaultTimeoutMs`) | 쓰지 않는다. operation `totalDeadlineMs`만 쓴다. 하드 상한 30분 |
|
| `REQUEST_TIMEOUT_MS` | 상한이다. 계약 `totalDeadlineMs`를 줄이기만 한다 (`runtime-adapters.ts` `requestDeadlineCeilingMs`) | 쓰지 않는다. operation `totalDeadlineMs`만 쓴다. 하드 상한 30분 |
|
||||||
|
|
||||||
결과 불명 뒤 사용자 재전송은 전송과 무관하게 같은 intent·같은 키를 쓴다
|
결과 불명 뒤 사용자 재전송은 전송과 무관하게 같은 intent·같은 키를 쓴다
|
||||||
(`src/presentation/adapters/query/application-query.ts` `resendUnknownEffect`).
|
(`src/presentation/adapters/query/application-query.ts` `resendUnknownEffect`).
|
||||||
|
|||||||
@@ -141,10 +141,9 @@ selected app. Every build and check script runs it first; run it yourself with
|
|||||||
entered. Do not import it statically from anywhere: each feature would add
|
entered. Do not import it statically from anywhere: each feature would add
|
||||||
its whole executable code to the initial chunk again, about 3.9 KB gzip
|
its whole executable code to the initial chunk again, about 3.9 KB gzip
|
||||||
(`tests/unit/feature-shape-growth.test.ts` bounds one feature at 1 KiB).
|
(`tests/unit/feature-shape-growth.test.ts` bounds one feature at 1 KiB).
|
||||||
An HTTP API is written twice: its API contract operation (V2) is what
|
An HTTP API is written once, as its contract contribution descriptor: it
|
||||||
`check:registries` governs, and its contract contribution descriptor (V3)
|
executes, and `check:registries` governs the FE-REG-API row projected from
|
||||||
is what executes. `tests/unit/http-operation-v2-v3-parity.test.ts` fails
|
it (`projectApiOperationRows` in `src/contracts/api-operations.ts`).
|
||||||
when one exists without the other or when they disagree.
|
|
||||||
A product feature's contract contribution uses an `EXTERNAL_PACKAGE`
|
A product feature's contract contribution uses an `EXTERNAL_PACKAGE`
|
||||||
source. `TEMPLATE_FIXTURE` belongs to `reference-feature` only and never
|
source. `TEMPLATE_FIXTURE` belongs to `reference-feature` only and never
|
||||||
joins the release contract set; the composer rejects it anywhere else.
|
joins the release contract set; the composer rejects it anywhere else.
|
||||||
|
|||||||
@@ -158,12 +158,12 @@ corepack pnpm create:feature invoice-feature
|
|||||||
생성된 파일:
|
생성된 파일:
|
||||||
|
|
||||||
- `contracts/<base>-feature-contract.ts`: 선언 쪽. 라우트, 무효화, 계약 패키지 신원(`contractPackages`).
|
- `contracts/<base>-feature-contract.ts`: 선언 쪽. 라우트, 무효화, 계약 패키지 신원(`contractPackages`).
|
||||||
- `contracts/<base>-api-contract.ts`: V2 행. `check:registries`가 검사하는 선언이다.
|
- `contracts/<base>-contract-contribution.ts`: HTTP 계약(descriptor). operation을 적는 곳은 여기 하나다. 이것이 실행되고, `check:registries`의 FE-REG-API 행도 여기서 뽑는다.
|
||||||
- `contracts/<base>-contract-contribution.ts`: V3 descriptor. 실제로 실행되는 HTTP 계약이다.
|
- `contracts/<base>-schema-metadata.ts`: 스키마 메타데이터(FE-REG-SCHEMA 행). 스키마 ID마다 쓰이는 자리(`boundary`)와 소유자를 적는다.
|
||||||
- `contracts/<base>-schemas.ts`: zod 스키마와 검증기.
|
- `contracts/<base>-schemas.ts`: zod 스키마와 검증기.
|
||||||
- `contracts/<base>-mapper.ts`: 와이어 값 → 화면 값.
|
- `contracts/<base>-mapper.ts`: 와이어 값 → 화면 값.
|
||||||
|
|
||||||
같은 API를 V2와 V3로 두 번 쓴다. V2는 레지스트리 검사용 선언이고, V3는 실행용이다.
|
FE-REG-API 행은 descriptor에서 자동으로 만든다(`src/contracts/api-operations.ts`의 `projectApiOperationRows`). 같은 API를 다른 파일에 다시 적지 않는다.
|
||||||
|
|
||||||
① **정할 것**
|
① **정할 것**
|
||||||
|
|
||||||
@@ -172,8 +172,8 @@ corepack pnpm create:feature invoice-feature
|
|||||||
- 재시도 의미(`retrySemantics`). [02 결정표 3절](02-decision-tables.md#3-재시도-의미)
|
- 재시도 의미(`retrySemantics`). [02 결정표 3절](02-decision-tables.md#3-재시도-의미)
|
||||||
- 쓰기의 실패 분류(`commandEffect`). [02 결정표 4절](02-decision-tables.md#4-결과-불명)
|
- 쓰기의 실패 분류(`commandEffect`). [02 결정표 4절](02-decision-tables.md#4-결과-불명)
|
||||||
- 인증 프로필(`authProfileId`). [02 결정표 5절](02-decision-tables.md#5-인증)
|
- 인증 프로필(`authProfileId`). [02 결정표 5절](02-decision-tables.md#5-인증)
|
||||||
- 바이트 한도·마감: V3 `requestByteLimit`, `responseByteLimit`, `totalDeadlineMs`. V2 `maxResponseBytes`는 V3 `responseByteLimit`와 같은 값이다.
|
- 바이트 한도·마감: `requestByteLimit`, `responseByteLimit`, `totalDeadlineMs`.
|
||||||
- 스키마 ID, mapper ID, operation ID. 모두 기능 접두어를 붙인다([reference/global-ids.md](reference/global-ids.md)).
|
- 스키마 ID, operation ID. 모두 기능 접두어를 붙인다([reference/global-ids.md](reference/global-ids.md)).
|
||||||
|
|
||||||
② **기준**
|
② **기준**
|
||||||
|
|
||||||
@@ -203,8 +203,8 @@ corepack pnpm create:feature invoice-feature
|
|||||||
- 백엔드는 값이 null인 필드를 키째 뺀다. `data` 키가 없으면 `null`로 읽는다. DTO 안에서 null일 수 있는 필드는 스키마에서 `.optional()`로 받는다.
|
- 백엔드는 값이 null인 필드를 키째 뺀다. `data` 키가 없으면 `null`로 읽는다. DTO 안에서 null일 수 있는 필드는 스키마에서 `.optional()`로 받는다.
|
||||||
- problem 스키마(`<base>-schemas.ts`의 `<base>ProblemSchema`)는 Envelope의 `error` 객체다. 분기는 `code`로 한다. `message`는 버린다.
|
- problem 스키마(`<base>-schemas.ts`의 `<base>ProblemSchema`)는 Envelope의 `error` 객체다. 분기는 `code`로 한다. `message`는 버린다.
|
||||||
- 400·409·422와 503 `IDEMPOTENCY_UNAVAILABLE`가 적용됐는지는 실행기가 백엔드 기준 표로 정한다. 목록은 [02 결정표 4절](02-decision-tables.md#4-결과-불명)이다.
|
- 400·409·422와 503 `IDEMPOTENCY_UNAVAILABLE`가 적용됐는지는 실행기가 백엔드 기준 표로 정한다. 목록은 [02 결정표 4절](02-decision-tables.md#4-결과-불명)이다.
|
||||||
- `mapProblem`이 없거나 `undefined`를 돌려주면 V2 클라이언트와 같은 kind·code·필드 오류로 읽는다(`src/adapters/http/backend-envelope.ts`).
|
- `mapProblem`이 없거나 `undefined`를 돌려주면 백엔드 code·필드 오류·status별 kind로 읽는다(`src/adapters/http/backend-envelope.ts`).
|
||||||
- 바이트 상한(`responseByteLimit`)과 구조 예산은 Envelope 전체에 걸린다. V2 `maxResponseBytes`와 같은 값이다.
|
- 바이트 상한(`responseByteLimit`)과 구조 예산은 Envelope 전체에 걸린다.
|
||||||
- MSW: `createHttpScenarioHandler`는 descriptor의 `responseEnvelope`를 보고 Envelope로 답한다(`tests/mocks/handlers/http-scenarios.ts`). 생성된 `tests/features/<id>/<base>-http-gateway.test.ts`는 백엔드 본문을 그대로 적어 검사한다.
|
- MSW: `createHttpScenarioHandler`는 descriptor의 `responseEnvelope`를 보고 Envelope로 답한다(`tests/mocks/handlers/http-scenarios.ts`). 생성된 `tests/features/<id>/<base>-http-gateway.test.ts`는 백엔드 본문을 그대로 적어 검사한다.
|
||||||
- `http-contract.md`는 status·`code`의 **뜻**(예: 409 `IDEMPOTENT_IN_FLIGHT`)의 정본이다. 기능 코드에서 그 code는 problem의 `code`로 읽는다.
|
- `http-contract.md`는 status·`code`의 **뜻**(예: 409 `IDEMPOTENT_IN_FLIGHT`)의 정본이다. 기능 코드에서 그 code는 problem의 `code`로 읽는다.
|
||||||
|
|
||||||
@@ -218,69 +218,56 @@ DTO와 problem details(`type`·`title`·`status`)를 감싸지 않고 보내는
|
|||||||
|
|
||||||
참조 기능(`src/features/reference-feature/`)이 이 모양이다. 참조 기능의 MSW 본문도 DTO와 problem details다.
|
참조 기능(`src/features/reference-feature/`)이 이 모양이다. 참조 기능의 MSW 본문도 DTO와 problem details다.
|
||||||
|
|
||||||
**V2 행의 입력 칸**
|
**입력과 스키마 메타데이터**
|
||||||
|
|
||||||
V2 행은 입력을 두 칸으로 나눠 적는다. 경로 파라미터는 `pathSchema`, 검색값·본문은 `requestSchema`다. V3는 입력 전체를 `inputValidator` 하나로 검증한다.
|
`inputValidator` 하나가 operation 입력 전체를 검증한다. 입력이 요청의 어디로 가는지는 `projectRequest`가 정한다.
|
||||||
|
|
||||||
정본: 칸 정의는 `src/contracts/api-operations.ts`(`RestOperationV2`, `validateRestOperation`), 스키마 칸은 `src/contracts/schema-registry.ts`(`SchemaDefinition`). 아래는 자주 바꾸고 자주 막히는 칸만 적는다.
|
- 경로 파라미터: `pathValues`. 키는 `pathTemplate`의 `{이름}`과 같다.
|
||||||
|
- 검색값: `queryEntries`. 인코딩한 쿼리는 8,192바이트까지다(`HTTP_EXECUTION_CEILINGS.encodedQueryBytes`).
|
||||||
|
- 본문: `body`. `requestBody: "JSON"`일 때만 쓴다. 아니면 `null`이다.
|
||||||
|
|
||||||
| 칸 | 뜻 | 값 고르는 법 | V3 짝 |
|
경로 파라미터와 본문을 함께 받는 operation(예: `PUT /items/{id}` + 본문)은 입력 스키마 하나에 둘을 담고 `projectRequest`가 나눈다.
|
||||||
|---|---|---|---|
|
|
||||||
| `requestSource` | 입력이 요청의 어디로 가나 | `none`(입력 없음, 또는 경로 파라미터만), `search`(쿼리 문자열), `body`(JSON 본문) | `body`면 `requestBody: "JSON"`, 아니면 `"NONE"` |
|
정본: descriptor 칸은 `src/contracts/external-contract-runtime.ts`(`InstalledHttpContract`), 스키마 메타데이터 칸은 `src/contracts/schema-registry.ts`(`SchemaDefinition`).
|
||||||
| `requestSchema` | 검색값·본문 스키마 ID | `requestSource`가 `none`이면 기능의 빈 입력 스키마(`<Base>NoRequest`) | `requestSource`가 `none`이 아니면 `inputValidator`의 스키마 ID와 같다 |
|
|
||||||
| `pathSchema` | 경로 파라미터 스키마 ID. 비울 수 없다 | 경로 파라미터가 없으면 빈 입력 스키마 | 파라미터가 있으면 `inputValidator`의 스키마 ID와 같다 |
|
|
||||||
| `pathParameterNames` | `path`의 `{이름}` 목록 | `path`에 적은 이름과 정확히 같게. 없으면 `[]` | `projectRequest`가 돌려주는 `pathValues`의 키 |
|
|
||||||
| `maxEncodedSearchBytes` | 인코딩한 쿼리 문자열의 바이트 상한(0~32,768). V2 실행기만 읽는다 | 검색값이 없으면 0. 있으면 값의 최대 길이로 정한다(참조 기능 4,096) | 없음. V3는 고정 상한 8,192바이트(`HTTP_EXECUTION_CEILINGS.encodedQueryBytes`)를 쓴다 |
|
|
||||||
| 스키마 `boundary` | 그 스키마가 쓰이는 자리 | 아래 목록 | 없음 |
|
|
||||||
|
|
||||||
스키마 `boundary` 값:
|
스키마 `boundary` 값:
|
||||||
|
|
||||||
- `route-params`: 라우트 경로 파라미터(`paramsSchema`). 같은 스키마를 GET의 `pathSchema`로도 쓴다.
|
- `route-params`: 라우트 경로 파라미터(`paramsSchema`). 같은 스키마를 경로 파라미터 GET의 `inputValidator`로도 쓴다.
|
||||||
- `route-search`: 라우트 검색값에만 쓴다.
|
- `route-search`: 라우트 검색값에만 쓴다.
|
||||||
- `route-search-api-request`: 라우트 검색값이면서 GET 쿼리다. 목록 검색이 이 경우다.
|
- `route-search-api-request`: 라우트 검색값이면서 GET 쿼리다. 목록 검색이 이 경우다.
|
||||||
- `api-request`: 요청 본문, 그리고 빈 입력 스키마.
|
- `api-request`: 요청 입력.
|
||||||
- `api-response`: 응답 DTO.
|
- `api-response`: 응답 DTO.
|
||||||
|
|
||||||
예: 공지 기능의 검색값 GET과 경로 파라미터 GET. 입력 칸만 적었다. 나머지 칸은 생성된 행과 같다.
|
예: 공지 기능의 검색값 GET과 경로 파라미터 GET. 입력에 관한 칸만 적었다.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
// GET /api/notices?q=... → V3 inputValidator: NoticeListQuery, projectRequest는 queryEntries를 채운다
|
// GET /api/notices?q=... inputValidator 스키마 NoticeListQuery (boundary: "route-search-api-request")
|
||||||
NOTICE_LIST_ITEMS: defineRestOperation({
|
pathTemplate: "/api/notices",
|
||||||
method: "GET",
|
inputValidator: zodValidator("NoticeListQuery", noticeListQuerySchema),
|
||||||
path: "/api/notices",
|
projectRequest: (input) => Object.freeze({
|
||||||
requestSource: "search",
|
pathValues: Object.freeze({}),
|
||||||
requestSchema: "NoticeListQuery", // boundary: "route-search-api-request"
|
queryEntries: Object.freeze(input.q === undefined ? [] : [Object.freeze(["q", input.q] as const)]),
|
||||||
pathSchema: "NoticeNoRequest", // boundary: "api-request"
|
body: null,
|
||||||
pathParameterNames: [],
|
|
||||||
maxEncodedSearchBytes: 4_096,
|
|
||||||
}),
|
}),
|
||||||
// GET /api/notices/{noticeId} → V3 inputValidator: NoticeParams, projectRequest는 pathValues를 채운다
|
|
||||||
NOTICE_GET_ITEM: defineRestOperation({
|
// GET /api/notices/{noticeId} inputValidator 스키마 NoticeParams (boundary: "route-params")
|
||||||
method: "GET",
|
pathTemplate: "/api/notices/{noticeId}",
|
||||||
path: "/api/notices/{noticeId}",
|
inputValidator: zodValidator("NoticeParams", noticeParamsSchema),
|
||||||
requestSource: "none",
|
projectRequest: (input) => Object.freeze({
|
||||||
requestSchema: "NoticeNoRequest",
|
pathValues: Object.freeze({ noticeId: input.noticeId }),
|
||||||
pathSchema: "NoticeParams", // boundary: "route-params"
|
queryEntries: Object.freeze([]),
|
||||||
pathParameterNames: ["noticeId"],
|
body: null,
|
||||||
maxEncodedSearchBytes: 0,
|
|
||||||
}),
|
}),
|
||||||
```
|
```
|
||||||
|
|
||||||
경로 파라미터와 검색값·본문을 함께 받는 operation(예: `PUT /items/{id}` + 본문)은 아직 규칙이 없다. V2/V3 일치 테스트가 `V2 declares both a path and a request schema; decide which V3 input schema matches them`로 실패한다.
|
|
||||||
|
|
||||||
③ **잡는 검사 / 못 잡는 것**
|
③ **잡는 검사 / 못 잡는 것**
|
||||||
|
|
||||||
- V2와 V3가 다르면 `tests/unit/http-operation-v2-v3-parity.test.ts`(`test:unit`, FE-GATE-005)가 실패한다.
|
- descriptor의 입력·응답 스키마 ID가 스키마 메타데이터에 없으면 `check:registries`가 실패한다.
|
||||||
- 비교하는 것: operation 목록, method, path, 성공 상태, 응답 한도, 인증 프로필, 재시도 의미, 쓰기 의미, 요청 본문, 스키마 ID.
|
- 메시지: `FE-REG-API.<operationId>.requestSchema references unknown FE-REG-SCHEMA.schemaId=<id>` (`responseSchema`도 같다)
|
||||||
- 마감 시간은 비교하지 않는다. V2 `timeoutMs`는 `null`이다.
|
- 인증 프로필 이름이 틀리면 계약 조립이 거부해 operation을 적재하는 모든 게이트가 실패한다.
|
||||||
- V2 입력 칸이 틀리면 모듈 로드 때 operation ID를 말하며 실패한다.
|
- 오류의 `reason`: `<featureId>/<operationId>: unknown authProfileId <id>`
|
||||||
- `pathParameterNames`가 `path`의 이름과 다름: `REST path codec does not match its template: <operationId>`
|
- 스키마 ID나 operation ID가 겹치면 적재 때 그 ID를 말하며 실패한다.
|
||||||
- `pathSchema`가 비었거나 `maxEncodedSearchBytes`가 범위 밖: `Invalid REST operation contract: <operationId>`
|
- 예: `Invalid or duplicate schema definition: <schemaId>`, 계약 조립 `duplicate operation: <operationId>`
|
||||||
- `pathSchema`·`requestSchema`·`responseSchema`가 등록되지 않은 스키마: `Unresolved API schema binding: <operationId>`
|
|
||||||
- 인증 프로필 이름이 틀리면 operation을 적재하는 모든 게이트가 실패한다.
|
|
||||||
- 메시지: `REST security profiles are incoherent for <operationId>: unknown authProfileId <id>.`
|
|
||||||
- 스키마·mapper·operation ID가 겹치면 모듈 로드 때 그 ID를 말하며 실패한다.
|
|
||||||
- 예: `Invalid or duplicate schema definition: <schemaId>`
|
|
||||||
- `TEMPLATE_FIXTURE` 출처를 참조 기능 밖에서 쓰면 계약 조립이 거부한다.
|
- `TEMPLATE_FIXTURE` 출처를 참조 기능 밖에서 쓰면 계약 조립이 거부한다.
|
||||||
- 오류의 `reason`: `<id>: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to reference-feature only; pin an EXTERNAL_PACKAGE`
|
- 오류의 `reason`: `<id>: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to reference-feature only; pin an EXTERNAL_PACKAGE`
|
||||||
- zod를 직접 import하면 `check:architecture`가 `zod-is-reached-through-contracts-zod`로 막는다.
|
- zod를 직접 import하면 `check:architecture`가 `zod-is-reached-through-contracts-zod`로 막는다.
|
||||||
@@ -364,7 +351,7 @@ NOTICE_GET_ITEM: defineRestOperation({
|
|||||||
- operation ID·route ID·입력 타입을 틀리면 `check:types`가 막는다. 음성 fixture: `check:types:fixture:http-operation-id`, `check:types:fixture:http-route-id`, `check:types:fixture:http-operation-input`.
|
- operation ID·route ID·입력 타입을 틀리면 `check:types`가 막는다. 음성 fixture: `check:types:fixture:http-operation-id`, `check:types:fixture:http-route-id`, `check:types:fixture:http-operation-input`.
|
||||||
- 호스트가 주지 않는 capability를 `needs`에 적으면 조립이 실패한다.
|
- 호스트가 주지 않는 capability를 `needs`에 적으면 조립이 실패한다.
|
||||||
- 메시지: `feature <id> needs <capability>, which the host did not provide`
|
- 메시지: `feature <id> needs <capability>, which the host did not provide`
|
||||||
- V2 operation을 선언하고 기능 `adapters/`·`application/`에서 쓰지 않으면 `check:registries`(FE-GATE-010)가 실패한다.
|
- operation을 계약에 두고 기능 `adapters/`·`application/`에서 쓰지 않으면 `check:registries`(FE-GATE-010)가 실패한다.
|
||||||
- 메시지: `FE-REG-API.<operationId> has no executable consumer for operationId=<operationId>`
|
- 메시지: `FE-REG-API.<operationId> has no executable consumer for operationId=<operationId>`
|
||||||
- **못 잡음**: `routeId`가 실제로 요청을 보내는 화면과 다른 것. 타입은 기능의 route ID인지만 본다.
|
- **못 잡음**: `routeId`가 실제로 요청을 보내는 화면과 다른 것. 타입은 기능의 route ID인지만 본다.
|
||||||
- **못 잡음**: 기능 `contracts/`나 다섯 폴더 밖에 새로 만든 폴더(예: `hooks/`)를 거쳐 `src/adapters`에 닿는 import. `.dependency-cruiser.json`에 그 경로를 막는 규칙이 없다. 기능 안에는 `domain/`, `application/`, `contracts/`, `adapters/`, `presentation/` 다섯 폴더만 둔다.
|
- **못 잡음**: 기능 `contracts/`나 다섯 폴더 밖에 새로 만든 폴더(예: `hooks/`)를 거쳐 `src/adapters`에 닿는 import. `.dependency-cruiser.json`에 그 경로를 막는 규칙이 없다. 기능 안에는 `domain/`, `application/`, `contracts/`, `adapters/`, `presentation/` 다섯 폴더만 둔다.
|
||||||
|
|||||||
@@ -88,8 +88,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
|||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 |
|
| 서버 보장 | 멱등 키(`Idempotency-Key` 헤더)로 같은 요청의 중복 적용을 막는다 | 같은 요청을 여러 번 적용해도 결과가 같다 (키 없이) | 중복을 막지 못한다 |
|
||||||
| 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다 | 된다 | 하지 않는다 |
|
| 자동 재시도 | 실제로 보내기 전까지만. 보낸 뒤 결과를 모르면 결과 불명(4절)으로 넘긴다 | 된다 | 하지 않는다 |
|
||||||
| V3 | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 참조 기능은 `retryBudget: 0` | — | `retryBudget: 0` 필수 |
|
| descriptor | `commandRecovery: { mode: "IDEMPOTENCY_REPLAY", operationIdentityField }` 필수. 참조 기능은 `retryBudget: 0` | — | `retryBudget: 0` 필수 |
|
||||||
| V2 `replayPolicy` | `KEYED_COMMAND` | `IDEMPOTENT` | `NON_REPLAYABLE` |
|
|
||||||
| 뮤테이션 정책 | `requiresIdempotencyKey: true` | — | — |
|
| 뮤테이션 정책 | `requiresIdempotencyKey: true` | — | — |
|
||||||
|
|
||||||
- 멱등 키: 서버가 "같은 쓰기 요청"을 알아보게 하는 값이다.
|
- 멱등 키: 서버가 "같은 쓰기 요청"을 알아보게 하는 값이다.
|
||||||
@@ -99,13 +98,12 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
|||||||
|
|
||||||
**정본**: 백엔드가 멱등 키 요청에 어떻게 답하는지는 `clean-architecture-backend-template/docs/web/http-contract.md` §2(멱등성 응답)다. 여기에 표를 옮기지 않는다.
|
**정본**: 백엔드가 멱등 키 요청에 어떻게 답하는지는 `clean-architecture-backend-template/docs/web/http-contract.md` §2(멱등성 응답)다. 여기에 표를 옮기지 않는다.
|
||||||
|
|
||||||
**어디에 적나**: `contracts/<base>-contract-contribution.ts`의 `retrySemantics`, `commandRecovery`, `frontend.retryBudget`. 같은 의미를 `contracts/<base>-api-contract.ts`의 `replayPolicy`, `idempotency`, `idempotencyKeyPolicy`에도 적는다.
|
**어디에 적나**: `contracts/<base>-contract-contribution.ts`의 `retrySemantics`, `commandRecovery`, `frontend.retryBudget`. 다른 파일에 다시 적지 않는다.
|
||||||
|
|
||||||
**틀리면**
|
**틀리면**
|
||||||
|
|
||||||
- `NEVER`에 `retryBudget`을 0보다 크게 주면 계약 조립이 `retry budget contradicts NEVER retry semantics`로 거부한다.
|
- `NEVER`에 `retryBudget`을 0보다 크게 주면 계약 조립이 `retry budget contradicts NEVER retry semantics`로 거부한다.
|
||||||
- `KEYED`에 `commandRecovery`가 없으면 `KEYED commands require a recovery descriptor`로 거부한다.
|
- `KEYED`에 `commandRecovery`가 없으면 `KEYED commands require a recovery descriptor`로 거부한다.
|
||||||
- V2와 V3의 재시도 의미가 다르면 `tests/unit/http-operation-v2-v3-parity.test.ts`가 실패한다.
|
|
||||||
- 서버 보장과 다른 의미를 고른 것은 검사가 잡지 못한다.
|
- 서버 보장과 다른 의미를 고른 것은 검사가 잡지 못한다.
|
||||||
|
|
||||||
근거: `scale-architecture.md` §13(재시도 모델).
|
근거: `scale-architecture.md` §13(재시도 모델).
|
||||||
@@ -141,7 +139,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
|||||||
- 같은 status라도 code로 나뉠 수 있다. 예: 409 중 "처리 중"은 `MAYBE_APPLIED`여야 한다. `NOT_APPLIED`로 보면 다음 저장이 새 키를 만들어 같은 작업이 두 번 적용된다.
|
- 같은 status라도 code로 나뉠 수 있다. 예: 409 중 "처리 중"은 `MAYBE_APPLIED`여야 한다. `NOT_APPLIED`로 보면 다음 저장이 새 키를 만들어 같은 작업이 두 번 적용된다.
|
||||||
- 401·403·429는 문제 응답 본문을 읽기 전에 status로 나뉜다. 서버가 상태를 안 바꾼다고 보장하면 `classifyStatus`로 `NOT_APPLIED`를 돌려준다. 없으면 `MAYBE_APPLIED`다.
|
- 401·403·429는 문제 응답 본문을 읽기 전에 status로 나뉜다. 서버가 상태를 안 바꾼다고 보장하면 `classifyStatus`로 `NOT_APPLIED`를 돌려준다. 없으면 `MAYBE_APPLIED`다.
|
||||||
- 문제 응답 본문이 기능의 problem 스키마를 통과하지 못하면 `classifyProblem`을 부르지 않는다. 쓰기는 `MAYBE_APPLIED`가 된다(`src/adapters/http/http-execution-v3.ts`).
|
- 문제 응답 본문이 기능의 problem 스키마를 통과하지 못하면 `classifyProblem`을 부르지 않는다. 쓰기는 `MAYBE_APPLIED`가 된다(`src/adapters/http/http-execution-v3.ts`).
|
||||||
- `responseEnvelope: "ENVELOPE_V1"`인 operation은 400·409·422와 503 `IDEMPOTENCY_UNAVAILABLE`의 판정을 실행기가 백엔드 기준 표로 정한다(`src/adapters/http/backend-envelope.ts`의 `REFUSED_BEFORE_WRITE`). 표의 근거는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절이다(백엔드 코드에서 code마다 쓰기 전·후를 읽은 결과). `classifyProblem`은 그 밖의 status만 받고, 다르게 답해도 표의 판정은 바뀌지 않는다. V2 클라이언트도 같은 표를 쓴다.
|
- `responseEnvelope: "ENVELOPE_V1"`인 operation은 400·409·422와 503 `IDEMPOTENCY_UNAVAILABLE`의 판정을 실행기가 백엔드 기준 표로 정한다(`src/adapters/http/backend-envelope.ts`의 `REFUSED_BEFORE_WRITE`). 표의 근거는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절이다(백엔드 코드에서 code마다 쓰기 전·후를 읽은 결과). `classifyProblem`은 그 밖의 status만 받고, 다르게 답해도 표의 판정은 바뀌지 않는다.
|
||||||
- `NOT_APPLIED`(쓰기 전 거절): 400 `VALIDATION_FAILED`(details 모양과 상관없음), 400 `IDEMPOTENCY_KEY_INVALID`, 422 `IDEMPOTENT_REQUEST_MISMATCH`
|
- `NOT_APPLIED`(쓰기 전 거절): 400 `VALIDATION_FAILED`(details 모양과 상관없음), 400 `IDEMPOTENCY_KEY_INVALID`, 422 `IDEMPOTENT_REQUEST_MISMATCH`
|
||||||
- `MAYBE_APPLIED`: 그 밖의 400·409·422. 409 `IDEMPOTENT_IN_FLIGHT`, `BAD_PARAMETER`, 도메인 code, fileserver의 422가 여기 든다. 그리고 503 `IDEMPOTENCY_UNAVAILABLE`
|
- `MAYBE_APPLIED`: 그 밖의 400·409·422. 409 `IDEMPOTENT_IN_FLIGHT`, `BAD_PARAMETER`, 도메인 code, fileserver의 422가 여기 든다. 그리고 503 `IDEMPOTENCY_UNAVAILABLE`
|
||||||
- 짝 백엔드가 쓰기 전에 거절하는 code를 새로 만들면 계약 문서 6.1절과 이 표를 함께 고친다. 표에 없으면 `MAYBE_APPLIED`다
|
- 짝 백엔드가 쓰기 전에 거절하는 code를 새로 만들면 계약 문서 6.1절과 이 표를 함께 고친다. 표에 없으면 `MAYBE_APPLIED`다
|
||||||
@@ -161,7 +159,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
|||||||
→ 결과 불명 화면 → "같은 요청으로 다시 보내기"가 같은 키로 보낸다
|
→ 결과 불명 화면 → "같은 요청으로 다시 보내기"가 같은 키로 보낸다
|
||||||
```
|
```
|
||||||
|
|
||||||
- V2 클라이언트(레거시)도 같다. V2와 V3 Envelope 경로가 같은 표(`src/adapters/http/backend-envelope.ts`)를 읽는다. V2는 `NOT_APPLIED`만 싣고 503은 effect 없이 돌아온다. 뮤테이션 조정자가 그것을 `MAYBE_APPLIED`로 본다(`src/presentation/adapters/query/application-query.ts`의 `mutationFailureWithEffect`).
|
- 뮤테이션 조정자는 effect가 없는 실패도 `MAYBE_APPLIED`로 본다(`src/presentation/adapters/query/application-query.ts`의 `mutationFailureWithEffect`).
|
||||||
- 판정: 맞는다. 지금 동작은 `MAYBE_APPLIED`이고 재전송은 같은 키다. 백엔드가 요구하는 행동과 같다.
|
- 판정: 맞는다. 지금 동작은 `MAYBE_APPLIED`이고 재전송은 같은 키다. 백엔드가 요구하는 행동과 같다.
|
||||||
- 다른 점은 화면뿐이다. 서버는 "실행 안 함"이라고 답했지만 화면은 "결과를 모른다"로 보여 준다.
|
- 다른 점은 화면뿐이다. 서버는 "실행 안 함"이라고 답했지만 화면은 "결과를 모른다"로 보여 준다.
|
||||||
- `NOT_APPLIED`로 바꾸면 다음 저장이 새 키를 만든다. 키를 다시 쓰는 것은 결과 불명으로 남은 요청뿐이다(같은 파일). 백엔드가 말한 "같은 키"와 어긋난다.
|
- `NOT_APPLIED`로 바꾸면 다음 저장이 새 키를 만든다. 키를 다시 쓰는 것은 결과 불명으로 남은 요청뿐이다(같은 파일). 백엔드가 말한 "같은 키"와 어긋난다.
|
||||||
@@ -188,16 +186,15 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
|
|||||||
| 언제 | 로그인 없이 부르는 API | 세션 토큰을 `authorization` 헤더로 보내는 API. 생성된 뼈대가 이것이다 | 위 둘로 안 되는 경우(쿠키 세션, 별도 토큰 등) |
|
| 언제 | 로그인 없이 부르는 API | 세션 토큰을 `authorization` 헤더로 보내는 API. 생성된 뼈대가 이것이다 | 위 둘로 안 되는 경우(쿠키 세션, 별도 토큰 등) |
|
||||||
| 정의 | `src/contracts/rest-profiles.ts` (템플릿 소유) | 같은 파일 | `src/contracts/product-contracts.ts`의 `PRODUCT_REST_AUTH_PROFILES` (제품 소유) |
|
| 정의 | `src/contracts/rest-profiles.ts` (템플릿 소유) | 같은 파일 | `src/contracts/product-contracts.ts`의 `PRODUCT_REST_AUTH_PROFILES` (제품 소유) |
|
||||||
| 자격 증명 | 없음 | 템플릿 세션 | `src/bootstrap/product-composition.ts`의 `credentialProviders` |
|
| 자격 증명 | 없음 | 템플릿 세션 | `src/bootstrap/product-composition.ts`의 `credentialProviders` |
|
||||||
| V2 `auth` | `none` | `external-session` | 프로필에 맞게 |
|
|
||||||
| 라우트 `access` | 보통 `public` | 보통 `session-required` | 프로필에 맞게 |
|
| 라우트 `access` | 보통 `public` | 보통 `session-required` | 프로필에 맞게 |
|
||||||
|
|
||||||
- `REFERENCE_EXTERNAL_BEARER`는 `EXTERNAL_BEARER`의 옛 이름이다. `@deprecated`이고 한 릴리스 뒤 지운다. 새 코드는 쓰지 않는다.
|
- `REFERENCE_EXTERNAL_BEARER`는 `EXTERNAL_BEARER`의 옛 이름이다. `@deprecated`이고 한 릴리스 뒤 지운다. 새 코드는 쓰지 않는다.
|
||||||
- 제품 프로필 ID는 템플릿 프로필 ID와 겹치면 안 된다.
|
- 제품 프로필 ID는 템플릿 프로필 ID와 겹치면 안 된다.
|
||||||
- CSRF 프로필은 템플릿 상수(`REST_CSRF_PROFILES`)뿐이다. 제품이 더할 자리는 없다. 쿠키 인증은 인증 프로필의 헤더 집합으로 표현한다. 예제: `tests/unit/product-composition-fixture.test.ts`.
|
- 쿠키 인증과 CSRF 헤더는 인증 프로필의 헤더 집합으로 표현한다. 예제: `tests/unit/product-composition-fixture.test.ts`.
|
||||||
|
|
||||||
**기준**: 백엔드가 그 API에 요구하는 인증을 따른다. 새 프로필은 템플릿 파일이 아니라 제품 소유 파일 두 곳에만 더한다.
|
**기준**: 백엔드가 그 API에 요구하는 인증을 따른다. 새 프로필은 템플릿 파일이 아니라 제품 소유 파일 두 곳에만 더한다.
|
||||||
|
|
||||||
**어디에 적나**: V3 `frontend.authProfileId`와 V2 `authProfileId`(같은 값), V2 `auth`, 라우트 `access`.
|
**어디에 적나**: descriptor의 `frontend.authProfileId`, 라우트 `access`.
|
||||||
|
|
||||||
**틀리면**
|
**틀리면**
|
||||||
|
|
||||||
|
|||||||
@@ -43,9 +43,9 @@ corepack pnpm create:feature <id> [--context <context id>] [--package @scope/nam
|
|||||||
- `context-routes.ts`: context가 적재하는 라우트
|
- `context-routes.ts`: context가 적재하는 라우트
|
||||||
- `contracts/<base>-feature-contract.ts`: 라우트, 무효화, 계약 패키지 신원
|
- `contracts/<base>-feature-contract.ts`: 라우트, 무효화, 계약 패키지 신원
|
||||||
- `contracts/<base>-schemas.ts`: zod 스키마와 `zodValidator` 검증기
|
- `contracts/<base>-schemas.ts`: zod 스키마와 `zodValidator` 검증기
|
||||||
- `contracts/<base>-mapper.ts`: 와이어 값 → 화면 값, 레지스트리 mapper
|
- `contracts/<base>-mapper.ts`: 와이어 값 → 화면 값
|
||||||
- `contracts/<base>-api-contract.ts`: V2 행
|
- `contracts/<base>-schema-metadata.ts`: 스키마 메타데이터(FE-REG-SCHEMA 행)
|
||||||
- `contracts/<base>-contract-contribution.ts`: V3 descriptor와 계약 기여
|
- `contracts/<base>-contract-contribution.ts`: HTTP descriptor와 계약 기여. FE-REG-API 행은 여기서 뽑는다
|
||||||
- `contracts/<base>-message-catalog.ts`: ko-KR·en-US 문구
|
- `contracts/<base>-message-catalog.ts`: ko-KR·en-US 문구
|
||||||
- `application/<base>-feature-api.ts`: input, gateway port, `ApplicationFeatureInputs` 보강
|
- `application/<base>-feature-api.ts`: input, gateway port, `ApplicationFeatureInputs` 보강
|
||||||
- `adapters/<base>-http-gateway.ts`: HTTP gateway
|
- `adapters/<base>-http-gateway.ts`: HTTP gateway
|
||||||
|
|||||||
@@ -71,23 +71,16 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
|
|||||||
|
|
||||||
| 메시지 | 원인 | 고칠 곳 |
|
| 메시지 | 원인 | 고칠 곳 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `REST security profiles are incoherent for <operationId>: unknown authProfileId <id>.` | 없는 인증 프로필 | `contracts/<base>-api-contract.ts`의 `authProfileId`. 제품 프로필이면 `src/contracts/product-contracts.ts` |
|
| `<featureId>/<operationId>: unknown authProfileId <id>` (계약 조립 오류의 `reason`) | 없는 인증 프로필 | `contracts/<base>-contract-contribution.ts`의 `frontend.authProfileId`. 제품 프로필이면 `src/contracts/product-contracts.ts` |
|
||||||
| `REST security profiles are incoherent for <operationId>: unknown csrfProfileId <id>.` | 없는 CSRF 프로필. 템플릿에는 `NO_CSRF_BEARER`뿐 | `contracts/<base>-api-contract.ts`의 `csrfProfileId` |
|
|
||||||
| `REST security profiles are incoherent for <operationId>: auth "none" needs an ANONYMOUS profile, <id> is <transport>.` | V2 `auth: "none"`인데 인증 프로필을 썼다 | V2 `auth` 또는 `authProfileId` |
|
|
||||||
| `REST security profiles are incoherent for <operationId>: auth "external-session" cannot use the ANONYMOUS profile <id>.` | 로그인 API에 `ANONYMOUS` | V2 `auth` 또는 `authProfileId` |
|
|
||||||
| `Product REST auth profile <id> reuses a template profile id.` | 제품 프로필 ID가 템플릿 것과 같다 | `src/contracts/product-contracts.ts` |
|
| `Product REST auth profile <id> reuses a template profile id.` | 제품 프로필 ID가 템플릿 것과 같다 | `src/contracts/product-contracts.ts` |
|
||||||
|
|
||||||
### 계약·스키마·mapper
|
### 계약·스키마·mapper
|
||||||
|
|
||||||
| 메시지 | 원인 | 고칠 곳 |
|
| 메시지 | 원인 | 고칠 곳 |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `Invalid or duplicate schema definition: <schemaId>` | 스키마 ID 중복 또는 메타 형식 | `contracts/<base>-api-contract.ts`의 `schemas`. 접두어를 붙인다 |
|
| `Invalid or duplicate schema definition: <schemaId>` | 스키마 ID 중복 또는 메타 형식 | `contracts/<base>-schema-metadata.ts`. 접두어를 붙인다 |
|
||||||
| `Invalid or duplicate runtime schema codec: <schemaId>` | 런타임 codec ID 중복 | `contracts/<base>-schemas.ts` |
|
| `duplicate operation: <operationId>` (계약 조립 오류의 `reason`) | operation ID 중복 | `contracts/<base>-contract-contribution.ts`. 접두어를 붙인다 |
|
||||||
| `Invalid or duplicate boundary mapper: <mapperId>` | mapper ID 중복 또는 형식 | `contracts/<base>-mapper.ts` |
|
| `FE-REG-API.<operationId>.requestSchema references unknown FE-REG-SCHEMA.schemaId=<id>` | descriptor의 입력 스키마 ID가 스키마 메타데이터에 없다 (`responseSchema`도 같은 꼴) | `contracts/<base>-schema-metadata.ts` |
|
||||||
| `Duplicate API operation: <operationId>` | V2 operation ID 중복 | `contracts/<base>-api-contract.ts` |
|
|
||||||
| `REST path codec does not match its template: <operationId>` | V2 `pathParameterNames`가 `path`의 `{이름}`과 다르다 | `contracts/<base>-api-contract.ts` ([01 문서 3단계](../01-add-a-feature.md#3단계-api-계약) "V2 행의 입력 칸") |
|
|
||||||
| `Invalid REST operation contract: <operationId>` | V2 행 형식. 예: 빈 `pathSchema`, `maxEncodedSearchBytes`가 0~32,768 밖 | 같은 곳 |
|
|
||||||
| `Unresolved API schema binding: <operationId>` | V2 `pathSchema`·`requestSchema`·`responseSchema`가 등록되지 않은 스키마 | 같은 파일의 `schemas`, `contracts/<base>-schemas.ts`의 codec |
|
|
||||||
| `Unregistered route codec: <codecId>` | URL 함수가 기능 codec을 `buildRouteUrl`에 넘기지 않았다 | `presentation/<base>-routes.ts` |
|
| `Unregistered route codec: <codecId>` | URL 함수가 기능 codec을 `buildRouteUrl`에 넘기지 않았다 | `presentation/<base>-routes.ts` |
|
||||||
| `contract package <packageId> is declared, but no loaded contribution pins it` | 계약 `contractPackages`에 적은 패키지를 계약 기여가 쓰지 않는다 | `contracts/<base>-contract-contribution.ts`의 `source` |
|
| `contract package <packageId> is declared, but no loaded contribution pins it` | 계약 `contractPackages`에 적은 패키지를 계약 기여가 쓰지 않는다 | `contracts/<base>-contract-contribution.ts`의 `source` |
|
||||||
| `<id> contributes contract package <packageId>, which no installed feature declares in contracts.contractPackages` | 계약 기여의 신원과 계약 선언의 신원이 다르다 | 둘 다 `<BASE>_CONTRACT_PACKAGE` 하나를 쓰게 한다 |
|
| `<id> contributes contract package <packageId>, which no installed feature declares in contracts.contractPackages` | 계약 기여의 신원과 계약 선언의 신원이 다르다 | 둘 다 `<BASE>_CONTRACT_PACKAGE` 하나를 쓰게 한다 |
|
||||||
@@ -149,7 +142,7 @@ lint / check:architecture / check:i18n → FE-GATE-002, FE-GATE-010
|
|||||||
| `FE-REG-ROUTE.<ROUTE_ID>.loadingSurface value <value> does not match <pattern>` | 로딩 화면 이름이 케밥 표기가 아니다 | 계약 `routes.*.loadingSurface` |
|
| `FE-REG-ROUTE.<ROUTE_ID>.loadingSurface value <value> does not match <pattern>` | 로딩 화면 이름이 케밥 표기가 아니다 | 계약 `routes.*.loadingSurface` |
|
||||||
| `FE-REG-ROUTE.<ROUTE_ID>.<field> has unknown value <value>` | `access`·`errorSurface`가 정해진 값이 아니다 | 계약 `routes` |
|
| `FE-REG-ROUTE.<ROUTE_ID>.<field> has unknown value <value>` | `access`·`errorSurface`가 정해진 값이 아니다 | 계약 `routes` |
|
||||||
| `FE-REG-ROUTE.<ROUTE_ID>.paramsSchema references unknown FE-REG-SCHEMA.schemaId=<id>` | 라우트 스키마 ID를 기능이 등록하지 않았다 (`searchSchema`도 같은 꼴) | 계약 스키마 메타 |
|
| `FE-REG-ROUTE.<ROUTE_ID>.paramsSchema references unknown FE-REG-SCHEMA.schemaId=<id>` | 라우트 스키마 ID를 기능이 등록하지 않았다 (`searchSchema`도 같은 꼴) | 계약 스키마 메타 |
|
||||||
| `FE-REG-API.<operationId> has no executable consumer for operationId=<operationId>` | V2 operation을 기능 `adapters/`·`application/`에서 쓰지 않는다 | 쓰지 않으면 V2 행을 지운다 |
|
| `FE-REG-API.<operationId> has no executable consumer for operationId=<operationId>` | 계약의 operation을 기능 `adapters/`·`application/`에서 쓰지 않는다 | 쓰지 않으면 descriptor를 지운다 |
|
||||||
| `breaking change missing evidence: <changeId>` | 행을 빼거나 바꿨는데 승인이 없다 | `update:registry-baseline` 또는 `config/contracts/registry-change-evidence.json` |
|
| `breaking change missing evidence: <changeId>` | 행을 빼거나 바꿨는데 승인이 없다 | `update:registry-baseline` 또는 `config/contracts/registry-change-evidence.json` |
|
||||||
| `stale breaking evidence <changeId>: no breaking change in the current diff has this changeId. ...` | 지금 diff와 맞지 않는 증거 행 | 그 행을 지운다 |
|
| `stale breaking evidence <changeId>: no breaking change in the current diff has this changeId. ...` | 지금 diff와 맞지 않는 증거 행 | 그 행을 지운다 |
|
||||||
| `registry baseline approval digest mismatch: approved=<digest> actual=<digest>` | 기준선 파일을 손으로 고쳤다 | `update:registry-baseline`으로 다시 찍는다 |
|
| `registry baseline approval digest mismatch: approved=<digest> actual=<digest>` | 기준선 파일을 손으로 고쳤다 | `update:registry-baseline`으로 다시 찍는다 |
|
||||||
|
|||||||
@@ -24,20 +24,19 @@
|
|||||||
| `chunkId` | 계약 `routes` | `route-invoice-list` | `check:registries` (`duplicates chunkId=`) |
|
| `chunkId` | 계약 `routes` | `route-invoice-list` | `check:registries` (`duplicates chunkId=`) |
|
||||||
| `moduleId` | `routeRuntimeContracts`, 지연 페이지 표 | `invoice-list-page` | `check:registries` (FE-REG-ROUTE-RUNTIME) |
|
| `moduleId` | `routeRuntimeContracts`, 지연 페이지 표 | `invoice-list-page` | `check:registries` (FE-REG-ROUTE-RUNTIME) |
|
||||||
| `loadingSurface` | 계약 `routes` | `invoice-list` | 검사 없음 (형식만 본다) |
|
| `loadingSurface` | 계약 `routes` | `invoice-list` | 검사 없음 (형식만 본다) |
|
||||||
| operation ID | V2 행, V3 descriptor, gateway | `INVOICE_LIST_ITEMS` | 모듈 로드 (`Duplicate API operation`), 계약 조립 (`duplicate operation`) |
|
| operation ID | descriptor, gateway | `INVOICE_LIST_ITEMS` | 계약 조립 (`duplicate operation`) |
|
||||||
| API 경로 | V2 `path`, V3 `pathTemplate` | `/api/invoice-items` | 검사 없음. 백엔드 계약을 따른다 |
|
| API 경로 | descriptor `pathTemplate` | `/api/invoice-items` | 검사 없음. 백엔드 계약을 따른다 |
|
||||||
| 스키마 ID | V2 스키마 메타, zod 검증기, codec | `InvoiceNoRequest`, `InvoiceItemListPayload`, `InvoiceProblem` | 모듈 로드 (`Invalid or duplicate schema definition`) |
|
| 스키마 ID | 스키마 메타데이터, zod 검증기 | `InvoiceNoRequest`, `InvoiceItemListPayload`, `InvoiceProblem` | 모듈 로드 (`Invalid or duplicate schema definition`) |
|
||||||
| mapper ID | V2 `mapperId`, 레지스트리 mapper | `InvoiceItemListMapper` | 모듈 로드 (`Invalid or duplicate boundary mapper`) |
|
|
||||||
| `contributionId` | 계약 기여 | `invoice-feature-http-v1` | 계약 조립 (`duplicate contributionId`) |
|
| `contributionId` | 계약 기여 | `invoice-feature-http-v1` | 계약 조립 (`duplicate contributionId`) |
|
||||||
| `policyId` | V3 `frontend` | `INVOICE_LIST_V1` | 검사 없음 |
|
| `policyId` | descriptor `frontend` | `INVOICE_LIST_V1` | 검사 없음 |
|
||||||
| `diagnosticsOperation` | V3 `frontend` | `invoice.list` | 검사 없음 |
|
| `diagnosticsOperation` | descriptor `frontend` | `invoice.list` | 검사 없음 |
|
||||||
| 쿼리 namespace | 계약 `invalidation.namespaces`, 쿼리 바인딩 | `invoice-item` (버전 1) | 조립 (`Duplicate invalidation namespace`) |
|
| 쿼리 namespace | 계약 `invalidation.namespaces`, 쿼리 바인딩 | `invoice-item` (버전 1) | 조립 (`Duplicate invalidation namespace`) |
|
||||||
| 무효화 topic | 계약 `invalidation.topics`, 뮤테이션 `invalidate` | `qinv.` + 무작위 26자 | 생성 명령이 설치된 topic과 비교, 조립 (`Duplicate invalidation topic`) |
|
| 무효화 topic | 계약 `invalidation.topics`, 뮤테이션 `invalidate` | `qinv.` + 무작위 26자 | 생성 명령이 설치된 topic과 비교, 조립 (`Duplicate invalidation topic`) |
|
||||||
| 쿼리·뮤테이션 `definitionId` | 쿼리 바인딩 | `invoice-item-list-v1` | 검사 없음 |
|
| 쿼리·뮤테이션 `definitionId` | 쿼리 바인딩 | `invoice-item-list-v1` | 검사 없음 |
|
||||||
| 문구 키 | 기능 문구 catalog | `route.INVOICE_LIST.title`, `invoice.list.title` 등 | 생성 명령, 조립 (`Duplicate ko-KR message key`) |
|
| 문구 키 | 기능 문구 catalog | `route.INVOICE_LIST.title`, `invoice.list.title` 등 | 생성 명령, 조립 (`Duplicate ko-KR message key`) |
|
||||||
| telemetry `kind` | application input | `invoice.list.failed` | 검사 없음 |
|
| telemetry `kind` | application input | `invoice.list.failed` | 검사 없음 |
|
||||||
| `owner` | V2 행, 스키마 메타, mapper | `feature-frontend-invoice-feature` | 검사 없음 |
|
| `owner` | 스키마 메타데이터 | `feature-frontend-invoice-feature` | 검사 없음 |
|
||||||
| 인증 프로필 ID | V2·V3 `authProfileId` | `EXTERNAL_BEARER` (템플릿 것을 씀) | 제품 프로필이 템플릿 ID를 쓰면 모듈 로드 (`reuses a template profile id`) |
|
| 인증 프로필 ID | descriptor `frontend.authProfileId` | `EXTERNAL_BEARER` (템플릿 것을 씀) | 제품 프로필이 템플릿 ID를 쓰면 모듈 로드 (`reuses a template profile id`) |
|
||||||
| `navigationOrder` | 계약 `routes` | 설치된 최댓값 + 10 | 검사 없음. 같은 숫자가 둘이어도 통과 |
|
| `navigationOrder` | 계약 `routes` | 설치된 최댓값 + 10 | 검사 없음. 같은 숫자가 둘이어도 통과 |
|
||||||
|
|
||||||
메시지 전체와 고칠 파일은 [errors.md](errors.md)에 있다.
|
메시지 전체와 고칠 파일은 [errors.md](errors.md)에 있다.
|
||||||
|
|||||||
@@ -77,12 +77,12 @@ const search = (q: string) =>
|
|||||||
|
|
||||||
| 패턴 | 정의 | 예제 | 검사 |
|
| 패턴 | 정의 | 예제 | 검사 |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| V2 operation 행 | `src/contracts/api-operations.ts`의 `defineRestOperation` | 생성 뼈대 `contracts/<base>-api-contract.ts` | `check:registries` (FE-REG-API) |
|
| HTTP 계약 | `src/contracts/external-contract-runtime.ts` | 생성 뼈대 `contracts/<base>-contract-contribution.ts` | 계약 조립, `check:registries` (FE-REG-API 행은 `src/contracts/api-operations.ts`의 `projectApiOperationRows`가 뽑는다) |
|
||||||
| V3 HTTP 계약(실행) | `src/contracts/external-contract-runtime.ts` | 생성 뼈대 `contracts/<base>-contract-contribution.ts` | 계약 조립, V2/V3 일치 테스트 |
|
| 스키마 메타데이터 | `src/contracts/schema-registry.ts`의 `SchemaDefinition` | 생성 뼈대 `contracts/<base>-schema-metadata.ts` | `check:registries` (FE-REG-SCHEMA) |
|
||||||
| 배포된 계약 패키지 출처 | 같은 파일의 `EXTERNAL_PACKAGE` | 생성 뼈대(자리표시자 또는 `--package` 신원). 실제 `@org-contracts/*` 패키지를 import하는 예제는 없음 | 계약 조립(신원 형식), 릴리스 승인(자리표시자) |
|
| 배포된 계약 패키지 출처 | 같은 파일의 `EXTERNAL_PACKAGE` | 생성 뼈대(자리표시자 또는 `--package` 신원). 실제 `@org-contracts/*` 패키지를 import하는 예제는 없음 | 계약 조립(신원 형식), 릴리스 승인(자리표시자) |
|
||||||
| 런타임 검증기 | `src/contracts/zod-validator.ts`의 `zodValidator` | 생성 뼈대 `contracts/<base>-schemas.ts` | 스키마 ID 중복 |
|
| 런타임 검증기 | `src/contracts/zod-validator.ts`의 `zodValidator` | 생성 뼈대 `contracts/<base>-schemas.ts` | 스키마 ID 중복 |
|
||||||
| 검증 생략 | `src/contracts/unvalidated-payload.ts`의 `unvalidatedPayload` | 없음 (기능 예제) | 이유가 비면 throw, `listUnvalidatedPayloads`가 목록을 보임 |
|
| 검증 생략 | `src/contracts/unvalidated-payload.ts`의 `unvalidatedPayload` | 없음 (기능 예제) | 이유가 비면 throw, `listUnvalidatedPayloads`가 목록을 보임 |
|
||||||
| DTO → 화면 값 mapper | `src/contracts/boundary-mapper.ts` | 생성 뼈대 `contracts/<base>-mapper.ts` | mapper ID 중복 |
|
| DTO → 화면 값 mapper | `src/contracts/boundary-mapper.ts`의 `BoundaryMappingResult` | 생성 뼈대 `contracts/<base>-mapper.ts` | 타입 검사 |
|
||||||
| gateway port + HTTP 어댑터 | `src/adapters/http/index.ts`의 `createFeatureHttpBinding`, `defineFeatureHttpOperationForRoutes` | 생성 뼈대 `adapters/<base>-http-gateway.ts` | 음성 타입 fixture (operation ID, route ID, 입력) |
|
| gateway port + HTTP 어댑터 | `src/adapters/http/index.ts`의 `createFeatureHttpBinding`, `defineFeatureHttpOperationForRoutes` | 생성 뼈대 `adapters/<base>-http-gateway.ts` | 음성 타입 fixture (operation ID, route ID, 입력) |
|
||||||
| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 |
|
| 문제 응답 → 업무 실패 | `mapProblem` (HTTP 바인딩) | 참조 기능 `adapters/reference-http-gateway.ts` (409, 422) | 기능 테스트 |
|
||||||
| 결과와 실패 | `src/contracts/result.ts`, `src/contracts/errors.ts` | 생성 뼈대 `application/<base>-feature-api.ts` | `FailureKind` 닫힌 어휘(타입) |
|
| 결과와 실패 | `src/contracts/result.ts`, `src/contracts/errors.ts` | 생성 뼈대 `application/<base>-feature-api.ts` | `FailureKind` 닫힌 어휘(타입) |
|
||||||
|
|||||||
@@ -157,7 +157,7 @@ V3는 자격증명이 없거나(`UNAUTHENTICATED`), auth owner가 장애거나
|
|||||||
fetch 없이 끝난다(`src/bootstrap/runtime-adapters.ts` `attachCredentials`,
|
fetch 없이 끝난다(`src/bootstrap/runtime-adapters.ts` `attachCredentials`,
|
||||||
`src/adapters/http/http-execution-v3.ts` credential patch 처리). 전송 0회 미인증은
|
`src/adapters/http/http-execution-v3.ts` credential patch 처리). 전송 0회 미인증은
|
||||||
diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그래도 무자격
|
diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그래도 무자격
|
||||||
전송이 보이면 V3가 아닌 경로(V2 client 직접 조합, 외부 SDK)를 먼저 의심한다.
|
전송이 보이면 V3가 아닌 경로(외부 SDK 직접 호출)를 먼저 의심한다.
|
||||||
|
|
||||||
점검:
|
점검:
|
||||||
|
|
||||||
|
|||||||
+34
-112
@@ -277,7 +277,7 @@ export function planFeature(
|
|||||||
[`${feature}/contracts/${base}-feature-contract.ts`, renderFeatureContract(shape)],
|
[`${feature}/contracts/${base}-feature-contract.ts`, renderFeatureContract(shape)],
|
||||||
[`${feature}/contracts/${base}-schemas.ts`, renderSchemas(shape)],
|
[`${feature}/contracts/${base}-schemas.ts`, renderSchemas(shape)],
|
||||||
[`${feature}/contracts/${base}-mapper.ts`, renderMapper(shape)],
|
[`${feature}/contracts/${base}-mapper.ts`, renderMapper(shape)],
|
||||||
[`${feature}/contracts/${base}-api-contract.ts`, renderApiContract(shape)],
|
[`${feature}/contracts/${base}-schema-metadata.ts`, renderSchemaMetadata(shape)],
|
||||||
[
|
[
|
||||||
`${feature}/contracts/${base}-contract-contribution.ts`,
|
`${feature}/contracts/${base}-contract-contribution.ts`,
|
||||||
renderContractContribution(shape),
|
renderContractContribution(shape),
|
||||||
@@ -369,9 +369,9 @@ function renderFeatureRuntime({ names }: Shape): string {
|
|||||||
const { base, upper } = names;
|
const { base, upper } = names;
|
||||||
return `import { defineFeatureRuntime } from "../feature-module.ts";
|
return `import { defineFeatureRuntime } from "../feature-module.ts";
|
||||||
import { ${upper}_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-${base}-feature-input.ts";
|
import { ${upper}_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-${base}-feature-input.ts";
|
||||||
import { ${upper}_API_CONTRACT } from "./contracts/${base}-api-contract.ts";
|
|
||||||
import { ${upper}_CONTRACT_CONTRIBUTION } from "./contracts/${base}-contract-contribution.ts";
|
import { ${upper}_CONTRACT_CONTRIBUTION } from "./contracts/${base}-contract-contribution.ts";
|
||||||
import { ${upper}_FEATURE_ID } from "./contracts/${base}-feature-contract.ts";
|
import { ${upper}_FEATURE_ID } from "./contracts/${base}-feature-contract.ts";
|
||||||
|
import { ${upper}_SCHEMA_METADATA } from "./contracts/${base}-schema-metadata.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The executable half. \`feature-module.ts\` imports this file dynamically, so
|
* The executable half. \`feature-module.ts\` imports this file dynamically, so
|
||||||
@@ -379,7 +379,7 @@ import { ${upper}_FEATURE_ID } from "./contracts/${base}-feature-contract.ts";
|
|||||||
*/
|
*/
|
||||||
export const FEATURE_RUNTIME = defineFeatureRuntime({
|
export const FEATURE_RUNTIME = defineFeatureRuntime({
|
||||||
featureId: ${upper}_FEATURE_ID,
|
featureId: ${upper}_FEATURE_ID,
|
||||||
apiContract: ${upper}_API_CONTRACT,
|
schemas: ${upper}_SCHEMA_METADATA,
|
||||||
adapters: [${upper}_FEATURE_ADAPTER_CONTRIBUTION],
|
adapters: [${upper}_FEATURE_ADAPTER_CONTRIBUTION],
|
||||||
contractContributions: [${upper}_CONTRACT_CONTRIBUTION],
|
contractContributions: [${upper}_CONTRACT_CONTRIBUTION],
|
||||||
} as const);
|
} as const);
|
||||||
@@ -522,8 +522,7 @@ export const ${upper}_FEATURE_CONTRACT = Object.freeze({
|
|||||||
|
|
||||||
function renderSchemas({ names }: Shape): string {
|
function renderSchemas({ names }: Shape): string {
|
||||||
const { camel, pascal, upper } = names;
|
const { camel, pascal, upper } = names;
|
||||||
return `import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
|
return `import { z } from "../../../contracts/zod.ts";
|
||||||
import { z } from "../../../contracts/zod.ts";
|
|
||||||
import { zodValidator } from "../../../contracts/zod-validator.ts";
|
import { zodValidator } from "../../../contracts/zod-validator.ts";
|
||||||
|
|
||||||
/** The GET takes no input. Schema ids are global, so this one is prefixed too. */
|
/** The GET takes no input. Schema ids are global, so this one is prefixed too. */
|
||||||
@@ -564,28 +563,16 @@ export const ${upper}_VALIDATORS = Object.freeze({
|
|||||||
),
|
),
|
||||||
${pascal}Problem: zodValidator("${pascal}Problem", ${camel}ProblemSchema),
|
${pascal}Problem: zodValidator("${pascal}Problem", ${camel}ProblemSchema),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const ${upper}_RUNTIME_SCHEMA_CODECS = Object.freeze({
|
|
||||||
${pascal}NoRequest: runtimeSchemaCodecFromValidator(${upper}_VALIDATORS.${pascal}NoRequest),
|
|
||||||
${pascal}ItemListPayload: runtimeSchemaCodecFromValidator(
|
|
||||||
${upper}_VALIDATORS.${pascal}ItemListPayload,
|
|
||||||
),
|
|
||||||
});
|
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderMapper({ names, owner }: Shape): string {
|
function renderMapper({ names }: Shape): string {
|
||||||
const { base, camel, pascal, upper } = names;
|
const { base, pascal } = names;
|
||||||
return `import {
|
return `import {
|
||||||
mappingFailure,
|
|
||||||
mappingSuccess,
|
mappingSuccess,
|
||||||
type BoundaryMappingResult,
|
type BoundaryMappingResult,
|
||||||
type InstalledBoundaryMapper,
|
|
||||||
} from "../../../contracts/boundary-mapper.ts";
|
} from "../../../contracts/boundary-mapper.ts";
|
||||||
import {
|
import type { ${pascal}ItemDto } from "./${base}-schemas.ts";
|
||||||
${camel}ItemListPayloadSchema,
|
|
||||||
type ${pascal}ItemDto,
|
|
||||||
} from "./${base}-schemas.ts";
|
|
||||||
|
|
||||||
/** What the page shows. A wire field never reaches presentation by its wire name. */
|
/** What the page shows. A wire field never reaches presentation by its wire name. */
|
||||||
export type ${pascal}ItemView = Readonly<{ itemId: string; name: string }>;
|
export type ${pascal}ItemView = Readonly<{ itemId: string; name: string }>;
|
||||||
@@ -604,93 +591,37 @@ export function map${pascal}ItemList(
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The registry row (FE-REG-API). The registry is untyped, so it checks the shape. */
|
|
||||||
export const ${upper}_BOUNDARY_MAPPERS = Object.freeze({
|
|
||||||
${pascal}ItemListMapper: Object.freeze({
|
|
||||||
mapperId: "${pascal}ItemListMapper",
|
|
||||||
mapperVersion: 1,
|
|
||||||
inputSchemaId: "${pascal}ItemListPayload",
|
|
||||||
outputContractId: "${pascal}ItemList",
|
|
||||||
owner: "${owner}",
|
|
||||||
maxOutputItems: 100,
|
|
||||||
map(value: unknown) {
|
|
||||||
const parsed = ${camel}ItemListPayloadSchema.safeParse(value);
|
|
||||||
return parsed.success
|
|
||||||
? map${pascal}ItemList(parsed.data)
|
|
||||||
: mappingFailure("MAPPING_INVARIANT_REJECTED");
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
} satisfies Readonly<Record<string, InstalledBoundaryMapper>>);
|
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderApiContract({ names, operationId, apiPath, owner }: Shape): string {
|
function renderSchemaMetadata({ names, owner }: Shape): string {
|
||||||
const { base, pascal, upper } = names;
|
const { pascal, upper } = names;
|
||||||
return `import { defineRestOperation } from "../../../contracts/api-operations.ts";
|
return `const OWNER = "${owner}";
|
||||||
import { ${upper}_BOUNDARY_MAPPERS } from "./${base}-mapper.ts";
|
|
||||||
import { ${upper}_RUNTIME_SCHEMA_CODECS } from "./${base}-schemas.ts";
|
|
||||||
|
|
||||||
const OWNER = "${owner}";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The V2 API contract \`check:registries\` governs (FE-REG-API). The executable
|
* FE-REG-SCHEMA rows of the feature's schemas (\`check:registries\`). The HTTP
|
||||||
* descriptor of the same operation is in \`${base}-contract-contribution.ts\`;
|
* operation is written once, in \`${names.base}-contract-contribution.ts\`;
|
||||||
* tests/unit/http-operation-v2-v3-parity.test.ts fails when they disagree.
|
* FE-REG-API rows are projected from it. Runtime half only:
|
||||||
* Runtime half only: \`feature-runtime.ts\` loads it.
|
* \`feature-runtime.ts\` loads it.
|
||||||
*/
|
*/
|
||||||
export const ${upper}_API_CONTRACT = Object.freeze({
|
export const ${upper}_SCHEMA_METADATA = Object.freeze({
|
||||||
runtimeSchemas: ${upper}_RUNTIME_SCHEMA_CODECS,
|
${pascal}NoRequest: Object.freeze({
|
||||||
mappers: ${upper}_BOUNDARY_MAPPERS,
|
schemaId: "${pascal}NoRequest",
|
||||||
schemas: Object.freeze({
|
boundary: "api-request",
|
||||||
${pascal}NoRequest: Object.freeze({
|
owner: OWNER,
|
||||||
schemaId: "${pascal}NoRequest",
|
runtime: "zod",
|
||||||
boundary: "api-request",
|
schemaVersion: 1,
|
||||||
owner: OWNER,
|
direction: "REQUEST",
|
||||||
runtime: "zod",
|
unknownFieldPolicy: "REJECT_UNKNOWN",
|
||||||
schemaVersion: 1,
|
|
||||||
direction: "REQUEST",
|
|
||||||
unknownFieldPolicy: "REJECT_UNKNOWN",
|
|
||||||
}),
|
|
||||||
${pascal}ItemListPayload: Object.freeze({
|
|
||||||
schemaId: "${pascal}ItemListPayload",
|
|
||||||
boundary: "api-response",
|
|
||||||
owner: OWNER,
|
|
||||||
runtime: "zod",
|
|
||||||
schemaVersion: 1,
|
|
||||||
direction: "RESPONSE",
|
|
||||||
unknownFieldPolicy: "STRIP_UNKNOWN",
|
|
||||||
}),
|
|
||||||
}),
|
}),
|
||||||
apiOperations: Object.freeze({
|
${pascal}ItemListPayload: Object.freeze({
|
||||||
${operationId}: defineRestOperation({
|
schemaId: "${pascal}ItemListPayload",
|
||||||
method: "GET",
|
boundary: "api-response",
|
||||||
path: "${apiPath}",
|
owner: OWNER,
|
||||||
operationId: "${operationId}",
|
runtime: "zod",
|
||||||
auth: "external-session",
|
schemaVersion: 1,
|
||||||
timeoutMs: null,
|
direction: "RESPONSE",
|
||||||
idempotency: "safe",
|
unknownFieldPolicy: "STRIP_UNKNOWN",
|
||||||
retry: "runtime",
|
|
||||||
requestSource: "none",
|
|
||||||
requestSchema: "${pascal}NoRequest",
|
|
||||||
responseSchema: "${pascal}ItemListPayload",
|
|
||||||
owner: OWNER,
|
|
||||||
contractVersion: 2,
|
|
||||||
protocol: "REST",
|
|
||||||
semantics: "QUERY",
|
|
||||||
replayPolicy: "SAFE",
|
|
||||||
idempotencyKeyPolicy: "NONE",
|
|
||||||
mapperId: "${pascal}ItemListMapper",
|
|
||||||
successStatuses: [200],
|
|
||||||
responseMediaTypes: ["application/json"],
|
|
||||||
maxResponseBytes: 262_144,
|
|
||||||
providerId: "PRIMARY_API",
|
|
||||||
authProfileId: "EXTERNAL_BEARER",
|
|
||||||
csrfProfileId: "NO_CSRF_BEARER",
|
|
||||||
pathSchema: "${pascal}NoRequest",
|
|
||||||
pathParameterNames: [],
|
|
||||||
maxEncodedSearchBytes: 0,
|
|
||||||
}),
|
|
||||||
}),
|
}),
|
||||||
} as const);
|
} as const);
|
||||||
`;
|
`;
|
||||||
@@ -713,7 +644,8 @@ import {
|
|||||||
} from "./${base}-schemas.ts";
|
} from "./${base}-schemas.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The executable (V3) descriptor of ${operationId}. It belongs to the contract
|
* The HTTP descriptor of ${operationId}, the one place the operation is
|
||||||
|
* written: it executes, and FE-REG-API reads it. It belongs to the contract
|
||||||
* package pinned in \`${base}-feature-contract.ts\`: import \`@org-contracts/*\`
|
* package pinned in \`${base}-feature-contract.ts\`: import \`@org-contracts/*\`
|
||||||
* only in this file (external-contract-package-single-import-path) and take
|
* only in this file (external-contract-package-single-import-path) and take
|
||||||
* the package's descriptor instead of this local one.
|
* the package's descriptor instead of this local one.
|
||||||
@@ -1038,12 +970,11 @@ export default function ${pascal}ListPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderInputTest({ names, operationId }: Shape): string {
|
function renderInputTest({ names, operationId }: Shape): string {
|
||||||
const { base, pascal, upper } = names;
|
const { base, pascal } = names;
|
||||||
return `import { describe, expect, it, vi } from "vitest";
|
return `import { describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { createFailure } from "../../../src/contracts/errors.ts";
|
import { createFailure } from "../../../src/contracts/errors.ts";
|
||||||
import { create${pascal}FeatureInput } from "../../../src/features/${names.id}/application/${base}-feature-api.ts";
|
import { create${pascal}FeatureInput } from "../../../src/features/${names.id}/application/${base}-feature-api.ts";
|
||||||
import { ${upper}_BOUNDARY_MAPPERS } from "../../../src/features/${names.id}/contracts/${base}-mapper.ts";
|
|
||||||
import type { TelemetryPort } from "../../../src/platform/telemetry/telemetry-port.ts";
|
import type { TelemetryPort } from "../../../src/platform/telemetry/telemetry-port.ts";
|
||||||
|
|
||||||
const ITEMS = Object.freeze([Object.freeze({ itemId: "item-1", name: "First item" })]);
|
const ITEMS = Object.freeze([Object.freeze({ itemId: "item-1", name: "First item" })]);
|
||||||
@@ -1086,15 +1017,6 @@ describe("${names.id} application input", () => {
|
|||||||
await expect(input.listItems()).resolves.toEqual({ ok: false, error: failure });
|
await expect(input.listItems()).resolves.toEqual({ ok: false, error: failure });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("${names.id} registry mapper", () => {
|
|
||||||
it("maps a list payload and rejects any other shape", () => {
|
|
||||||
const { map } = ${upper}_BOUNDARY_MAPPERS.${pascal}ItemListMapper;
|
|
||||||
|
|
||||||
expect(map([{ id: "item-1", name: "First item" }])).toEqual({ ok: true, value: ITEMS });
|
|
||||||
expect(map({ items: [] })).toEqual({ ok: false, code: "MAPPING_INVARIANT_REJECTED" });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ export const COMPOSITION_WORKLOADS: readonly CompositionWorkload[] = Object.free
|
|||||||
loadRuntime: async () =>
|
loadRuntime: async () =>
|
||||||
Object.freeze({
|
Object.freeze({
|
||||||
featureId: id,
|
featureId: id,
|
||||||
apiContract: Object.freeze({}),
|
schemas: Object.freeze({}),
|
||||||
adapters: Object.freeze([]),
|
adapters: Object.freeze([]),
|
||||||
contractContributions: Object.freeze([]),
|
contractContributions: Object.freeze([]),
|
||||||
}),
|
}),
|
||||||
|
|||||||
+46
-215
@@ -1,226 +1,57 @@
|
|||||||
export type ApiOperation = Readonly<{
|
import type {
|
||||||
method: string;
|
HttpMethod,
|
||||||
path: string;
|
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;
|
operationId: string;
|
||||||
auth: "none" | "external-session";
|
featureId: string;
|
||||||
timeoutMs: number | null;
|
method: HttpMethod;
|
||||||
idempotency: "safe" | "keyed" | "none";
|
path: string;
|
||||||
retry: "runtime" | "never";
|
authProfileId: string;
|
||||||
requestSource: "search" | "body" | "none";
|
retrySemantics: RetrySemantics;
|
||||||
|
requestBody: InstalledHttpContract<unknown, unknown, unknown>["contract"]["requestBody"];
|
||||||
|
responseBody: InstalledHttpContract<unknown, unknown, unknown>["contract"]["responseBody"];
|
||||||
|
responseEnvelope: ResponseEnvelope;
|
||||||
requestSchema: string;
|
requestSchema: string;
|
||||||
responseSchema: string;
|
responseSchema: string;
|
||||||
owner: string;
|
problemSchema: 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;
|
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 07-02. A V2 row is the declaration `check:registries` (FE-REG-API) governs;
|
* Pass composed contributions (`composeContractContributions`): composition
|
||||||
* it is not what executes. The executed copy of the same HTTP API is the V3
|
* already refused duplicate operation ids and snapshotted every row.
|
||||||
* 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.
|
|
||||||
*/
|
*/
|
||||||
export type RestOperationV2 = ApiOperation &
|
export function projectApiOperationRows(
|
||||||
Readonly<{
|
contributions: readonly InstalledContractContribution[],
|
||||||
contractVersion: 2;
|
): Readonly<Record<string, ApiOperationRow>> {
|
||||||
protocol: "REST";
|
const rows: Record<string, ApiOperationRow> = {};
|
||||||
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);
|
|
||||||
for (const contribution of contributions) {
|
for (const contribution of contributions) {
|
||||||
for (const [registryId, operation] of Object.entries(contribution)) {
|
for (const { contract, frontend } of contribution.http) {
|
||||||
if (registryId !== operation.operationId) {
|
rows[contract.operationId] = Object.freeze({
|
||||||
throw new TypeError("API operation registry key does not match operationId.");
|
operationId: contract.operationId,
|
||||||
}
|
featureId: contribution.featureId,
|
||||||
if (Object.hasOwn(result, registryId)) {
|
method: contract.method,
|
||||||
throw new TypeError(`Duplicate API operation: ${registryId}`);
|
path: contract.pathTemplate,
|
||||||
}
|
authProfileId: frontend.authProfileId,
|
||||||
if (operation.contractVersion === 2) {
|
retrySemantics: contract.retrySemantics,
|
||||||
validateRestOperation(operation as RestOperationV2);
|
requestBody: contract.requestBody,
|
||||||
}
|
responseBody: contract.responseBody,
|
||||||
result[registryId] = operation;
|
responseEnvelope: contract.responseEnvelope ?? "NONE",
|
||||||
|
requestSchema: contract.inputValidator.schemaId,
|
||||||
|
responseSchema: contract.outputValidator.schemaId,
|
||||||
|
problemSchema: contract.problemValidator.schemaId,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Object.freeze(result);
|
return Object.freeze(rows);
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 { InstalledBoundaryMapper } from "./boundary-mapper.ts";
|
||||||
import type { RuntimeSchemaCodec } from "./schema-registry.ts";
|
import type { RuntimeSchemaCodec } from "./schema-registry.ts";
|
||||||
import {
|
import {
|
||||||
@@ -105,7 +105,7 @@ export type RealtimeEventTypeRegistration = Readonly<{
|
|||||||
export type RealtimePolicyRegistryBindings = Readonly<{
|
export type RealtimePolicyRegistryBindings = Readonly<{
|
||||||
schemaCodecs: Readonly<Record<string, RuntimeSchemaCodec>>;
|
schemaCodecs: Readonly<Record<string, RuntimeSchemaCodec>>;
|
||||||
mappers: Readonly<Record<string, InstalledBoundaryMapper>>;
|
mappers: Readonly<Record<string, InstalledBoundaryMapper>>;
|
||||||
apiOperations: Readonly<Record<string, ApiOperation>>;
|
apiOperations: Readonly<Record<string, ApiOperationRow>>;
|
||||||
endpointIds: readonly RealtimeEndpointId[];
|
endpointIds: readonly RealtimeEndpointId[];
|
||||||
effectProfileIds: readonly ExternalEventEffectProfileId[];
|
effectProfileIds: readonly ExternalEventEffectProfileId[];
|
||||||
killSwitchIds: readonly KillSwitchId[];
|
killSwitchIds: readonly KillSwitchId[];
|
||||||
@@ -467,11 +467,9 @@ function validSnapshotBindings(
|
|||||||
OWNED_ID.test(input.checkpointCodecId) &&
|
OWNED_ID.test(input.checkpointCodecId) &&
|
||||||
bindings.schemaCodecs[input.checkpointCodecId]?.schemaId ===
|
bindings.schemaCodecs[input.checkpointCodecId]?.schemaId ===
|
||||||
input.checkpointCodecId &&
|
input.checkpointCodecId &&
|
||||||
operation?.contractVersion === 2 &&
|
operation?.method === "GET" &&
|
||||||
operation.protocol === "REST" &&
|
(operation.retrySemantics === "SAFE" ||
|
||||||
operation.semantics === "QUERY" &&
|
operation.retrySemantics === "IDEMPOTENT")
|
||||||
(operation.replayPolicy === "SAFE" ||
|
|
||||||
operation.replayPolicy === "IDEMPOTENT")
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,19 +3,10 @@ import {
|
|||||||
type ReadOnlyRegistry,
|
type ReadOnlyRegistry,
|
||||||
} from "./read-only-registry.ts";
|
} from "./read-only-registry.ts";
|
||||||
import { snapshotExactArray, snapshotExactObject } from "./exact-snapshot.ts";
|
import { snapshotExactArray, snapshotExactObject } from "./exact-snapshot.ts";
|
||||||
import { isLoopbackHostname } from "./deployment-admission.ts";
|
|
||||||
import { PRODUCT_REST_AUTH_PROFILES } from "./product-contracts.ts";
|
import { PRODUCT_REST_AUTH_PROFILES } from "./product-contracts.ts";
|
||||||
|
|
||||||
export type FetchCredentialsMode = "omit" | "same-origin" | "include";
|
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.
|
* VD-23. The complete closed set of headers a credential owner may contribute.
|
||||||
* Transport-owned headers (`accept`, `content-type`, `idempotency-key`) and
|
* Transport-owned headers (`accept`, `content-type`, `idempotency-key`) and
|
||||||
@@ -57,12 +48,6 @@ export type InstalledRestAuthProfiles = ReadOnlyRegistry<
|
|||||||
RestAuthProfile
|
RestAuthProfile
|
||||||
>;
|
>;
|
||||||
|
|
||||||
export type RestCsrfProfile = Readonly<{
|
|
||||||
csrfProfileId: string;
|
|
||||||
mode: "NONE" | "HEADER";
|
|
||||||
headerName: "x-csrf-token" | null;
|
|
||||||
}>;
|
|
||||||
|
|
||||||
const EXTERNAL_BEARER = Object.freeze({
|
const EXTERNAL_BEARER = Object.freeze({
|
||||||
authProfileId: "EXTERNAL_BEARER",
|
authProfileId: "EXTERNAL_BEARER",
|
||||||
transport: "BEARER_HEADER",
|
transport: "BEARER_HEADER",
|
||||||
@@ -213,35 +198,7 @@ export function installRestAuthProfileRegistry(
|
|||||||
if (installed.size === 0) {
|
if (installed.size === 0) {
|
||||||
throw new TypeError("REST auth profile registry cannot be empty.");
|
throw new TypeError("REST auth profile registry cannot be empty.");
|
||||||
}
|
}
|
||||||
const registry = createReadOnlyRegistry(installed);
|
return 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>>,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function withProductProfiles(): Readonly<Record<string, RestAuthProfile>> {
|
function withProductProfiles(): Readonly<Record<string, RestAuthProfile>> {
|
||||||
@@ -263,141 +220,3 @@ function withProductProfiles(): Readonly<Record<string, RestAuthProfile>> {
|
|||||||
*/
|
*/
|
||||||
export const INSTALLED_REST_AUTH_PROFILES: InstalledRestAuthProfiles =
|
export const INSTALLED_REST_AUTH_PROFILES: InstalledRestAuthProfiles =
|
||||||
installRestAuthProfileRegistry(withProductProfiles());
|
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;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -42,13 +42,6 @@ type EmptyFeatureMessageCatalogs = Readonly<
|
|||||||
Record<string, Readonly<Record<never, never>>>
|
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
|
* 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.
|
* it belongs to that feature.
|
||||||
*/
|
*/
|
||||||
export type FeatureRuntime<
|
export type FeatureRuntime<
|
||||||
ApiContract = EmptyFeatureApiContract,
|
Schemas = EmptyRecord,
|
||||||
Adapter = never,
|
Adapter = never,
|
||||||
ContractContribution = never,
|
ContractContribution = never,
|
||||||
> = Readonly<{
|
> = Readonly<{
|
||||||
featureId: string;
|
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[];
|
adapters: readonly Adapter[];
|
||||||
contractContributions: readonly ContractContribution[];
|
contractContributions: readonly ContractContribution[];
|
||||||
}>;
|
}>;
|
||||||
|
|||||||
@@ -1,15 +1,9 @@
|
|||||||
import {
|
import { projectApiOperationRows } from "../contracts/api-operations.ts";
|
||||||
composeApiOperations,
|
|
||||||
validateApiRuntimeBindings,
|
|
||||||
} from "../contracts/api-operations.ts";
|
|
||||||
import { composeBoundaryMapperRegistry } from "../contracts/boundary-mapper.ts";
|
|
||||||
import {
|
import {
|
||||||
composeContractContributions,
|
composeContractContributions,
|
||||||
type InstalledContractContribution,
|
type InstalledContractContribution,
|
||||||
} from "../contracts/external-contract-runtime.ts";
|
} from "../contracts/external-contract-runtime.ts";
|
||||||
import { validateRestProfileBindings } from "../contracts/rest-profiles.ts";
|
|
||||||
import {
|
import {
|
||||||
composeRuntimeSchemaCodecs,
|
|
||||||
composeSchemaRegistry,
|
composeSchemaRegistry,
|
||||||
PLATFORM_SCHEMA_REGISTRY,
|
PLATFORM_SCHEMA_REGISTRY,
|
||||||
} from "../contracts/schema-registry.ts";
|
} 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
|
* 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
|
* registries that need all of them: the schema registry, the contract
|
||||||
* contributions. Duplicates across features throw here, as they did at boot
|
* contributions, and the FE-REG-API rows projected from those contributions.
|
||||||
* before 15-01.
|
* 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
|
* 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`).
|
* 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(
|
const runtimes = Object.freeze(
|
||||||
await Promise.all(INSTALLED_PRODUCT_FEATURE_MODULES.map(loadFeatureRuntime)),
|
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([
|
const schemaRegistry = composeSchemaRegistry([
|
||||||
PLATFORM_SCHEMA_REGISTRY,
|
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[] =
|
const contractContributions: readonly InstalledContractContribution[] =
|
||||||
Object.freeze(
|
Object.freeze(
|
||||||
@@ -94,12 +64,10 @@ export async function loadInstalledFeatureRuntimeRegistries() {
|
|||||||
|
|
||||||
return Object.freeze({
|
return Object.freeze({
|
||||||
runtimes,
|
runtimes,
|
||||||
apiOperations,
|
apiOperations: projectApiOperationRows(
|
||||||
restProfileBindingsValid,
|
composedContractContributions.contributions,
|
||||||
|
),
|
||||||
schemaRegistry,
|
schemaRegistry,
|
||||||
runtimeSchemaCodecs,
|
|
||||||
mapperRegistry,
|
|
||||||
apiRuntimeBindingsValid,
|
|
||||||
contractContributions,
|
contractContributions,
|
||||||
composedContractContributions,
|
composedContractContributions,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -17,11 +17,7 @@ const registries = await loadInstalledFeatureRuntimeRegistries();
|
|||||||
|
|
||||||
export const LOADED_FEATURE_RUNTIMES = registries.runtimes;
|
export const LOADED_FEATURE_RUNTIMES = registries.runtimes;
|
||||||
export const API_OPERATIONS = registries.apiOperations;
|
export const API_OPERATIONS = registries.apiOperations;
|
||||||
export const REST_PROFILE_BINDINGS_VALID = registries.restProfileBindingsValid;
|
|
||||||
export const SCHEMA_REGISTRY = registries.schemaRegistry;
|
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 INSTALLED_CONTRACT_CONTRIBUTIONS = registries.contractContributions;
|
||||||
export const COMPOSED_CONTRACT_CONTRIBUTIONS =
|
export const COMPOSED_CONTRACT_CONTRIBUTIONS =
|
||||||
registries.composedContractContributions;
|
registries.composedContractContributions;
|
||||||
|
|||||||
@@ -57,8 +57,8 @@ feature가 실제 contribution을 소유한다.
|
|||||||
|
|
||||||
- 선언(초기 청크, `feature-module.ts`): route 표와 invalidation은
|
- 선언(초기 청크, `feature-module.ts`): route 표와 invalidation은
|
||||||
`reference-feature-contract.ts`, 문구는 `reference-message-catalog.ts`
|
`reference-feature-contract.ts`, 문구는 `reference-message-catalog.ts`
|
||||||
- 실행부(`feature-runtime.ts`, reference route에 들어갈 때 적재): API 계약
|
- 실행부(`feature-runtime.ts`, reference route에 들어갈 때 적재): 스키마 메타데이터
|
||||||
`reference-api-contract.ts`, bootstrap input
|
`reference-schema-metadata.ts`, bootstrap input
|
||||||
`REFERENCE_FEATURE_ADAPTER_CONTRIBUTION`, HTTP contract contribution
|
`REFERENCE_FEATURE_ADAPTER_CONTRIBUTION`, HTTP contract contribution
|
||||||
- route codec과 page component: `REFERENCE_FEATURE_ROUTE_CODECS`,
|
- route codec과 page component: `REFERENCE_FEATURE_ROUTE_CODECS`,
|
||||||
`REFERENCE_FEATURE_ROUTE_RUNTIME` (`context-routes.ts`가 route handle에 실어
|
`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
|
* 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
|
* is entered. It is in the initial chunk, so it holds data only. The schema
|
||||||
* contract with its runtime schemas and mappers is
|
* metadata is `reference-schema-metadata.ts` and the HTTP operations are
|
||||||
* `reference-api-contract.ts`, loaded with `feature-runtime.ts`.
|
* `reference-feature-contract-contribution.ts`, both loaded with
|
||||||
|
* `feature-runtime.ts`.
|
||||||
*/
|
*/
|
||||||
export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
|
export const REFERENCE_FEATURE_CONTRACT = Object.freeze({
|
||||||
featureId: REFERENCE_FEATURE_ID,
|
featureId: REFERENCE_FEATURE_ID,
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import {
|
|||||||
import {
|
import {
|
||||||
mappingFailure,
|
mappingFailure,
|
||||||
mappingSuccess,
|
mappingSuccess,
|
||||||
type InstalledBoundaryMapper,
|
|
||||||
type BoundaryMappingResult,
|
type BoundaryMappingResult,
|
||||||
} from "../../../contracts/boundary-mapper.ts";
|
} from "../../../contracts/boundary-mapper.ts";
|
||||||
import type { ReferenceResourceDto } from "./reference-schemas.ts";
|
import type { ReferenceResourceDto } from "./reference-schemas.ts";
|
||||||
@@ -49,83 +48,6 @@ export function mapReferenceResourceListPayload(
|
|||||||
return mappingSuccess(Object.freeze(output));
|
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(
|
export function toReferenceView(
|
||||||
resource: ReferenceResource,
|
resource: ReferenceResource,
|
||||||
): ReferenceResourceView {
|
): 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 { z } from "../../../contracts/zod.ts";
|
||||||
import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
|
|
||||||
import { zodValidator } from "../../../contracts/zod-validator.ts";
|
|
||||||
|
|
||||||
export const referenceResourceListQuerySchema = z
|
export const referenceResourceListQuerySchema = z
|
||||||
.object({
|
.object({
|
||||||
@@ -67,69 +65,3 @@ export const createReferenceResourceCommandSchema = z
|
|||||||
note: z.string().trim().max(500).optional(),
|
note: z.string().trim().max(500).optional(),
|
||||||
})
|
})
|
||||||
.strict();
|
.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 { defineFeatureRuntime } from "../feature-module.ts";
|
||||||
import { REFERENCE_FEATURE_ADAPTER_CONTRIBUTION } from "./adapters/create-reference-feature-input.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_TEMPLATE_CONTRIBUTION } from "./contracts/reference-feature-contract-contribution.ts";
|
||||||
import { REFERENCE_FEATURE_ID } from "./contracts/reference-feature-contract.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`
|
* 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({
|
export const FEATURE_RUNTIME = defineFeatureRuntime({
|
||||||
featureId: REFERENCE_FEATURE_ID,
|
featureId: REFERENCE_FEATURE_ID,
|
||||||
apiContract: REFERENCE_API_CONTRACT,
|
schemas: REFERENCE_SCHEMA_METADATA,
|
||||||
adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION],
|
adapters: [REFERENCE_FEATURE_ADAPTER_CONTRIBUTION],
|
||||||
contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION],
|
contractContributions: [REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION],
|
||||||
} as const);
|
} as const);
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ function feature(id: string, paths: Readonly<Record<string, string>>) {
|
|||||||
messages: {},
|
messages: {},
|
||||||
loadRuntime: async () => ({
|
loadRuntime: async () => ({
|
||||||
featureId: id,
|
featureId: id,
|
||||||
apiContract: {},
|
schemas: {},
|
||||||
adapters: [],
|
adapters: [],
|
||||||
contractContributions: [],
|
contractContributions: [],
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { defineFeatureModule } from "../../src/features/feature-module.ts";
|
|||||||
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
|
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
|
||||||
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
|
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
|
||||||
|
|
||||||
const feature = defineFeatureModule({ id:"f", contracts:{featureId:"f"}, routes:{}, messages:{}, loadRuntime: async () => ({ featureId: "f", apiContract: {}, adapters: [], contractContributions: [] }) });
|
const feature = defineFeatureModule({ id:"f", contracts:{featureId:"f"}, routes:{}, messages:{}, loadRuntime: async () => ({ featureId: "f", schemas: {}, adapters: [], contractContributions: [] }) });
|
||||||
describe("module hierarchy", () => {
|
describe("module hierarchy", () => {
|
||||||
it("exposes only direct children and freezes copied arrays", () => {
|
it("exposes only direct children and freezes copied arrays", () => {
|
||||||
const features = [feature];
|
const features = [feature];
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ function fakeFeature(id: string) {
|
|||||||
messages: {},
|
messages: {},
|
||||||
loadRuntime: async () => ({
|
loadRuntime: async () => ({
|
||||||
featureId: id,
|
featureId: id,
|
||||||
apiContract: {},
|
schemas: {},
|
||||||
adapters: [],
|
adapters: [],
|
||||||
contractContributions: [],
|
contractContributions: [],
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
|
|
||||||
const runtimeOf = async (featureId: string) => ({
|
const runtimeOf = async (featureId: string) => ({
|
||||||
featureId,
|
featureId,
|
||||||
apiContract: {},
|
schemas: {},
|
||||||
adapters: [],
|
adapters: [],
|
||||||
contractContributions: [],
|
contractContributions: [],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ describe("REFERENCE_FEATURE_MODULE", () => {
|
|||||||
expect(runtime.featureId).toBe("reference-feature");
|
expect(runtime.featureId).toBe("reference-feature");
|
||||||
expect(runtime.adapters.length).toBeGreaterThan(0);
|
expect(runtime.adapters.length).toBeGreaterThan(0);
|
||||||
expect(runtime.contractContributions.length).toBeGreaterThan(0);
|
expect(runtime.contractContributions.length).toBeGreaterThan(0);
|
||||||
expect(Object.keys(runtime.apiContract.apiOperations).length).toBeGreaterThan(0);
|
expect(Object.keys(runtime.schemas).length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("types a feature message's parameters from its catalog placeholders", () => {
|
it("types a feature message's parameters from its catalog placeholders", () => {
|
||||||
|
|||||||
@@ -5,19 +5,20 @@ import {
|
|||||||
parseRouteInput,
|
parseRouteInput,
|
||||||
} from "../../../src/presentation/routes/route-codecs.ts";
|
} from "../../../src/presentation/routes/route-codecs.ts";
|
||||||
import {
|
import {
|
||||||
mapReferenceOperation,
|
mapReferenceResourcePayload,
|
||||||
toReferenceView,
|
toReferenceView,
|
||||||
} from "../../../src/features/reference-feature/contracts/reference-mapper.ts";
|
} from "../../../src/features/reference-feature/contracts/reference-mapper.ts";
|
||||||
import {
|
import {
|
||||||
validateReferencePayload,
|
CREATE_REFERENCE_RESOURCE_CONTRACT,
|
||||||
validateReferenceRequest,
|
GET_REFERENCE_RESOURCE_CONTRACT,
|
||||||
} from "../../../src/features/reference-feature/contracts/reference-schemas.ts";
|
LIST_REFERENCE_RESOURCES_CONTRACT,
|
||||||
|
REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION,
|
||||||
|
} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts";
|
||||||
import {
|
import {
|
||||||
REFERENCE_FEATURE_CONTRACT,
|
REFERENCE_FEATURE_CONTRACT,
|
||||||
REFERENCE_FEATURE_ID,
|
REFERENCE_FEATURE_ID,
|
||||||
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
REFERENCE_RESOURCE_INVALIDATION_TOPIC,
|
||||||
} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
} from "../../../src/features/reference-feature/contracts/reference-feature-contract.ts";
|
||||||
import { REFERENCE_API_CONTRACT } from "../../../src/features/reference-feature/contracts/reference-api-contract.ts";
|
|
||||||
import { REFERENCE_FEATURE_ROUTE_CODECS } from "../../../src/features/reference-feature/presentation/reference-route-codecs.ts";
|
import { REFERENCE_FEATURE_ROUTE_CODECS } from "../../../src/features/reference-feature/presentation/reference-route-codecs.ts";
|
||||||
import type { ReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts";
|
import type { ReferenceFeatureInput } from "../../../src/features/reference-feature/application/reference-feature-api.ts";
|
||||||
import { createTestApplication } from "../../helpers/create-test-application.ts";
|
import { createTestApplication } from "../../helpers/create-test-application.ts";
|
||||||
@@ -85,31 +86,24 @@ describe("reference feature boundary contracts", () => {
|
|||||||
),
|
),
|
||||||
).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" });
|
).toEqual({ success: false, code: "ROUTE_SEARCH_INVALID" });
|
||||||
expect(
|
expect(
|
||||||
validateReferencePayload("ReferenceResourceListPayload", [
|
LIST_REFERENCE_RESOURCES_CONTRACT.contract.outputValidator.safeParse([
|
||||||
{ id: "unsafe", name: 42 },
|
{ id: "unsafe", name: 42 },
|
||||||
]),
|
]),
|
||||||
).toMatchObject({ success: false });
|
).toMatchObject({ success: false });
|
||||||
expect(
|
|
||||||
mapReferenceOperation("LIST_REFERENCE_RESOURCES", [
|
|
||||||
{ id: "unsafe", name: 42 },
|
|
||||||
]),
|
|
||||||
).toMatchObject({ ok: false });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("normalizes request input and maps only owned domain fields", () => {
|
it("normalizes request input and maps only owned domain fields", () => {
|
||||||
expect(
|
expect(
|
||||||
validateReferenceRequest("CreateReferenceResourceCommand", {
|
CREATE_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.safeParse({
|
||||||
name: " Example ",
|
name: " Example ",
|
||||||
}),
|
}),
|
||||||
).toMatchObject({ success: true, data: { name: "Example" } });
|
).toMatchObject({ success: true, data: { name: "Example" } });
|
||||||
const model = mapReferenceOperation("CREATE_REFERENCE_RESOURCE", {
|
const model = mapReferenceResourcePayload({
|
||||||
id: "reference-1",
|
id: "reference-1",
|
||||||
name: "Example",
|
name: "Example",
|
||||||
createdAt: "2026-07-26T00:00:00.000Z",
|
createdAt: "2026-07-26T00:00:00.000Z",
|
||||||
});
|
});
|
||||||
if (!model.ok || !("id" in model.value)) {
|
if (!model.ok) throw new Error("expected one model");
|
||||||
throw new Error("expected one model");
|
|
||||||
}
|
|
||||||
expect(toReferenceView(model.value)).toEqual({
|
expect(toReferenceView(model.value)).toEqual({
|
||||||
resourceId: "reference-1",
|
resourceId: "reference-1",
|
||||||
title: "Example",
|
title: "Example",
|
||||||
@@ -124,20 +118,24 @@ describe("reference feature boundary contracts", () => {
|
|||||||
"REFERENCE_RESOURCE_FORM",
|
"REFERENCE_RESOURCE_FORM",
|
||||||
"REFERENCE_RESOURCE_STATUS",
|
"REFERENCE_RESOURCE_STATUS",
|
||||||
]);
|
]);
|
||||||
expect(Object.keys(REFERENCE_API_CONTRACT.apiOperations)).toEqual([
|
|
||||||
"LIST_REFERENCE_RESOURCES",
|
|
||||||
"CREATE_REFERENCE_RESOURCE",
|
|
||||||
"GET_REFERENCE_RESOURCE",
|
|
||||||
]);
|
|
||||||
expect(
|
expect(
|
||||||
REFERENCE_API_CONTRACT.apiOperations.GET_REFERENCE_RESOURCE,
|
REFERENCE_FEATURE_TEMPLATE_CONTRIBUTION.http.map(
|
||||||
).toMatchObject({
|
({ contract }) => contract.operationId,
|
||||||
pathSchema: "ReferenceResourceParams",
|
),
|
||||||
pathParameterNames: ["resourceId"],
|
).toEqual([
|
||||||
providerId: "PRIMARY_API",
|
"LIST_REFERENCE_RESOURCES",
|
||||||
authProfileId: "EXTERNAL_BEARER",
|
"GET_REFERENCE_RESOURCE",
|
||||||
csrfProfileId: "NO_CSRF_BEARER",
|
"CREATE_REFERENCE_RESOURCE",
|
||||||
|
]);
|
||||||
|
expect(GET_REFERENCE_RESOURCE_CONTRACT.contract).toMatchObject({
|
||||||
|
pathTemplate: "/api/reference-resources/{resourceId}",
|
||||||
});
|
});
|
||||||
|
expect(GET_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.schemaId).toBe(
|
||||||
|
"ReferenceResourceParams",
|
||||||
|
);
|
||||||
|
expect(GET_REFERENCE_RESOURCE_CONTRACT.frontend.authProfileId).toBe(
|
||||||
|
"EXTERNAL_BEARER",
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("contributes an identity-based invalidation graph and an explicit wire version", () => {
|
it("contributes an identity-based invalidation graph and an explicit wire version", () => {
|
||||||
|
|||||||
@@ -4,17 +4,10 @@ import {
|
|||||||
CREATE_REFERENCE_RESOURCE_CONTRACT,
|
CREATE_REFERENCE_RESOURCE_CONTRACT,
|
||||||
LIST_REFERENCE_RESOURCES_CONTRACT,
|
LIST_REFERENCE_RESOURCES_CONTRACT,
|
||||||
} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts";
|
} from "../../../src/features/reference-feature/contracts/reference-feature-contract-contribution.ts";
|
||||||
import {
|
|
||||||
REFERENCE_RUNTIME_SCHEMA_CODECS,
|
|
||||||
validateReferencePayload,
|
|
||||||
validateReferenceRequest,
|
|
||||||
} from "../../../src/features/reference-feature/contracts/reference-schemas.ts";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Q-6.7-8 characterization. The reference feature exposes one schema through
|
* Q-6.7-8 characterization. The reference feature's schemas answer through the
|
||||||
* two protocols: the canonical `RuntimeValidator` (array paths) for the HTTP
|
* canonical `RuntimeValidator` protocol (array paths) of its HTTP contract.
|
||||||
* contract and the registry-facing `RuntimeSchemaCodec` (dotted paths). Both
|
|
||||||
* must keep answering exactly this after they share one zod wrapper.
|
|
||||||
*/
|
*/
|
||||||
describe("reference validator protocols", () => {
|
describe("reference validator protocols", () => {
|
||||||
const badList = [{ id: "unsafe", name: 42 }];
|
const badList = [{ id: "unsafe", name: 42 }];
|
||||||
@@ -34,55 +27,4 @@ describe("reference validator protocols", () => {
|
|||||||
}),
|
}),
|
||||||
).toEqual({ success: true, data: { name: "Example" } });
|
).toEqual({ success: true, data: { name: "Example" } });
|
||||||
});
|
});
|
||||||
|
|
||||||
it("answers the schema codec with dotted paths", () => {
|
|
||||||
const codecs = REFERENCE_RUNTIME_SCHEMA_CODECS;
|
|
||||||
expect(codecs.ReferenceResourceListPayload.parse(badList)).toEqual({
|
|
||||||
success: false,
|
|
||||||
issues: [{ path: "0.name", code: "invalid_type" }],
|
|
||||||
});
|
|
||||||
expect(
|
|
||||||
codecs.CreateReferenceResourceCommand.parse({ name: "a", extra: 1 }),
|
|
||||||
).toEqual({
|
|
||||||
success: false,
|
|
||||||
issues: [{ path: "", code: "unrecognized_keys" }],
|
|
||||||
});
|
|
||||||
expect(
|
|
||||||
codecs.ReferenceResourceListQuery.parse({ limit: "5", tags: "open" }),
|
|
||||||
).toEqual({ success: true, data: { limit: 5, tags: ["open"] } });
|
|
||||||
expect(Object.keys(codecs)).toEqual([
|
|
||||||
"ReferenceResourceParams",
|
|
||||||
"ReferenceResourceListQuery",
|
|
||||||
"NoRequest",
|
|
||||||
"CreateReferenceResourceCommand",
|
|
||||||
"ReferenceResourceListPayload",
|
|
||||||
"ReferenceResourcePayload",
|
|
||||||
]);
|
|
||||||
for (const [schemaId, codec] of Object.entries(codecs)) {
|
|
||||||
expect(codec.schemaId).toBe(schemaId);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps the payload and request lookups apart", () => {
|
|
||||||
expect(validateReferencePayload("ReferenceResourceListPayload", badList))
|
|
||||||
.toEqual({
|
|
||||||
success: false,
|
|
||||||
issues: [{ path: "0.name", code: "invalid_type" }],
|
|
||||||
});
|
|
||||||
expect(validateReferencePayload("NoRequest", {})).toEqual({
|
|
||||||
success: false,
|
|
||||||
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }],
|
|
||||||
});
|
|
||||||
expect(
|
|
||||||
validateReferenceRequest("CreateReferenceResourceCommand", {
|
|
||||||
name: " Example ",
|
|
||||||
}),
|
|
||||||
).toEqual({ success: true, data: { name: "Example" } });
|
|
||||||
expect(
|
|
||||||
validateReferenceRequest("ReferenceResourcePayload", {}),
|
|
||||||
).toEqual({
|
|
||||||
success: false,
|
|
||||||
issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -123,12 +123,7 @@ export const FIXTURE_FEATURE_MODULE = defineFeatureModule({
|
|||||||
loadRuntime: async () =>
|
loadRuntime: async () =>
|
||||||
Object.freeze({
|
Object.freeze({
|
||||||
featureId: FIXTURE_FEATURE_ID,
|
featureId: FIXTURE_FEATURE_ID,
|
||||||
apiContract: Object.freeze({
|
schemas: Object.freeze({}),
|
||||||
apiOperations: Object.freeze({}),
|
|
||||||
schemas: Object.freeze({}),
|
|
||||||
runtimeSchemas: Object.freeze({}),
|
|
||||||
mappers: Object.freeze({}),
|
|
||||||
}),
|
|
||||||
adapters: Object.freeze([]),
|
adapters: Object.freeze([]),
|
||||||
contractContributions: Object.freeze([]),
|
contractContributions: Object.freeze([]),
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -83,12 +83,7 @@ function layoutFeature(featureId: string, specs: readonly RouteSpec[]) {
|
|||||||
loadRuntime: async () =>
|
loadRuntime: async () =>
|
||||||
Object.freeze({
|
Object.freeze({
|
||||||
featureId,
|
featureId,
|
||||||
apiContract: Object.freeze({
|
schemas: Object.freeze({}),
|
||||||
apiOperations: Object.freeze({}),
|
|
||||||
schemas: Object.freeze({}),
|
|
||||||
runtimeSchemas: Object.freeze({}),
|
|
||||||
mappers: Object.freeze({}),
|
|
||||||
}),
|
|
||||||
adapters: Object.freeze([]),
|
adapters: Object.freeze([]),
|
||||||
contractContributions: Object.freeze([]),
|
contractContributions: Object.freeze([]),
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { projectApiOperationRows } from "../../src/contracts/api-operations.ts";
|
||||||
|
import { composeContractContributions } from "../../src/contracts/external-contract-runtime.ts";
|
||||||
|
import {
|
||||||
|
API_OPERATIONS,
|
||||||
|
COMPOSED_CONTRACT_CONTRIBUTIONS,
|
||||||
|
} from "../../src/features/loaded-feature-runtimes.ts";
|
||||||
|
import {
|
||||||
|
TEST_CONTRACT_CONTRIBUTION,
|
||||||
|
TEST_LIST_HTTP_CONTRACT,
|
||||||
|
} from "../helpers/external-contract-fixture.ts";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FE-REG-API rows are projected from the installed HTTP descriptors, so an
|
||||||
|
* operation is written once and the governed row cannot disagree with what
|
||||||
|
* executes.
|
||||||
|
*/
|
||||||
|
describe("FE-REG-API rows projected from HTTP descriptors", () => {
|
||||||
|
it("projects each descriptor with its feature, wire and schema identities", () => {
|
||||||
|
const rows = projectApiOperationRows(
|
||||||
|
composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).contributions,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(Object.keys(rows)).toEqual([
|
||||||
|
"TEST_LIST_ENTITIES",
|
||||||
|
"TEST_GET_ENTITY",
|
||||||
|
"TEST_CREATE_ENTITY",
|
||||||
|
]);
|
||||||
|
expect(rows.TEST_LIST_ENTITIES).toEqual({
|
||||||
|
operationId: "TEST_LIST_ENTITIES",
|
||||||
|
featureId: "test-feature",
|
||||||
|
method: "GET",
|
||||||
|
path: "/api/test-entities",
|
||||||
|
authProfileId: "ANONYMOUS",
|
||||||
|
retrySemantics: "SAFE",
|
||||||
|
requestBody: "NONE",
|
||||||
|
responseBody: "REQUIRED_JSON",
|
||||||
|
responseEnvelope: "NONE",
|
||||||
|
requestSchema: "TestEntityListQuery",
|
||||||
|
responseSchema: "TestEntityListPayload",
|
||||||
|
problemSchema: "TestProblem",
|
||||||
|
});
|
||||||
|
expect(rows.TEST_CREATE_ENTITY).toMatchObject({
|
||||||
|
method: "POST",
|
||||||
|
retrySemantics: "KEYED",
|
||||||
|
requestBody: "JSON",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("carries an Envelope declaration", () => {
|
||||||
|
const rows = projectApiOperationRows(
|
||||||
|
composeContractContributions([
|
||||||
|
{
|
||||||
|
...TEST_CONTRACT_CONTRIBUTION,
|
||||||
|
http: [
|
||||||
|
{
|
||||||
|
...TEST_LIST_HTTP_CONTRACT,
|
||||||
|
contract: {
|
||||||
|
...TEST_LIST_HTTP_CONTRACT.contract,
|
||||||
|
responseEnvelope: "ENVELOPE_V1" as const,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
] as never,
|
||||||
|
},
|
||||||
|
]).contributions,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(rows.TEST_LIST_ENTITIES?.responseEnvelope).toBe("ENVELOPE_V1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is what the registry governance reads for the installed features", () => {
|
||||||
|
expect(API_OPERATIONS).toEqual(
|
||||||
|
projectApiOperationRows(COMPOSED_CONTRACT_CONTRIBUTIONS.contributions),
|
||||||
|
);
|
||||||
|
expect(Object.keys(API_OPERATIONS).sort()).toEqual(
|
||||||
|
[...COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.keys()].sort(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import {
|
|
||||||
composeApiOperations,
|
|
||||||
defineRestOperation,
|
|
||||||
type RestOperationV2,
|
|
||||||
} from "../../src/contracts/api-operations.ts";
|
|
||||||
import { API_OPERATIONS } from "../../src/features/loaded-feature-runtimes.ts";
|
|
||||||
|
|
||||||
function operation(operationId = "GET_RESOURCE") {
|
|
||||||
return defineRestOperation({
|
|
||||||
contractVersion: 2,
|
|
||||||
protocol: "REST",
|
|
||||||
semantics: "QUERY",
|
|
||||||
method: "GET",
|
|
||||||
path: "/resources/{resourceId}",
|
|
||||||
operationId,
|
|
||||||
auth: "external-session",
|
|
||||||
timeoutMs: 5_000,
|
|
||||||
idempotency: "safe",
|
|
||||||
retry: "runtime",
|
|
||||||
replayPolicy: "SAFE",
|
|
||||||
idempotencyKeyPolicy: "NONE",
|
|
||||||
requestSource: "none",
|
|
||||||
requestSchema: "NoRequest",
|
|
||||||
responseSchema: "ResourcePayload",
|
|
||||||
mapperId: "ResourceMapper",
|
|
||||||
successStatuses: [200],
|
|
||||||
responseMediaTypes: ["application/json"],
|
|
||||||
maxResponseBytes: 32_768,
|
|
||||||
providerId: "PRIMARY_API",
|
|
||||||
authProfileId: "EXTERNAL_BEARER",
|
|
||||||
csrfProfileId: "NO_CSRF_BEARER",
|
|
||||||
pathSchema: "ResourceParams",
|
|
||||||
pathParameterNames: ["resourceId"],
|
|
||||||
maxEncodedSearchBytes: 0,
|
|
||||||
owner: "test",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("REST operation v2 registry", () => {
|
|
||||||
it("rejects duplicate contributions before an object spread can overwrite them", () => {
|
|
||||||
const selected = operation();
|
|
||||||
expect(() =>
|
|
||||||
composeApiOperations([
|
|
||||||
{ GET_RESOURCE: selected },
|
|
||||||
{ GET_RESOURCE: selected },
|
|
||||||
]),
|
|
||||||
).toThrow("Duplicate API operation");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("rejects an unsafe query/replay policy combination", () => {
|
|
||||||
expect(() =>
|
|
||||||
defineRestOperation({
|
|
||||||
...operation(),
|
|
||||||
method: "POST",
|
|
||||||
}),
|
|
||||||
).toThrow("Incoherent REST replay contract");
|
|
||||||
});
|
|
||||||
|
|
||||||
// 07-06 (MX5). A KEYED command without a required idempotency key would be
|
|
||||||
// resent with no key to bind the retry to.
|
|
||||||
it("rejects a KEYED_COMMAND whose idempotency key is not required", () => {
|
|
||||||
expect(() =>
|
|
||||||
defineRestOperation({ ...command(), idempotencyKeyPolicy: "NONE" }),
|
|
||||||
).toThrow("Incoherent REST replay contract: CREATE_RESOURCE");
|
|
||||||
expect(defineRestOperation(command()).idempotencyKeyPolicy).toBe("REQUIRED");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
function command(): RestOperationV2 {
|
|
||||||
return {
|
|
||||||
...operation(),
|
|
||||||
semantics: "COMMAND",
|
|
||||||
method: "POST",
|
|
||||||
path: "/resources",
|
|
||||||
operationId: "CREATE_RESOURCE",
|
|
||||||
idempotency: "keyed",
|
|
||||||
replayPolicy: "KEYED_COMMAND",
|
|
||||||
idempotencyKeyPolicy: "REQUIRED",
|
|
||||||
requestSource: "body",
|
|
||||||
pathSchema: "NoRequest",
|
|
||||||
pathParameterNames: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* R-7.4. CSRF protection is chosen from the HTTP method, so a COMMAND sent
|
|
||||||
* as GET/HEAD would skip it. browser-rpc and the V3 composition already bind
|
|
||||||
* commands to unsafe methods; REST V2 must too.
|
|
||||||
*/
|
|
||||||
describe("REST operation v2 command method and enum rules", () => {
|
|
||||||
it.each(["POST", "PUT", "PATCH", "DELETE"])("accepts a COMMAND sent as %s", (method) => {
|
|
||||||
expect(defineRestOperation({ ...command(), method }).method).toBe(method);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each(["GET", "HEAD", "OPTIONS", "post"])("rejects a COMMAND sent as %s", (method) => {
|
|
||||||
expect(() => defineRestOperation({ ...command(), method })).toThrow(TypeError);
|
|
||||||
expect(() =>
|
|
||||||
composeApiOperations([{ CREATE_RESOURCE: { ...command(), method } }]),
|
|
||||||
).toThrow(TypeError);
|
|
||||||
});
|
|
||||||
|
|
||||||
it.each<[string, Record<string, unknown>]>([
|
|
||||||
["semantics", { semantics: "SUBSCRIBE" }],
|
|
||||||
["replayPolicy", { replayPolicy: "ALWAYS" }],
|
|
||||||
])("rejects an unknown %s value", (_field, patch) => {
|
|
||||||
void _field;
|
|
||||||
const candidate = { ...command(), ...patch } as unknown as RestOperationV2;
|
|
||||||
expect(() => defineRestOperation(candidate)).toThrow(TypeError);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("keeps every installed REST v2 operation valid", () => {
|
|
||||||
for (const installed of Object.values(API_OPERATIONS)) {
|
|
||||||
if (installed.contractVersion !== 2) continue;
|
|
||||||
expect(
|
|
||||||
() => defineRestOperation(installed as RestOperationV2),
|
|
||||||
installed.operationId,
|
|
||||||
).not.toThrow();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { getApiOperation } from "../../src/contracts/api-operations.ts";
|
|
||||||
import { mapWithBoundaryRegistry } from "../../src/contracts/boundary-mapper.ts";
|
import { mapWithBoundaryRegistry } from "../../src/contracts/boundary-mapper.ts";
|
||||||
import {
|
import {
|
||||||
isAllowedOfflineTransition,
|
isAllowedOfflineTransition,
|
||||||
@@ -17,12 +16,6 @@ import { getStorageDefinition } from "../../src/contracts/storage-keys.ts";
|
|||||||
const INHERITED = ["constructor", "__proto__", "toString", "hasOwnProperty"];
|
const INHERITED = ["constructor", "__proto__", "toString", "hasOwnProperty"];
|
||||||
|
|
||||||
describe("registry lookups ignore inherited keys", () => {
|
describe("registry lookups ignore inherited keys", () => {
|
||||||
it("getApiOperation", () => {
|
|
||||||
for (const id of INHERITED) {
|
|
||||||
expect(() => getApiOperation(id), id).toThrow("Unregistered API operation");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
it("getStorageDefinition", () => {
|
it("getStorageDefinition", () => {
|
||||||
for (const id of INHERITED) {
|
for (const id of INHERITED) {
|
||||||
expect(() => getStorageDefinition(id), id).toThrow(
|
expect(() => getStorageDefinition(id), id).toThrow(
|
||||||
|
|||||||
@@ -1,97 +0,0 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
|
||||||
|
|
||||||
import type {
|
|
||||||
ApiOperation,
|
|
||||||
RestOperationV2,
|
|
||||||
} from "../../src/contracts/api-operations.ts";
|
|
||||||
import {
|
|
||||||
API_OPERATIONS,
|
|
||||||
INSTALLED_CONTRACT_CONTRIBUTIONS,
|
|
||||||
} from "../../src/features/loaded-feature-runtimes.ts";
|
|
||||||
|
|
||||||
// 07-03 (D-7), 07-02. FE-REG-API governs the V2 rows while the V3 descriptors
|
|
||||||
// are what executes. Until V2 is generated from V3, both copies must agree.
|
|
||||||
const RETRY_SEMANTICS_FOR_REPLAY_POLICY = Object.freeze({
|
|
||||||
SAFE: "SAFE",
|
|
||||||
IDEMPOTENT: "IDEMPOTENT",
|
|
||||||
KEYED_COMMAND: "KEYED",
|
|
||||||
NON_REPLAYABLE: "NEVER",
|
|
||||||
} as const);
|
|
||||||
|
|
||||||
const v3ByOperationId = new Map(
|
|
||||||
INSTALLED_CONTRACT_CONTRIBUTIONS.flatMap((contribution) =>
|
|
||||||
contribution.http.map(
|
|
||||||
(descriptor) => [descriptor.contract.operationId, descriptor] as const,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
const v2Rows = (Object.values(API_OPERATIONS) as readonly ApiOperation[]).filter(
|
|
||||||
(operation): operation is RestOperationV2 => operation.contractVersion === 2,
|
|
||||||
);
|
|
||||||
|
|
||||||
// V3 validates the whole canonical input with one schema; V2 splits it into a
|
|
||||||
// path schema and a request (search or body) schema. The row says which of
|
|
||||||
// the two carry input: path parameters, and a request source other than
|
|
||||||
// "none". The other one names the feature's empty-input schema, whatever the
|
|
||||||
// feature calls it (schema ids are global, so a second feature cannot reuse
|
|
||||||
// the sample's `NoRequest`). An operation that needs both has no rule yet and
|
|
||||||
// fails here until one is written down.
|
|
||||||
function v2InputSchema(row: RestOperationV2): string {
|
|
||||||
const declared = [
|
|
||||||
...(row.pathParameterNames.length > 0 ? [row.pathSchema] : []),
|
|
||||||
...(row.requestSource !== "none" ? [row.requestSchema] : []),
|
|
||||||
];
|
|
||||||
expect(
|
|
||||||
declared.length,
|
|
||||||
`${row.operationId}: V2 declares both a path and a request schema; decide which V3 input schema matches them`,
|
|
||||||
).toBeLessThanOrEqual(1);
|
|
||||||
return declared[0] ?? row.requestSchema;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("HTTP operation V2 rows and V3 descriptors", () => {
|
|
||||||
// 07-02. Both directions: a V3-only operation executes outside the
|
|
||||||
// FE-REG-API gate, a V2-only one is governed but never executes. With the
|
|
||||||
// sample feature removed both sets are empty, which is why there is no
|
|
||||||
// "at least one row" assertion (test:sample-removal runs this file).
|
|
||||||
it("cover the same operations", () => {
|
|
||||||
expect([...v3ByOperationId.keys()].sort(), "V3 descriptors").toEqual(
|
|
||||||
v2Rows.map((row) => row.operationId).sort(),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("declare the same method, path, statuses, limit, auth profile, replay policy, write semantics, request body and schema ids", () => {
|
|
||||||
for (const row of v2Rows) {
|
|
||||||
const descriptor = v3ByOperationId.get(row.operationId);
|
|
||||||
expect(descriptor, `${row.operationId} has no V3 descriptor`).toBeDefined();
|
|
||||||
if (!descriptor) continue;
|
|
||||||
expect(
|
|
||||||
{
|
|
||||||
method: descriptor.contract.method,
|
|
||||||
path: descriptor.contract.pathTemplate,
|
|
||||||
successStatuses: [...descriptor.contract.acceptedStatuses],
|
|
||||||
maxResponseBytes: descriptor.frontend.responseByteLimit,
|
|
||||||
authProfileId: descriptor.frontend.authProfileId,
|
|
||||||
retrySemantics: descriptor.contract.retrySemantics,
|
|
||||||
// The executor treats an operation as a write by its effect
|
|
||||||
// descriptor, not by its method.
|
|
||||||
semantics: descriptor.contract.commandEffect === null ? "QUERY" : "COMMAND",
|
|
||||||
requestBody: descriptor.contract.requestBody,
|
|
||||||
inputSchema: descriptor.contract.inputValidator.schemaId,
|
|
||||||
responseSchema: descriptor.contract.outputValidator.schemaId,
|
|
||||||
},
|
|
||||||
row.operationId,
|
|
||||||
).toEqual({
|
|
||||||
method: row.method,
|
|
||||||
path: row.path,
|
|
||||||
successStatuses: [...row.successStatuses],
|
|
||||||
maxResponseBytes: row.maxResponseBytes,
|
|
||||||
authProfileId: row.authProfileId,
|
|
||||||
retrySemantics: RETRY_SEMANTICS_FOR_REPLAY_POLICY[row.replayPolicy],
|
|
||||||
semantics: row.semantics,
|
|
||||||
requestBody: row.requestSource === "body" ? "JSON" : "NONE",
|
|
||||||
inputSchema: v2InputSchema(row),
|
|
||||||
responseSchema: row.responseSchema,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -2,7 +2,7 @@ import {
|
|||||||
mappingSuccess,
|
mappingSuccess,
|
||||||
type InstalledBoundaryMapper,
|
type InstalledBoundaryMapper,
|
||||||
} from "../../../src/contracts/boundary-mapper.ts";
|
} from "../../../src/contracts/boundary-mapper.ts";
|
||||||
import type { ApiOperation } from "../../../src/contracts/api-operations.ts";
|
import type { ApiOperationRow } from "../../../src/contracts/api-operations.ts";
|
||||||
import {
|
import {
|
||||||
createRealtimePolicyRegistry,
|
createRealtimePolicyRegistry,
|
||||||
defineEventTypeId,
|
defineEventTypeId,
|
||||||
@@ -102,33 +102,19 @@ export const TEST_MAPPERS = Object.freeze({
|
|||||||
ReferenceRealtimeMapper: TEST_MAPPER,
|
ReferenceRealtimeMapper: TEST_MAPPER,
|
||||||
});
|
});
|
||||||
|
|
||||||
const snapshotOperation: ApiOperation = Object.freeze({
|
const snapshotOperation: ApiOperationRow = Object.freeze({
|
||||||
|
operationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
|
||||||
|
featureId: "sample-feature",
|
||||||
method: "GET",
|
method: "GET",
|
||||||
path: "/api/reference-snapshot",
|
path: "/api/reference-snapshot",
|
||||||
operationId: "GET_REFERENCE_REALTIME_SNAPSHOT",
|
authProfileId: "EXTERNAL_BEARER",
|
||||||
auth: "external-session",
|
retrySemantics: "SAFE",
|
||||||
timeoutMs: 10_000,
|
requestBody: "NONE",
|
||||||
idempotency: "safe",
|
responseBody: "REQUIRED_JSON",
|
||||||
retry: "never",
|
responseEnvelope: "NONE",
|
||||||
requestSource: "none",
|
|
||||||
requestSchema: "NoRequest",
|
requestSchema: "NoRequest",
|
||||||
responseSchema: "ReferenceRealtimeCheckpoint",
|
responseSchema: "ReferenceRealtimeCheckpoint",
|
||||||
owner: "sample-owner",
|
problemSchema: "ReferenceRealtimeProblem",
|
||||||
contractVersion: 2,
|
|
||||||
protocol: "REST",
|
|
||||||
semantics: "QUERY",
|
|
||||||
replayPolicy: "SAFE",
|
|
||||||
idempotencyKeyPolicy: "NONE",
|
|
||||||
mapperId: "ReferenceRealtimeSnapshotMapper",
|
|
||||||
successStatuses: [200],
|
|
||||||
responseMediaTypes: ["application/json"],
|
|
||||||
maxResponseBytes: 16_384,
|
|
||||||
providerId: "PRIMARY_API",
|
|
||||||
authProfileId: "EXTERNAL_SESSION",
|
|
||||||
csrfProfileId: "NONE",
|
|
||||||
pathSchema: "NoRequest",
|
|
||||||
pathParameterNames: [],
|
|
||||||
maxEncodedSearchBytes: 0,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const TEST_API_OPERATIONS = Object.freeze({
|
export const TEST_API_OPERATIONS = Object.freeze({
|
||||||
|
|||||||
@@ -3,177 +3,32 @@ import path from "node:path";
|
|||||||
|
|
||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
import { defineRestOperation } from "../../src/contracts/api-operations.ts";
|
|
||||||
import {
|
import {
|
||||||
composeContractContributions,
|
composeContractContributions,
|
||||||
ContractContributionError,
|
ContractContributionError,
|
||||||
} from "../../src/contracts/external-contract-runtime.ts";
|
} from "../../src/contracts/external-contract-runtime.ts";
|
||||||
import {
|
import {
|
||||||
createRestProviderProfile,
|
|
||||||
INSTALLED_REST_AUTH_PROFILES,
|
INSTALLED_REST_AUTH_PROFILES,
|
||||||
installRestAuthProfileRegistry,
|
installRestAuthProfileRegistry,
|
||||||
resolveRestSecurityProfiles,
|
|
||||||
REST_AUTH_PROFILES,
|
REST_AUTH_PROFILES,
|
||||||
validateRestProfileBindings,
|
|
||||||
} from "../../src/contracts/rest-profiles.ts";
|
} from "../../src/contracts/rest-profiles.ts";
|
||||||
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
|
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
|
||||||
|
|
||||||
/**
|
|
||||||
* §24.12: the common REST profile contract must stay independently verifiable
|
|
||||||
* after the sample feature is removed, so this suite owns its own operation
|
|
||||||
* fixture instead of importing an installed feature contract.
|
|
||||||
*/
|
|
||||||
const SAMPLE_COMMAND = defineRestOperation({
|
|
||||||
method: "POST",
|
|
||||||
path: "/api/sample-resources",
|
|
||||||
operationId: "CREATE_SAMPLE_RESOURCE",
|
|
||||||
auth: "external-session",
|
|
||||||
timeoutMs: null,
|
|
||||||
idempotency: "keyed",
|
|
||||||
retry: "runtime",
|
|
||||||
requestSource: "body",
|
|
||||||
requestSchema: "SampleCommand",
|
|
||||||
responseSchema: "SamplePayload",
|
|
||||||
owner: "platform-test-fixture",
|
|
||||||
contractVersion: 2,
|
|
||||||
protocol: "REST",
|
|
||||||
semantics: "COMMAND",
|
|
||||||
replayPolicy: "KEYED_COMMAND",
|
|
||||||
idempotencyKeyPolicy: "REQUIRED",
|
|
||||||
mapperId: "SampleMapper",
|
|
||||||
successStatuses: [200, 201],
|
|
||||||
responseMediaTypes: ["application/json"],
|
|
||||||
maxResponseBytes: 32_768,
|
|
||||||
providerId: "PRIMARY_API",
|
|
||||||
authProfileId: "EXTERNAL_BEARER",
|
|
||||||
csrfProfileId: "NO_CSRF_BEARER",
|
|
||||||
pathSchema: "NoRequest",
|
|
||||||
pathParameterNames: [],
|
|
||||||
maxEncodedSearchBytes: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
const SAMPLE_OPERATIONS = Object.freeze({
|
|
||||||
CREATE_SAMPLE_RESOURCE: SAMPLE_COMMAND,
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("REST provider/auth/CSRF profiles", () => {
|
|
||||||
it("preserves the provider prefix and rejects unsafe endpoint forms", () => {
|
|
||||||
expect(
|
|
||||||
createRestProviderProfile(
|
|
||||||
"PRIMARY_API",
|
|
||||||
"https://api.test/base/",
|
|
||||||
["omit"],
|
|
||||||
),
|
|
||||||
).toMatchObject({
|
|
||||||
providerId: "PRIMARY_API",
|
|
||||||
baseUrl: "https://api.test/base/",
|
|
||||||
redirect: "error",
|
|
||||||
referrerPolicy: "no-referrer",
|
|
||||||
});
|
|
||||||
expect(() =>
|
|
||||||
createRestProviderProfile(
|
|
||||||
"PRIMARY_API",
|
|
||||||
"https://user:password@api.test/base/",
|
|
||||||
),
|
|
||||||
).toThrow("Invalid REST provider profile");
|
|
||||||
expect(() =>
|
|
||||||
createRestProviderProfile("PRIMARY_API", "http://api.test/base/"),
|
|
||||||
).toThrow("Invalid REST provider profile");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("resolves bearer auth to omit credentials and no CSRF", () => {
|
|
||||||
const resolved = resolveRestSecurityProfiles(
|
|
||||||
SAMPLE_COMMAND,
|
|
||||||
createRestProviderProfile("PRIMARY_API", "https://api.test", ["omit"]),
|
|
||||||
);
|
|
||||||
expect(resolved).toMatchObject({
|
|
||||||
auth: {
|
|
||||||
transport: "BEARER_HEADER",
|
|
||||||
credentials: "omit",
|
|
||||||
allowedCredentialHeaders: ["authorization"],
|
|
||||||
},
|
|
||||||
csrf: { mode: "NONE" },
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("validates every installed profile binding as a set", () => {
|
|
||||||
expect(
|
|
||||||
validateRestProfileBindings(SAMPLE_OPERATIONS, {
|
|
||||||
PRIMARY_API: ["omit"],
|
|
||||||
}),
|
|
||||||
).toBe(true);
|
|
||||||
expect(() =>
|
|
||||||
validateRestProfileBindings(SAMPLE_OPERATIONS, {}),
|
|
||||||
).toThrow("Unregistered REST provider binding");
|
|
||||||
});
|
|
||||||
|
|
||||||
// 16-03. A copied feature that renamed the sample's profile id stopped every
|
|
||||||
// gate with one sentence that named neither the operation nor the profile.
|
|
||||||
it("names the operation, the profile and the broken condition", () => {
|
|
||||||
const renamed = Object.freeze({
|
|
||||||
CREATE_SAMPLE_RESOURCE: {
|
|
||||||
...SAMPLE_COMMAND,
|
|
||||||
authProfileId: "ORDER_EXTERNAL_BEARER",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
expect(() =>
|
|
||||||
validateRestProfileBindings(renamed, { PRIMARY_API: ["omit"] }),
|
|
||||||
).toThrow(
|
|
||||||
/incoherent.*CREATE_SAMPLE_RESOURCE.*unknown authProfileId ORDER_EXTERNAL_BEARER/,
|
|
||||||
);
|
|
||||||
|
|
||||||
const publicWithBearer = Object.freeze({
|
|
||||||
CREATE_SAMPLE_RESOURCE: { ...SAMPLE_COMMAND, auth: "none" as const },
|
|
||||||
});
|
|
||||||
expect(() =>
|
|
||||||
validateRestProfileBindings(publicWithBearer, { PRIMARY_API: ["omit"] }),
|
|
||||||
).toThrow(
|
|
||||||
/CREATE_SAMPLE_RESOURCE.*auth "none" needs an ANONYMOUS profile.*EXTERNAL_BEARER is BEARER_HEADER/,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Q-6.7-9. Composition, the V3 executor and the V2 resolve must all answer
|
|
||||||
* from one validated installed registry. A raw record handed to resolve used
|
|
||||||
* to skip installation, so a bearer profile with ambient credentials passed.
|
|
||||||
*/
|
|
||||||
describe("one installed REST auth profile registry", () => {
|
describe("one installed REST auth profile registry", () => {
|
||||||
const provider = createRestProviderProfile("PRIMARY_API", "https://api.test", [
|
it("refuses a raw profile record that is incoherent", () => {
|
||||||
"omit",
|
|
||||||
"same-origin",
|
|
||||||
]);
|
|
||||||
|
|
||||||
it("rejects a raw profile record that installation would refuse", () => {
|
|
||||||
const incoherent = {
|
|
||||||
EXTERNAL_BEARER: {
|
|
||||||
...REST_AUTH_PROFILES.EXTERNAL_BEARER,
|
|
||||||
credentials: "same-origin" as const,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
expect(() =>
|
expect(() =>
|
||||||
resolveRestSecurityProfiles(SAMPLE_COMMAND, provider, incoherent),
|
installRestAuthProfileRegistry({
|
||||||
|
EXTERNAL_BEARER: {
|
||||||
|
...REST_AUTH_PROFILES.EXTERNAL_BEARER,
|
||||||
|
credentials: "same-origin" as const,
|
||||||
|
},
|
||||||
|
}),
|
||||||
).toThrow(TypeError);
|
).toThrow(TypeError);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("resolves through the installed registry", () => {
|
it("does not answer for an inherited profile id", () => {
|
||||||
expect(
|
expect(INSTALLED_REST_AUTH_PROFILES.has("toString")).toBe(false);
|
||||||
resolveRestSecurityProfiles(
|
expect(INSTALLED_REST_AUTH_PROFILES.get("toString")).toBeUndefined();
|
||||||
SAMPLE_COMMAND,
|
|
||||||
provider,
|
|
||||||
INSTALLED_REST_AUTH_PROFILES,
|
|
||||||
).auth,
|
|
||||||
).toBe(INSTALLED_REST_AUTH_PROFILES.get("EXTERNAL_BEARER"));
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not resolve an inherited profile id", () => {
|
|
||||||
expect(() =>
|
|
||||||
resolveRestSecurityProfiles(
|
|
||||||
{ ...SAMPLE_COMMAND, authProfileId: "toString" },
|
|
||||||
provider,
|
|
||||||
REST_AUTH_PROFILES,
|
|
||||||
),
|
|
||||||
).toThrow("incoherent");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("composes contributions against the registry it is given", () => {
|
it("composes contributions against the registry it is given", () => {
|
||||||
|
|||||||
@@ -23,13 +23,18 @@ const FEATURE_ID = "second-api-feature";
|
|||||||
const CONTEXT_ID = "second-api-context";
|
const CONTEXT_ID = "second-api-context";
|
||||||
const TOPIC_ID = "qinv.01kb3m8q2v6t4r9s1n5p7c0w";
|
const TOPIC_ID = "qinv.01kb3m8q2v6t4r9s1n5p7c0w";
|
||||||
|
|
||||||
const FEATURE_CONTRACT = `import { defineRestOperation } from "../../../contracts/api-operations.ts";
|
const FEATURE_CONTRACT = `import {
|
||||||
import type { InstalledBoundaryMapper } from "../../../contracts/boundary-mapper.ts";
|
PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,
|
||||||
import { mappingFailure, mappingSuccess } from "../../../contracts/boundary-mapper.ts";
|
PLACEHOLDER_CONTRACT_PACKAGE_REVISION,
|
||||||
|
PLACEHOLDER_CONTRACT_PACKAGE_VERSION,
|
||||||
|
} from "../../../contracts/deployment-admission.ts";
|
||||||
|
import type {
|
||||||
|
InstalledContractContribution,
|
||||||
|
InstalledHttpContract,
|
||||||
|
} from "../../../contracts/external-contract-runtime.ts";
|
||||||
import { unvalidatedPayload } from "../../../contracts/unvalidated-payload.ts";
|
import { unvalidatedPayload } from "../../../contracts/unvalidated-payload.ts";
|
||||||
import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts";
|
import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts";
|
||||||
import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts";
|
import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts";
|
||||||
import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
|
|
||||||
|
|
||||||
const OWNER = "feature-frontend-second-api-feature";
|
const OWNER = "feature-frontend-second-api-feature";
|
||||||
const SECOND_ITEM_TOPIC = defineQueryInvalidationTopic("${TOPIC_ID}");
|
const SECOND_ITEM_TOPIC = defineQueryInvalidationTopic("${TOPIC_ID}");
|
||||||
@@ -38,10 +43,16 @@ const SECOND_ITEM_NAMESPACE = defineQueryNamespaceIdentity("second-item", 1);
|
|||||||
const schema = (schemaId: string, boundary: string, direction: string) =>
|
const schema = (schemaId: string, boundary: string, direction: string) =>
|
||||||
Object.freeze({ schemaId, boundary, owner: OWNER, runtime: "zod", schemaVersion: 1, direction });
|
Object.freeze({ schemaId, boundary, owner: OWNER, runtime: "zod", schemaVersion: 1, direction });
|
||||||
|
|
||||||
const codec = (schemaId: string) =>
|
const unchecked = (schemaId: string) =>
|
||||||
runtimeSchemaCodecFromValidator(
|
unvalidatedPayload(schemaId, "registry fixture: only check-registries reads it");
|
||||||
unvalidatedPayload(schemaId, "registry fixture: only check-registries reads it"),
|
|
||||||
);
|
const SECOND_CONTRACT_PACKAGE = Object.freeze({
|
||||||
|
packageId: "@org-contracts/second-api",
|
||||||
|
version: PLACEHOLDER_CONTRACT_PACKAGE_VERSION,
|
||||||
|
digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,
|
||||||
|
runtimeProtocolVersion: 1 as const,
|
||||||
|
sourceRevision: PLACEHOLDER_CONTRACT_PACKAGE_REVISION,
|
||||||
|
});
|
||||||
|
|
||||||
const ROUTES = Object.freeze({
|
const ROUTES = Object.freeze({
|
||||||
SECOND_ITEM_LIST: Object.freeze({
|
SECOND_ITEM_LIST: Object.freeze({
|
||||||
@@ -81,66 +92,57 @@ export const SECOND_API_CONTRACT = Object.freeze({
|
|||||||
topicVersions: Object.freeze([
|
topicVersions: Object.freeze([
|
||||||
Object.freeze({ topicId: SECOND_ITEM_TOPIC, topicVersion: 1 }),
|
Object.freeze({ topicId: SECOND_ITEM_TOPIC, topicVersion: 1 }),
|
||||||
]),
|
]),
|
||||||
contractPackages: Object.freeze([]),
|
contractPackages: Object.freeze([SECOND_CONTRACT_PACKAGE]),
|
||||||
} as const);
|
} as const);
|
||||||
|
|
||||||
// Runtime half: the V2 API contract, loaded with feature-runtime.ts.
|
// Runtime half, loaded with feature-runtime.ts.
|
||||||
export const SECOND_API_V2_CONTRACT = Object.freeze({
|
export const SECOND_API_SCHEMAS = Object.freeze({
|
||||||
apiOperations: Object.freeze({
|
SecondItemListQuery: schema("SecondItemListQuery", "route-search", "REQUEST"),
|
||||||
GET_SECOND_ITEM: defineRestOperation({
|
SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"),
|
||||||
method: "GET",
|
SecondItemPayload: schema("SecondItemPayload", "api-response", "RESPONSE"),
|
||||||
path: "/api/second-items/{itemId}",
|
|
||||||
operationId: "GET_SECOND_ITEM",
|
|
||||||
auth: "none",
|
|
||||||
timeoutMs: null,
|
|
||||||
idempotency: "safe",
|
|
||||||
retry: "runtime",
|
|
||||||
requestSource: "none",
|
|
||||||
requestSchema: "SecondItemRequest",
|
|
||||||
responseSchema: "SecondItemPayload",
|
|
||||||
owner: OWNER,
|
|
||||||
contractVersion: 2,
|
|
||||||
protocol: "REST",
|
|
||||||
semantics: "QUERY",
|
|
||||||
replayPolicy: "SAFE",
|
|
||||||
idempotencyKeyPolicy: "NONE",
|
|
||||||
mapperId: "SecondItemMapper",
|
|
||||||
successStatuses: [200],
|
|
||||||
responseMediaTypes: ["application/json"],
|
|
||||||
maxResponseBytes: 16_384,
|
|
||||||
providerId: "PRIMARY_API",
|
|
||||||
authProfileId: "ANONYMOUS",
|
|
||||||
csrfProfileId: "NO_CSRF_BEARER",
|
|
||||||
pathSchema: "SecondItemParams",
|
|
||||||
pathParameterNames: ["itemId"],
|
|
||||||
maxEncodedSearchBytes: 0,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
schemas: Object.freeze({
|
|
||||||
SecondItemListQuery: schema("SecondItemListQuery", "route-search", "REQUEST"),
|
|
||||||
SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"),
|
|
||||||
SecondItemRequest: schema("SecondItemRequest", "api-request", "REQUEST"),
|
|
||||||
SecondItemPayload: schema("SecondItemPayload", "api-response", "RESPONSE"),
|
|
||||||
}),
|
|
||||||
runtimeSchemas: Object.freeze({
|
|
||||||
SecondItemListQuery: codec("SecondItemListQuery"),
|
|
||||||
SecondItemParams: codec("SecondItemParams"),
|
|
||||||
SecondItemRequest: codec("SecondItemRequest"),
|
|
||||||
SecondItemPayload: codec("SecondItemPayload"),
|
|
||||||
}),
|
|
||||||
mappers: Object.freeze({
|
|
||||||
SecondItemMapper: Object.freeze({
|
|
||||||
mapperId: "SecondItemMapper",
|
|
||||||
mapperVersion: 1,
|
|
||||||
inputSchemaId: "SecondItemPayload",
|
|
||||||
outputContractId: "SecondItem",
|
|
||||||
owner: OWNER,
|
|
||||||
maxOutputItems: 1,
|
|
||||||
map: (value: unknown) =>
|
|
||||||
value && typeof value === "object" ? mappingSuccess(value) : mappingFailure("MAPPING_INVARIANT_REJECTED"),
|
|
||||||
} satisfies InstalledBoundaryMapper),
|
|
||||||
}),
|
|
||||||
} as const);
|
} as const);
|
||||||
|
|
||||||
|
export const SECOND_API_CONTRIBUTION: InstalledContractContribution = Object.freeze({
|
||||||
|
contributionId: "second-api-feature-http-v1",
|
||||||
|
featureId: "${FEATURE_ID}",
|
||||||
|
source: Object.freeze({ kind: "EXTERNAL_PACKAGE" as const, package: SECOND_CONTRACT_PACKAGE }),
|
||||||
|
http: Object.freeze([
|
||||||
|
Object.freeze({
|
||||||
|
contract: Object.freeze({
|
||||||
|
operationId: "GET_SECOND_ITEM",
|
||||||
|
method: "GET" as const,
|
||||||
|
pathTemplate: "/api/second-items/{itemId}",
|
||||||
|
inputValidator: unchecked("SecondItemParams"),
|
||||||
|
outputValidator: unchecked("SecondItemPayload"),
|
||||||
|
problemValidator: unchecked("SecondItemProblem"),
|
||||||
|
acceptedStatuses: Object.freeze([200]),
|
||||||
|
emptyBodyStatuses: Object.freeze([]),
|
||||||
|
retrySemantics: "SAFE" as const,
|
||||||
|
requestBody: "NONE" as const,
|
||||||
|
responseBody: "REQUIRED_JSON" as const,
|
||||||
|
responseEnvelope: "ENVELOPE_V1" as const,
|
||||||
|
commandRecovery: null,
|
||||||
|
commandEffect: null,
|
||||||
|
projectRequest: (input: unknown) =>
|
||||||
|
Object.freeze({
|
||||||
|
pathValues: Object.freeze({ itemId: String((input as { itemId: string }).itemId) }),
|
||||||
|
queryEntries: Object.freeze([]),
|
||||||
|
body: null,
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
frontend: Object.freeze({
|
||||||
|
policyId: "SECOND_ITEM_V1",
|
||||||
|
requestByteLimit: 0,
|
||||||
|
responseByteLimit: 16_384,
|
||||||
|
totalDeadlineMs: 10_000,
|
||||||
|
retryBudget: 0 as const,
|
||||||
|
authProfileId: "ANONYMOUS",
|
||||||
|
diagnosticsOperation: "second.item",
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
|
||||||
|
events: Object.freeze([]),
|
||||||
|
});
|
||||||
`;
|
`;
|
||||||
|
|
||||||
const FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts";
|
const FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts";
|
||||||
@@ -159,13 +161,16 @@ export const FEATURE_MODULE = defineFeatureModule({
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
const FEATURE_RUNTIME = `import { defineFeatureRuntime } from "../feature-module.ts";
|
const FEATURE_RUNTIME = `import { defineFeatureRuntime } from "../feature-module.ts";
|
||||||
import { SECOND_API_V2_CONTRACT } from "./contracts/second-api-contract.ts";
|
import {
|
||||||
|
SECOND_API_CONTRIBUTION,
|
||||||
|
SECOND_API_SCHEMAS,
|
||||||
|
} from "./contracts/second-api-contract.ts";
|
||||||
|
|
||||||
export const FEATURE_RUNTIME = defineFeatureRuntime({
|
export const FEATURE_RUNTIME = defineFeatureRuntime({
|
||||||
featureId: "${FEATURE_ID}",
|
featureId: "${FEATURE_ID}",
|
||||||
apiContract: SECOND_API_V2_CONTRACT,
|
schemas: SECOND_API_SCHEMAS,
|
||||||
adapters: [],
|
adapters: [],
|
||||||
contractContributions: [],
|
contractContributions: [SECOND_API_CONTRIBUTION],
|
||||||
} as const);
|
} as const);
|
||||||
`;
|
`;
|
||||||
|
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ declare module "../../application/ports/in/application-api.ts" {
|
|||||||
|
|
||||||
export const FEATURE_RUNTIME = defineFeatureRuntime({
|
export const FEATURE_RUNTIME = defineFeatureRuntime({
|
||||||
featureId: "second-feature",
|
featureId: "second-feature",
|
||||||
apiContract: { apiOperations: {}, schemas: {}, runtimeSchemas: {}, mappers: {} },
|
schemas: {},
|
||||||
adapters: [
|
adapters: [
|
||||||
defineFeatureAdapterContribution({
|
defineFeatureAdapterContribution({
|
||||||
featureId: "second-feature",
|
featureId: "second-feature",
|
||||||
@@ -126,7 +126,7 @@ export const FEATURE_MODULE = defineFeatureModule({
|
|||||||
messages: { "ko-KR": MESSAGES, "en-US": MESSAGES },
|
messages: { "ko-KR": MESSAGES, "en-US": MESSAGES },
|
||||||
loadRuntime: async () => ({
|
loadRuntime: async () => ({
|
||||||
featureId: FEATURE_MODULE_ID,
|
featureId: FEATURE_MODULE_ID,
|
||||||
apiContract: { apiOperations: {}, schemas: {}, runtimeSchemas: {}, mappers: {} },
|
schemas: {},
|
||||||
adapters: [],
|
adapters: [],
|
||||||
contractContributions: [],
|
contractContributions: [],
|
||||||
}),
|
}),
|
||||||
|
|||||||
Reference in New Issue
Block a user