feat(contracts): zod 검증기 어댑터를 공유하고 검증 생략을 이름으로 드러낸다 (1101/07-03)
문제 - zod 스키마를 RuntimeValidator로 바꾸는 zodValidator가 참조 기능의 reference-schemas.ts 안에만 있다. 기능끼리 import가 금지라 새 기능은 복사하고, 복사본은 이미 갈라졌다(tests/helpers 복사본은 성공 값을 structuredClone하지 않는다). 참조 기능을 지우면 어댑터도 사라진다. - RuntimeValidator<T>는 schemaId와 safeParse만 요구한다. 아무것도 검증하지 않는 검증기도 조립을 통과하고, 검증을 생략했다는 사실이 타입·이름·조립 결과 어디에도 남지 않는다. 고른 방법 (C: 공유 어댑터 + 생략 표시) - zodValidator를 src/contracts/zod-validator.ts로 옮긴다. 참조 기능과 tests/helpers/external-contract-fixture.ts가 이것을 import한다. 동작은 참조 기능 쪽 원본 그대로다(성공 값 structuredClone, 경로 배열, code 문자열). tests/helpers도 이제 성공 값을 복사한다. - unvalidatedPayload(schemaId, reason)를 external-contract-runtime.ts에 둔다. 만든 검증기에는 validation: "NONE"과 unvalidatedReason이 붙는다. zod가 필요 없어서 검증기 프로토콜 옆에 뒀다. - composeContractContributions가 이 표시가 붙은 검증기를 unvalidatedPayloads(featureId, contractId, validator, schemaId, reason)로 내놓는다. HTTP의 input·output·problem과 이벤트의 envelope·payload를 모두 본다. 표시가 "NONE"이 아니거나 이유가 비어 있으면 조립을 거부한다. - 플랫폼 개요 화면(스타터 화면)의 계약 절에 "런타임 검증을 생략한 계약" 표를 둔다. 목록이 비면 그리지 않는다. 버린 대안 - (B) 공유 어댑터만: 검증 생략이 여전히 보이지 않는다. - (D) 브랜드 타입으로 zodValidator가 만든 검증기만 받기: 외부 패키지의 자체 검증기까지 막아 §4 설계와 충돌한다. 위험·한계 - 표시 없이 손으로 쓴 통과 검증기(리뷰 실험 L5)는 여전히 조립을 통과하고 목록에도 없다. 이 변경은 생략을 막지 않는다. 이름 있는 길을 만들어 그 길로 생략한 것만 드러낸다. - 공개 계약 추가: RuntimeValidator에 선택 필드 2개, ComposedContractContributions에 필드 1개, 새 export zodValidator· unvalidatedPayload·UnvalidatedPayloadEntry. 기존 호출자는 바뀌지 않는다. ComposedContractContributions를 손으로 만드는 코드는 새 필드를 채워야 한다(repo 안에는 없다). - 초기 JS gzip 204,586 → 204,745 B(+159). 예산 204,800까지 55 B 남는다. 플랫폼 개요 청크 4,625 → 4,750 B. - 참조 기능은 모든 검증기가 검증하므로 화면 모양은 그대로다. 시각 회귀는 돌리지 않았다. - tests/unit/second-api-feature-registries.test.ts의 V2 codec 통과 검증기는 그대로 둔다(16-01이 그 파일을 넓힌다). 검증 - RED(수정 전): zod-validator.test.ts "Cannot find module '../../src/contracts/zod-validator.ts'", external-contract-runtime.test.ts와 starter-platform-overview-page.test.tsx "unvalidatedPayload is not a function". 3파일 모두 실패. - GREEN: 같은 3파일 33건 통과. - 회귀: tests/unit·contract·component·runtime-schema·features·platform 268파일 3,189건, tests/integration 12파일 158건(pnpm을 띄우는 security-followup-archive 제외), tests/architecture 7파일 33건 통과. tsc app·node·test·recipes·web-worker·service-worker 오류 0. 바꾼 파일 eslint 0. check-registries PASS(compatibility=none), verify-documentation PASS_SCOPED, check-adapter-inventory PASS. 아키텍처 그래프 검사(pnpm 대신 exec stub) 383 모듈 PASS. - 참조 기능 삭제 모의: scripts/test-sample-removal.ts의 삭제 목록(기능 폴더, tests/features, reference-context, SAMPLE_EXTRAS)을 복사본에 적용. src/contracts/zod-validator.ts가 남고, tsc app·test 오류 0, 어댑터·조립· 플랫폼 개요·HTTP 시나리오 테스트 4파일 35건 통과. Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md 07-03, 5.3
This commit is contained in:
@@ -58,9 +58,42 @@ export type RuntimeValidationResult<T> =
|
||||
|
||||
export interface RuntimeValidator<T> {
|
||||
readonly schemaId: string;
|
||||
/**
|
||||
* 1101/07-03. Absent on a validator that checks its input. `"NONE"` marks
|
||||
* one made by `unvalidatedPayload`, which accepts any value as `T`;
|
||||
* composition lists it in `unvalidatedPayloads`. A hand-written validator
|
||||
* that checks nothing and omits the marker is not detected.
|
||||
*/
|
||||
readonly validation?: "NONE";
|
||||
/** Why validation is skipped. Required with `validation: "NONE"`. */
|
||||
readonly unvalidatedReason?: string;
|
||||
safeParse(value: unknown): RuntimeValidationResult<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 1101/07-03. The named way to skip runtime validation, for a payload whose
|
||||
* shape the feature decides to trust (for example generated client types).
|
||||
* The value reaches the mapper as `T` unchecked: a server that sends another
|
||||
* shape produces no `SCHEMA_MISMATCH`. The skip and its reason stay visible in
|
||||
* `ComposedContractContributions.unvalidatedPayloads`.
|
||||
*/
|
||||
export function unvalidatedPayload<T>(
|
||||
schemaId: string,
|
||||
reason: string,
|
||||
): RuntimeValidator<T> {
|
||||
return Object.freeze({
|
||||
schemaId,
|
||||
validation: "NONE" as const,
|
||||
unvalidatedReason: reason,
|
||||
safeParse(value: unknown) {
|
||||
return Object.freeze({
|
||||
success: true as const,
|
||||
data: structuredClone(value) as T,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A validator invocation never escapes as a native throw. `THROWN` is the
|
||||
* `CONTRACT_RUNTIME_FAILURE` signal; `false` success is the ordinary
|
||||
@@ -306,18 +339,58 @@ function assertPackageIdentity(
|
||||
}
|
||||
}
|
||||
|
||||
function assertValidator(
|
||||
validator: RuntimeValidator<unknown>,
|
||||
label: string,
|
||||
): void {
|
||||
if (
|
||||
!validator ||
|
||||
typeof validator.safeParse !== "function" ||
|
||||
typeof validator.schemaId !== "string" ||
|
||||
validator.schemaId.length === 0
|
||||
) {
|
||||
fail(`${label}: runtime validator with non-empty schemaId is required`);
|
||||
/** 1101/07-03. A validator slot whose validation is skipped by name. */
|
||||
export type UnvalidatedPayloadEntry = Readonly<{
|
||||
featureId: string;
|
||||
/** The HTTP operationId, or the event type of an event contract. */
|
||||
contractId: string;
|
||||
validator: "input" | "output" | "problem" | "envelope" | "payload";
|
||||
schemaId: string;
|
||||
reason: string;
|
||||
}>;
|
||||
|
||||
/** Checks each validator and returns the ones that skip validation by name. */
|
||||
function assertValidators(
|
||||
featureId: string,
|
||||
contractId: string,
|
||||
validators: Partial<
|
||||
Record<UnvalidatedPayloadEntry["validator"], RuntimeValidator<unknown>>
|
||||
>,
|
||||
): UnvalidatedPayloadEntry[] {
|
||||
const unvalidated: UnvalidatedPayloadEntry[] = [];
|
||||
for (const [role, validator] of Object.entries(validators) as [
|
||||
UnvalidatedPayloadEntry["validator"],
|
||||
RuntimeValidator<unknown>,
|
||||
][]) {
|
||||
const label = `${featureId}/${contractId}.${role}`;
|
||||
if (
|
||||
!validator ||
|
||||
typeof validator.safeParse !== "function" ||
|
||||
typeof validator.schemaId !== "string" ||
|
||||
validator.schemaId.length === 0
|
||||
) {
|
||||
fail(`${label}: runtime validator with non-empty schemaId is required`);
|
||||
}
|
||||
if (validator.validation === undefined) continue;
|
||||
const reason = validator.unvalidatedReason;
|
||||
if (
|
||||
validator.validation !== "NONE" ||
|
||||
typeof reason !== "string" ||
|
||||
reason.trim().length === 0
|
||||
) {
|
||||
fail(`${label}: an unvalidated payload needs validation "NONE" and a reason`);
|
||||
}
|
||||
unvalidated.push(
|
||||
Object.freeze({
|
||||
featureId,
|
||||
contractId,
|
||||
validator: role,
|
||||
schemaId: validator.schemaId,
|
||||
reason,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return unvalidated;
|
||||
}
|
||||
|
||||
function assertStatuses(
|
||||
@@ -405,7 +478,7 @@ function assertHttpContract(
|
||||
installed: InstalledHttpContract<unknown, unknown, unknown>,
|
||||
featureId: string,
|
||||
authProfiles: InstalledRestAuthProfiles,
|
||||
): void {
|
||||
): UnvalidatedPayloadEntry[] {
|
||||
const contract = installed?.contract;
|
||||
if (!contract || typeof contract !== "object") {
|
||||
fail(`${featureId}: http contract descriptor missing`);
|
||||
@@ -434,9 +507,11 @@ function assertHttpContract(
|
||||
) {
|
||||
fail(`${label}: pathTemplate`);
|
||||
}
|
||||
assertValidator(contract.inputValidator, `${label}.input`);
|
||||
assertValidator(contract.outputValidator, `${label}.output`);
|
||||
assertValidator(contract.problemValidator, `${label}.problem`);
|
||||
const unvalidated = assertValidators(featureId, String(contract.operationId), {
|
||||
input: contract.inputValidator,
|
||||
output: contract.outputValidator,
|
||||
problem: contract.problemValidator,
|
||||
});
|
||||
if (typeof contract.projectRequest !== "function") {
|
||||
fail(`${label}: descriptor request projection is required`);
|
||||
}
|
||||
@@ -514,12 +589,13 @@ function assertHttpContract(
|
||||
) {
|
||||
fail(`${label}: retry budget contradicts NEVER retry semantics`);
|
||||
}
|
||||
return unvalidated;
|
||||
}
|
||||
|
||||
function assertEventContract(
|
||||
event: InstalledEventContract<unknown, unknown>,
|
||||
featureId: string,
|
||||
): void {
|
||||
): UnvalidatedPayloadEntry[] {
|
||||
const label = `${featureId}/${String(event?.eventType)}`;
|
||||
if (
|
||||
typeof event?.eventType !== "string" ||
|
||||
@@ -529,8 +605,10 @@ function assertEventContract(
|
||||
) {
|
||||
fail(`${label}: eventType`);
|
||||
}
|
||||
assertValidator(event.envelopeValidator, `${label}.envelope`);
|
||||
assertValidator(event.payloadValidator, `${label}.payload`);
|
||||
return assertValidators(featureId, event.eventType, {
|
||||
envelope: event.envelopeValidator,
|
||||
payload: event.payloadValidator,
|
||||
});
|
||||
}
|
||||
|
||||
export type ComposedContractContributions = Readonly<{
|
||||
@@ -549,6 +627,8 @@ export type ComposedContractContributions = Readonly<{
|
||||
InstalledEventContract<unknown, unknown>
|
||||
>;
|
||||
externalPackages: readonly InstalledContractPackageIdentity[];
|
||||
/** 1101/07-03. Every validator made by `unvalidatedPayload`, in install order. */
|
||||
unvalidatedPayloads: readonly UnvalidatedPayloadEntry[];
|
||||
}>;
|
||||
|
||||
const EXECUTION_POLICY_KEYS = [
|
||||
@@ -698,6 +778,7 @@ export function composeContractContributions(
|
||||
const packagesById = new Map<string, InstalledContractPackageIdentity>();
|
||||
const contributionIds = new Set<string>();
|
||||
const installedContributions: InstalledContractContribution[] = [];
|
||||
const unvalidatedPayloads: UnvalidatedPayloadEntry[] = [];
|
||||
let fixtureInstalled = false;
|
||||
|
||||
for (const raw of rows) {
|
||||
@@ -833,7 +914,9 @@ export function composeContractContributions(
|
||||
installed as InstalledHttpContract<unknown, unknown, unknown>,
|
||||
featureId,
|
||||
);
|
||||
assertHttpContract(snapshot, featureId, authProfiles);
|
||||
unvalidatedPayloads.push(
|
||||
...assertHttpContract(snapshot, featureId, authProfiles),
|
||||
);
|
||||
const operationId = snapshot.contract.operationId;
|
||||
const previous = httpByOperationId.get(operationId);
|
||||
if (previous) fail(`duplicate operation: ${operationId}`);
|
||||
@@ -847,7 +930,7 @@ export function composeContractContributions(
|
||||
event as InstalledEventContract<unknown, unknown>,
|
||||
featureId,
|
||||
);
|
||||
assertEventContract(snapshot, featureId);
|
||||
unvalidatedPayloads.push(...assertEventContract(snapshot, featureId));
|
||||
if (eventByType.has(snapshot.eventType)) {
|
||||
fail(`duplicate event type: ${snapshot.eventType}`);
|
||||
}
|
||||
@@ -877,5 +960,6 @@ export function composeContractContributions(
|
||||
httpByOperationId: createReadOnlyRegistry(httpByOperationId),
|
||||
eventByType: createReadOnlyRegistry(eventByType),
|
||||
externalPackages: Object.freeze(externalPackages),
|
||||
unvalidatedPayloads: Object.freeze(unvalidatedPayloads),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { RuntimeValidator } from "./external-contract-runtime.ts";
|
||||
import type { ZodType } from "./zod.ts";
|
||||
|
||||
/**
|
||||
* 1101/07-03. The one adapter from a zod schema to the `RuntimeValidator`
|
||||
* protocol (`external-contract-runtime.ts`). Features import it from here
|
||||
* rather than keeping a copy, so its rules cannot drift between features:
|
||||
* - a success value is a `structuredClone` copy, so the caller's object never
|
||||
* reaches the executor;
|
||||
* - an issue path stays an array of numbers and strings (symbol keys become
|
||||
* strings); an issue code is zod's code as a string.
|
||||
* A package that ships its own validators keeps implementing the protocol
|
||||
* directly. To skip validation on purpose, use `unvalidatedPayload`, which
|
||||
* composition lists.
|
||||
*/
|
||||
export function zodValidator<T>(
|
||||
schemaId: string,
|
||||
schema: 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),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
InstalledContractContribution,
|
||||
InstalledHttpContract,
|
||||
} from "../../../contracts/external-contract-runtime.ts";
|
||||
import { zodValidator } from "../../../contracts/zod-validator.ts";
|
||||
import { REFERENCE_FEATURE_ID } from "./reference-feature-contract.ts";
|
||||
import {
|
||||
createReferenceResourceCommandSchema,
|
||||
@@ -13,7 +14,6 @@ import {
|
||||
referenceResourceListQuerySchema,
|
||||
referenceResourceParamsSchema,
|
||||
type ReferenceProblem,
|
||||
zodValidator,
|
||||
} from "./reference-schemas.ts";
|
||||
|
||||
export type { ReferenceProblem } from "./reference-schemas.ts";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "../../../contracts/zod.ts";
|
||||
import type { RuntimeValidator } from "../../../contracts/external-contract-runtime.ts";
|
||||
import { runtimeSchemaCodecFromValidator } from "../../../contracts/schema-registry.ts";
|
||||
import { zodValidator } from "../../../contracts/zod-validator.ts";
|
||||
|
||||
export const referenceResourceListQuerySchema = z
|
||||
.object({
|
||||
@@ -80,44 +80,6 @@ const requestSchemas = {
|
||||
CreateReferenceResourceCommand: createReferenceResourceCommandSchema,
|
||||
} satisfies Record<string, z.ZodType>;
|
||||
|
||||
/**
|
||||
* 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<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 codec = (schemaId: string, schema: z.ZodType) =>
|
||||
runtimeSchemaCodecFromValidator(zodValidator(schemaId, schema));
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { type ComponentType, useEffect, useState } from "react";
|
||||
import {
|
||||
HTTP_EXECUTION_CEILINGS,
|
||||
type ComposedContractContributions,
|
||||
type UnvalidatedPayloadEntry,
|
||||
} from "../../contracts/external-contract-runtime.ts";
|
||||
import { SERVER_STATE_PROFILES } from "../../contracts/server-state.ts";
|
||||
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../features/installed-contract-contributions.ts";
|
||||
@@ -155,6 +156,26 @@ const OPERATION_COLUMNS: readonly DataTableColumn<OperationRow>[] =
|
||||
},
|
||||
]);
|
||||
|
||||
const UNVALIDATED_COLUMNS: readonly DataTableColumn<UnvalidatedPayloadEntry>[] =
|
||||
Object.freeze([
|
||||
{
|
||||
id: "contractId",
|
||||
header: "계약",
|
||||
cell: (row) => <code>{row.contractId}</code>,
|
||||
},
|
||||
{
|
||||
id: "validator",
|
||||
header: "검증기",
|
||||
cell: (row) => (
|
||||
<>
|
||||
<Badge variant="warning">{row.validator}</Badge>
|
||||
<span className="platform-operation__path">{row.schemaId}</span>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{ id: "reason", header: "생략 이유", cell: (row) => row.reason },
|
||||
]);
|
||||
|
||||
type ProfileRow = (typeof SERVER_STATE_PROFILES)[keyof typeof SERVER_STATE_PROFILES];
|
||||
|
||||
const PROFILE_COLUMNS: readonly DataTableColumn<ProfileRow>[] = Object.freeze([
|
||||
@@ -448,6 +469,14 @@ export function PlatformOverviewPage({
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{/* 1101/07-03. Drawn only when a contract skips validation by name. */}
|
||||
<DataTable
|
||||
caption="런타임 검증을 생략한 계약"
|
||||
columns={UNVALIDATED_COLUMNS}
|
||||
rows={contracts.unvalidatedPayloads}
|
||||
rowKey={(row) => `${row.contractId}.${row.validator}`}
|
||||
empty={null}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
composeContractContributions,
|
||||
unvalidatedPayload,
|
||||
} from "../../src/contracts/external-contract-runtime.ts";
|
||||
import { SERVER_STATE_PROFILES } from "../../src/contracts/server-state.ts";
|
||||
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts";
|
||||
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
|
||||
@@ -10,6 +14,7 @@ import { PlatformOverviewPage } from "../../src/presentation/examples/platform-o
|
||||
import { LocaleProvider } from "../../src/presentation/i18n/index.ts";
|
||||
import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx";
|
||||
import { createTestApplication } from "../helpers/create-test-application.ts";
|
||||
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
|
||||
import { createRuntimeCapabilitiesStub } from "../helpers/runtime-capabilities-stub.ts";
|
||||
|
||||
/**
|
||||
@@ -83,6 +88,50 @@ describe("platform overview page", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// 1101/07-03. A skipped validation is shown, not just composed.
|
||||
it("lists the operations that skip runtime validation, with the reason", () => {
|
||||
const [listRow, ...rest] = TEST_CONTRACT_CONTRIBUTION.http;
|
||||
const contracts = composeContractContributions([
|
||||
Object.freeze({
|
||||
...TEST_CONTRACT_CONTRIBUTION,
|
||||
http: Object.freeze([
|
||||
{
|
||||
...listRow!,
|
||||
contract: {
|
||||
...listRow!.contract,
|
||||
outputValidator: unvalidatedPayload(
|
||||
"TestEntityListPayload",
|
||||
"typed by the package",
|
||||
),
|
||||
},
|
||||
},
|
||||
...rest,
|
||||
]),
|
||||
}),
|
||||
]);
|
||||
render(
|
||||
<ApplicationProvider application={createTestApplication()}>
|
||||
<LocaleProvider>
|
||||
<PlatformOverviewPage contracts={contracts} />
|
||||
</LocaleProvider>
|
||||
</ApplicationProvider>,
|
||||
);
|
||||
|
||||
const table = tableByCaption("런타임 검증을 생략한 계약");
|
||||
const [row, ...others] = within(table).getAllByRole("row").slice(1);
|
||||
expect(others).toHaveLength(0);
|
||||
expect(within(row!).getByText("TEST_LIST_ENTITIES")).toBeVisible();
|
||||
expect(within(row!).getByText("typed by the package")).toBeVisible();
|
||||
});
|
||||
|
||||
it("shows no skipped-validation list when every operation validates", () => {
|
||||
renderPage();
|
||||
|
||||
expect(
|
||||
screen.queryByRole("table", { name: "런타임 검증을 생략한 계약" }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("renders every fixed server-state profile with its own budget", () => {
|
||||
renderPage();
|
||||
|
||||
|
||||
@@ -5,38 +5,8 @@ import type {
|
||||
InstalledContractContribution,
|
||||
InstalledEventContract,
|
||||
InstalledHttpContract,
|
||||
RuntimeValidator,
|
||||
} from "../../src/contracts/external-contract-runtime.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: 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) =>
|
||||
typeof segment === "number" ? segment : String(segment),
|
||||
),
|
||||
),
|
||||
code: String(issue.code),
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
import { zodValidator } from "../../src/contracts/zod-validator.ts";
|
||||
|
||||
const entitySchema = z
|
||||
.object({
|
||||
|
||||
@@ -4,10 +4,14 @@ import {
|
||||
ContractContributionError,
|
||||
composeContractContributions,
|
||||
invokeValidator,
|
||||
unvalidatedPayload,
|
||||
type InstalledContractContribution,
|
||||
type RuntimeValidator,
|
||||
} from "../../src/contracts/external-contract-runtime.ts";
|
||||
import { TEST_CONTRACT_CONTRIBUTION } from "../helpers/external-contract-fixture.ts";
|
||||
import {
|
||||
TEST_CONTRACT_CONTRIBUTION,
|
||||
TEST_EVENT_CONTRACT,
|
||||
} from "../helpers/external-contract-fixture.ts";
|
||||
|
||||
function contribution(
|
||||
contributionId: string,
|
||||
@@ -159,6 +163,73 @@ describe("template fixture provenance (07-04, §4.8)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
// 1101/07-03. Skipping runtime validation stays possible, but only a skip
|
||||
// made through `unvalidatedPayload` is named, so composition can list it.
|
||||
describe("validation skipped by name (1101/07-03)", () => {
|
||||
const [listRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
|
||||
InstalledContractContribution["http"][number],
|
||||
];
|
||||
const skipped = unvalidatedPayload("TestEntityListPayload", "typed by the package");
|
||||
|
||||
function withOutput(validator: RuntimeValidator<unknown>) {
|
||||
return contribution("skip-test", [
|
||||
{ ...listRow, contract: { ...listRow.contract, outputValidator: validator } },
|
||||
]);
|
||||
}
|
||||
|
||||
it("lists nothing when every validator checks its input", () => {
|
||||
expect(
|
||||
composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).unvalidatedPayloads,
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("lists an operation whose output skips validation, with its reason", () => {
|
||||
expect(
|
||||
composeContractContributions([withOutput(skipped)]).unvalidatedPayloads,
|
||||
).toEqual([
|
||||
{
|
||||
featureId: "test-feature",
|
||||
contractId: "TEST_LIST_ENTITIES",
|
||||
validator: "output",
|
||||
schemaId: "TestEntityListPayload",
|
||||
reason: "typed by the package",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("lists an event whose payload skips validation", () => {
|
||||
const composed = composeContractContributions([
|
||||
Object.freeze({
|
||||
...contribution("skip-event", []),
|
||||
events: Object.freeze([
|
||||
{ ...TEST_EVENT_CONTRACT, payloadValidator: unvalidatedPayload("TestEntity", "trusted feed") },
|
||||
]),
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(composed.unvalidatedPayloads).toEqual([
|
||||
expect.objectContaining({
|
||||
contractId: "test.entity.changed",
|
||||
validator: "payload",
|
||||
reason: "trusted feed",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no reason", { ...skipped, unvalidatedReason: " " }],
|
||||
["an unknown marker", { ...skipped, validation: "PARTIAL" }],
|
||||
])("rejects a skip marker with %s", (_label, validator) => {
|
||||
expect(
|
||||
captureContributionError(() =>
|
||||
composeContractContributions([withOutput(validator as RuntimeValidator<unknown>)]),
|
||||
).reason,
|
||||
).toBe(
|
||||
'test-feature/TEST_LIST_ENTITIES.output: an unvalidated payload needs validation "NONE" and a reason',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validator invocation (07-06)", () => {
|
||||
const returning = (result: unknown): RuntimeValidator<unknown> => ({
|
||||
schemaId: "Malformed",
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
invokeValidator,
|
||||
unvalidatedPayload,
|
||||
} from "../../src/contracts/external-contract-runtime.ts";
|
||||
import { z } from "../../src/contracts/zod.ts";
|
||||
import { zodValidator } from "../../src/contracts/zod-validator.ts";
|
||||
|
||||
/**
|
||||
* 1101/07-03. The one zod adapter lives in src/contracts, so every feature
|
||||
* imports it instead of copying it, and it outlives the sample feature.
|
||||
*/
|
||||
describe("zodValidator", () => {
|
||||
const validator = zodValidator(
|
||||
"Entity",
|
||||
z.object({ id: z.string().min(1), tags: z.array(z.string()) }).strip(),
|
||||
);
|
||||
|
||||
it("returns a copy of the parsed value, not the caller's object", () => {
|
||||
const source = { id: "a", tags: ["x"] };
|
||||
const result = validator.safeParse(source);
|
||||
|
||||
expect(result).toEqual({ success: true, data: source });
|
||||
if (!result.success) throw new Error("expected success");
|
||||
expect(result.data.tags).not.toBe(source.tags);
|
||||
expect(Object.isFrozen(result)).toBe(true);
|
||||
});
|
||||
|
||||
it("reports issues with array paths and string codes", () => {
|
||||
expect(validator.safeParse({ id: "", tags: [1] })).toEqual({
|
||||
success: false,
|
||||
issues: [
|
||||
{ path: ["id"], code: "too_small" },
|
||||
{ path: ["tags", 0], code: "invalid_type" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("checks its input, so it carries no skip marker", () => {
|
||||
expect(validator.schemaId).toBe("Entity");
|
||||
expect(validator.validation).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("unvalidatedPayload", () => {
|
||||
const skipped = unvalidatedPayload<{ id: string }>(
|
||||
"EntityPayload",
|
||||
"generated client types are trusted",
|
||||
);
|
||||
|
||||
it("names the skip on the validator itself", () => {
|
||||
expect(skipped).toMatchObject({
|
||||
schemaId: "EntityPayload",
|
||||
validation: "NONE",
|
||||
unvalidatedReason: "generated client types are trusted",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts any value as a copy", () => {
|
||||
const source = { anything: [1] };
|
||||
const invocation = invokeValidator(skipped, source);
|
||||
|
||||
expect(invocation).toEqual({ outcome: "VALID", value: source });
|
||||
if (invocation.outcome !== "VALID") throw new Error("expected VALID");
|
||||
expect(invocation.value).not.toBe(source);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user