From 56de543d492d315cf68daa4426e2d21c2dd00bde Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 24 Sep 2026 13:27:13 +0900 Subject: [PATCH] refactor(contracts): make the external-contract-runtime shapes canonical (Q-6.7-8) D-15. `RuntimeValidator` and `MappingResult` in external-contract-runtime.ts are the canonical validator protocol and mapping result. The other shapes stay as public names over them: - schema-registry.ts: `RuntimeSchemaCodec` is documented as the registry adapter and gains `runtimeSchemaCodecFromValidator`. - boundary-mapper.ts: the flat `{ ok: false, code }` result is named `BoundaryMappingResult`; `MappingResult` stays as an alias, and `toContractMappingResult` converts to the canonical shape. The reference feature wrapped each zod schema twice (a RuntimeValidator in the contract contribution and a separate `project`/`codec` in reference-schemas.ts). It now has one `zodValidator`; the registry codecs are a one-liner over it, and validateReferencePayload/Request look up the codec with Object.hasOwn. Verified: characterization test tests/features/reference-feature/reference-validator-protocol.test.ts passed before and after (array paths, dotted paths, codec ids, SCHEMA_NOT_REGISTERED); adapter case added to boundary-mapper.test.ts; gates green except the known removal-fixture test. Co-Authored-By: Claude Opus 5.5 --- src/contracts/boundary-mapper.ts | 26 +++++- src/contracts/external-contract-runtime.ts | 5 ++ src/contracts/schema-registry.ts | 27 ++++++ ...reference-feature-contract-contribution.ts | 35 +------- .../contracts/reference-schemas.ts | 83 +++++++++++------ .../reference-validator-protocol.test.ts | 88 +++++++++++++++++++ tests/unit/boundary-mapper.test.ts | 13 +++ 7 files changed, 217 insertions(+), 60 deletions(-) create mode 100644 tests/features/reference-feature/reference-validator-protocol.test.ts diff --git a/src/contracts/boundary-mapper.ts b/src/contracts/boundary-mapper.ts index a6b97576..f53f91f5 100644 --- a/src/contracts/boundary-mapper.ts +++ b/src/contracts/boundary-mapper.ts @@ -1,12 +1,36 @@ +import type { MappingResult as ContractMappingResult } from "./external-contract-runtime.ts"; + export type MappingFailureCode = | "MAPPING_INVARIANT_REJECTED" | "UNSUPPORTED_WIRE_VALUE" | "OUTPUT_LIMIT_EXCEEDED"; -export type MappingResult = +/** + * D-15. The boundary mapper's own result: a flat failure `code`. The canonical + * mapping result is `MappingResult` in `external-contract-runtime.ts` + * (`error: { kind, code }`); convert with `toContractMappingResult`. + */ +export type BoundaryMappingResult = | Readonly<{ ok: true; value: Value }> | Readonly<{ ok: false; code: MappingFailureCode }>; +/** Compatible alias kept for existing importers; see `BoundaryMappingResult`. */ +export type MappingResult = BoundaryMappingResult; + +/** Adapts a boundary mapper result to the canonical contract mapping result. */ +export function toContractMappingResult( + result: BoundaryMappingResult, +): ContractMappingResult { + if (result.ok) return result; + return Object.freeze({ + ok: false as const, + error: Object.freeze({ + kind: "MAPPING_CONTRACT_VIOLATION" as const, + code: result.code, + }), + }); +} + export type BoundaryMapper = Readonly<{ mapperId: string; mapperVersion: number; diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index d951147e..edacd2d3 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -36,6 +36,11 @@ export const HTTP_EXECUTION_CEILINGS = Object.freeze({ finalUrlBytes: 16_384, }); +/* + * D-15. The validator protocol and `MappingResult` below are the canonical + * shapes. `RuntimeSchemaCodec` (`schema-registry.ts`) and the boundary + * mapper's result (`boundary-mapper.ts`) are adapters over them. + */ export type RuntimeValidationIssue = Readonly<{ path: readonly (string | number)[]; code: string; diff --git a/src/contracts/schema-registry.ts b/src/contracts/schema-registry.ts index 2ce68194..4988c31e 100644 --- a/src/contracts/schema-registry.ts +++ b/src/contracts/schema-registry.ts @@ -1,3 +1,4 @@ +import type { RuntimeValidator } from "./external-contract-runtime.ts"; import { projectValidationIssues } from "./validation-issues.ts"; export type SchemaDefinition = Readonly<{ @@ -22,11 +23,37 @@ export type RuntimeSchemaResult = issues: readonly Readonly<{ path: string; code: string }>[]; }>; +/** + * D-15. The registry-facing form of the canonical `RuntimeValidator` + * (`external-contract-runtime.ts`): same `schemaId`, `parse` instead of + * `safeParse`, and dotted string paths. Build one from a validator with + * `runtimeSchemaCodecFromValidator` rather than wrapping a schema twice. + */ export type RuntimeSchemaCodec = Readonly<{ schemaId: string; parse(value: unknown): RuntimeSchemaResult; }>; +export function runtimeSchemaCodecFromValidator( + validator: RuntimeValidator, +): RuntimeSchemaCodec { + return Object.freeze({ + schemaId: validator.schemaId, + parse(value: unknown): RuntimeSchemaResult { + const result = validator.safeParse(value); + if (result.success) return result; + return Object.freeze({ + success: false as const, + issues: Object.freeze( + result.issues.map((issue) => + Object.freeze({ path: issue.path.join("."), code: issue.code }), + ), + ), + }); + }, + }); +} + export function composeRuntimeSchemaCodecs( contributions: readonly Readonly>[], ): Readonly> { diff --git a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts index 48003b2a..48985218 100644 --- a/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts +++ b/src/features/reference-feature/contracts/reference-feature-contract-contribution.ts @@ -4,7 +4,6 @@ import type { CommandEffectDescriptor, InstalledContractContribution, InstalledHttpContract, - RuntimeValidator, } from "../../../contracts/external-contract-runtime.ts"; import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts"; import { @@ -14,6 +13,7 @@ import { referenceResourceListQuerySchema, referenceResourceParamsSchema, type ReferenceProblem, + zodValidator, } from "./reference-schemas.ts"; export type { ReferenceProblem } from "./reference-schemas.ts"; @@ -25,39 +25,6 @@ export type { ReferenceProblem } from "./reference-schemas.ts"; * import it from its own `contracts/-contract-contribution.ts`. */ -function zodValidator( - schemaId: string, - schema: z.ZodType, -): RuntimeValidator { - return Object.freeze({ - schemaId, - safeParse(value: unknown) { - const result = schema.safeParse(value); - if (result.success) { - return Object.freeze({ - success: true as const, - data: structuredClone(result.data), - }); - } - return Object.freeze({ - success: false as const, - issues: Object.freeze( - result.error.issues.map((issue) => - Object.freeze({ - path: Object.freeze( - issue.path.map((segment): string | number => - typeof segment === "number" ? segment : String(segment), - ), - ), - code: String(issue.code), - }), - ), - ), - }); - }, - }); -} - const PROBLEM_VALIDATOR = zodValidator( "ReferenceProblem", referenceProblemSchema, diff --git a/src/features/reference-feature/contracts/reference-schemas.ts b/src/features/reference-feature/contracts/reference-schemas.ts index dff64aad..62372639 100644 --- a/src/features/reference-feature/contracts/reference-schemas.ts +++ b/src/features/reference-feature/contracts/reference-schemas.ts @@ -1,5 +1,6 @@ import { z } from "zod"; -import type { RuntimeSchemaCodec } from "../../../contracts/schema-registry.ts"; +import type { RuntimeValidator } from "../../../contracts/external-contract-runtime.ts"; +import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts"; export const referenceResourceListQuerySchema = z .object({ @@ -67,28 +68,47 @@ const requestSchemas = { CreateReferenceResourceCommand: createReferenceResourceCommandSchema, } satisfies Record; -function project(result: z.ZodSafeParseResult) { - return result.success - ? ({ success: true as const, data: structuredClone(result.data) }) - : ({ - success: false as const, - issues: result.error.issues.map((issue) => ({ - path: issue.path.join("."), - code: issue.code, - })), - }); -} - -function codec( +/** + * D-15. The one zod wrapper: every reference schema is exposed through the + * canonical `RuntimeValidator`, and the registry codecs below are adapters + * over it. + */ +export function zodValidator( schemaId: string, - schema: z.ZodType, -): RuntimeSchemaCodec { + schema: z.ZodType, +): RuntimeValidator { return Object.freeze({ schemaId, - parse: (value: unknown) => project(schema.safeParse(value)), + safeParse(value: unknown) { + const result = schema.safeParse(value); + if (result.success) { + return Object.freeze({ + success: true as const, + data: structuredClone(result.data), + }); + } + return Object.freeze({ + success: false as const, + issues: Object.freeze( + result.error.issues.map((issue) => + Object.freeze({ + path: Object.freeze( + issue.path.map((segment): string | number => + typeof segment === "number" ? segment : String(segment), + ), + ), + code: String(issue.code), + }), + ), + ), + }); + }, }); } +const codec = (schemaId: string, schema: z.ZodType) => + runtimeSchemaCodecFromValidator(zodValidator(schemaId, schema)); + export const REFERENCE_RUNTIME_SCHEMA_CODECS = Object.freeze({ ReferenceResourceParams: codec( "ReferenceResourceParams", @@ -113,16 +133,29 @@ export const REFERENCE_RUNTIME_SCHEMA_CODECS = Object.freeze({ ), }); +const NOT_REGISTERED = Object.freeze({ + success: false as const, + issues: Object.freeze([ + Object.freeze({ path: "", code: "SCHEMA_NOT_REGISTERED" }), + ]), +}); + +function validateOwned( + owned: Readonly>, + 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) { - const schema = payloadSchemas[schemaId as keyof typeof payloadSchemas]; - return schema - ? project(schema.safeParse(value)) - : { success: false as const, issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }] }; + return validateOwned(payloadSchemas, schemaId, value); } export function validateReferenceRequest(schemaId: string, value: unknown) { - const schema = requestSchemas[schemaId as keyof typeof requestSchemas]; - return schema - ? project(schema.safeParse(value)) - : { success: false as const, issues: [{ path: "", code: "SCHEMA_NOT_REGISTERED" }] }; + return validateOwned(requestSchemas, schemaId, value); } diff --git a/tests/features/reference-feature/reference-validator-protocol.test.ts b/tests/features/reference-feature/reference-validator-protocol.test.ts new file mode 100644 index 00000000..ed04cc2b --- /dev/null +++ b/tests/features/reference-feature/reference-validator-protocol.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from "vitest"; + +import { + CREATE_REFERENCE_RESOURCE_CONTRACT, + LIST_REFERENCE_RESOURCES_CONTRACT, +} 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 + * two protocols: the canonical `RuntimeValidator` (array paths) for the HTTP + * contract and the registry-facing `RuntimeSchemaCodec` (dotted paths). Both + * must keep answering exactly this after they share one zod wrapper. + */ +describe("reference validator protocols", () => { + const badList = [{ id: "unsafe", name: 42 }]; + + it("answers the canonical validator with array paths", () => { + expect( + LIST_REFERENCE_RESOURCES_CONTRACT.contract.outputValidator.safeParse( + badList, + ), + ).toEqual({ + success: false, + issues: [{ path: [0, "name"], code: "invalid_type" }], + }); + expect( + CREATE_REFERENCE_RESOURCE_CONTRACT.contract.inputValidator.safeParse({ + 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" }], + }); + }); +}); diff --git a/tests/unit/boundary-mapper.test.ts b/tests/unit/boundary-mapper.test.ts index 9ae6a330..6d3c6dc8 100644 --- a/tests/unit/boundary-mapper.test.ts +++ b/tests/unit/boundary-mapper.test.ts @@ -3,8 +3,11 @@ import { describe, expect, it } from "vitest"; import { mapOperationPayload } from "../../src/adapters/http/resource-mapper.ts"; import { composeBoundaryMapperRegistry, + mappingFailure, mappingSuccess, + toContractMappingResult, } from "../../src/contracts/boundary-mapper.ts"; +import { mappingViolation } from "../../src/contracts/external-contract-runtime.ts"; describe("platform DTO mapper boundary", () => { it("fails closed when no feature mapper was injected", () => { @@ -31,4 +34,14 @@ describe("platform DTO mapper boundary", () => { ]), ).toThrow("duplicate boundary mapper"); }); + + it("adapts a boundary result to the canonical mapping result (D-15)", () => { + expect(toContractMappingResult(mappingSuccess(1))).toEqual({ + ok: true, + value: 1, + }); + expect( + toContractMappingResult(mappingFailure("UNSUPPORTED_WIRE_VALUE")), + ).toEqual(mappingViolation("UNSUPPORTED_WIRE_VALUE")); + }); });