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 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
abaaa9c773
commit
56de543d49
@@ -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<Value> =
|
||||
/**
|
||||
* 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<Value> =
|
||||
| Readonly<{ ok: true; value: Value }>
|
||||
| Readonly<{ ok: false; code: MappingFailureCode }>;
|
||||
|
||||
/** Compatible alias kept for existing importers; see `BoundaryMappingResult`. */
|
||||
export type MappingResult<Value> = BoundaryMappingResult<Value>;
|
||||
|
||||
/** Adapts a boundary mapper result to the canonical contract mapping result. */
|
||||
export function toContractMappingResult<Value>(
|
||||
result: BoundaryMappingResult<Value>,
|
||||
): ContractMappingResult<Value> {
|
||||
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<Input, Output> = Readonly<{
|
||||
mapperId: string;
|
||||
mapperVersion: number;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<unknown>,
|
||||
): 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<Record<string, RuntimeSchemaCodec>>[],
|
||||
): Readonly<Record<string, RuntimeSchemaCodec>> {
|
||||
|
||||
+1
-34
@@ -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/<service>-contract-contribution.ts`.
|
||||
*/
|
||||
|
||||
function zodValidator<T>(
|
||||
schemaId: string,
|
||||
schema: z.ZodType<T>,
|
||||
): RuntimeValidator<T> {
|
||||
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,
|
||||
|
||||
@@ -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<string, z.ZodType>;
|
||||
|
||||
function project(result: z.ZodSafeParseResult<unknown>) {
|
||||
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<T>(
|
||||
schemaId: string,
|
||||
schema: z.ZodType,
|
||||
): RuntimeSchemaCodec {
|
||||
schema: z.ZodType<T>,
|
||||
): RuntimeValidator<T> {
|
||||
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<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) {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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" }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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"));
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user