문제 - 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
239 lines
7.3 KiB
TypeScript
239 lines
7.3 KiB
TypeScript
import { z } from "zod";
|
|
|
|
import type {
|
|
CommandEffectDescriptor,
|
|
InstalledContractContribution,
|
|
InstalledEventContract,
|
|
InstalledHttpContract,
|
|
} from "../../src/contracts/external-contract-runtime.ts";
|
|
import { zodValidator } from "../../src/contracts/zod-validator.ts";
|
|
|
|
const entitySchema = z
|
|
.object({
|
|
id: z.string().min(1),
|
|
name: z.string().min(1),
|
|
})
|
|
.strip();
|
|
|
|
const problemSchema = z
|
|
.object({
|
|
type: z.string().min(1),
|
|
title: z.string().min(1),
|
|
status: z.int().min(100).max(599),
|
|
code: z.string().min(1).optional(),
|
|
})
|
|
.strip();
|
|
|
|
type TestProblem = z.output<typeof problemSchema>;
|
|
|
|
const problemValidator = zodValidator("TestProblem", problemSchema);
|
|
const readPolicy = Object.freeze({
|
|
policyId: "TEST_READ_V1",
|
|
requestByteLimit: 0,
|
|
responseByteLimit: 32_768,
|
|
totalDeadlineMs: 10_000,
|
|
retryBudget: 2 as const,
|
|
authProfileId: "ANONYMOUS",
|
|
diagnosticsOperation: "test.read",
|
|
});
|
|
|
|
export const TEST_LIST_HTTP_CONTRACT: InstalledHttpContract<
|
|
Readonly<{ limit: number }>,
|
|
readonly z.output<typeof entitySchema>[],
|
|
TestProblem
|
|
> = Object.freeze({
|
|
contract: Object.freeze({
|
|
operationId: "TEST_LIST_ENTITIES",
|
|
method: "GET" as const,
|
|
pathTemplate: "/api/test-entities",
|
|
inputValidator: zodValidator(
|
|
"TestEntityListQuery",
|
|
z
|
|
.object({
|
|
limit: z.coerce.number().int().min(1).max(100).default(20),
|
|
})
|
|
.strict(),
|
|
),
|
|
outputValidator: zodValidator(
|
|
"TestEntityListPayload",
|
|
z.array(entitySchema).max(100),
|
|
),
|
|
problemValidator,
|
|
acceptedStatuses: Object.freeze([200]),
|
|
emptyBodyStatuses: Object.freeze([]),
|
|
retrySemantics: "SAFE" as const,
|
|
requestBody: "NONE" as const,
|
|
responseBody: "REQUIRED_JSON" as const,
|
|
commandRecovery: null,
|
|
commandEffect: null,
|
|
projectRequest(input: Readonly<{ limit: number }>) {
|
|
return Object.freeze({
|
|
pathValues: Object.freeze({}),
|
|
queryEntries: Object.freeze([
|
|
Object.freeze(["limit", String(input.limit)] as const),
|
|
]),
|
|
body: null,
|
|
});
|
|
},
|
|
}),
|
|
frontend: readPolicy,
|
|
});
|
|
|
|
export const TEST_DETAIL_HTTP_CONTRACT: InstalledHttpContract<
|
|
Readonly<{ entityId: string }>,
|
|
z.output<typeof entitySchema>,
|
|
TestProblem
|
|
> = Object.freeze({
|
|
contract: Object.freeze({
|
|
operationId: "TEST_GET_ENTITY",
|
|
method: "GET" as const,
|
|
pathTemplate: "/api/test-entities/{entityId}",
|
|
inputValidator: zodValidator(
|
|
"TestEntityParams",
|
|
z.object({ entityId: z.string().min(1) }).strict(),
|
|
),
|
|
outputValidator: zodValidator("TestEntityPayload", entitySchema),
|
|
problemValidator,
|
|
acceptedStatuses: Object.freeze([200]),
|
|
emptyBodyStatuses: Object.freeze([]),
|
|
retrySemantics: "SAFE" as const,
|
|
requestBody: "NONE" as const,
|
|
responseBody: "REQUIRED_JSON" as const,
|
|
commandRecovery: null,
|
|
commandEffect: null,
|
|
projectRequest(input: Readonly<{ entityId: string }>) {
|
|
return Object.freeze({
|
|
pathValues: Object.freeze({ entityId: input.entityId }),
|
|
queryEntries: Object.freeze([]),
|
|
body: null,
|
|
});
|
|
},
|
|
}),
|
|
frontend: Object.freeze({
|
|
...readPolicy,
|
|
policyId: "TEST_DETAIL_V1",
|
|
diagnosticsOperation: "test.detail",
|
|
}),
|
|
});
|
|
|
|
const commandEffect: CommandEffectDescriptor<TestProblem> = Object.freeze({
|
|
successEffect: "APPLIED_CONFIRMED" as const,
|
|
classifyProblem({
|
|
status,
|
|
}: Readonly<{ status: number; problem: TestProblem }>) {
|
|
return status === 400 ? "NOT_APPLIED" : "MAYBE_APPLIED";
|
|
},
|
|
});
|
|
|
|
export const TEST_CREATE_HTTP_CONTRACT: InstalledHttpContract<
|
|
Readonly<{ name: string }>,
|
|
z.output<typeof entitySchema>,
|
|
TestProblem
|
|
> = Object.freeze({
|
|
contract: Object.freeze({
|
|
operationId: "TEST_CREATE_ENTITY",
|
|
method: "POST" as const,
|
|
pathTemplate: "/api/test-entities",
|
|
inputValidator: zodValidator(
|
|
"TestCreateEntityCommand",
|
|
z.object({ name: z.string().trim().min(1) }).strict(),
|
|
),
|
|
outputValidator: zodValidator("TestEntityPayload", entitySchema),
|
|
problemValidator,
|
|
acceptedStatuses: Object.freeze([201]),
|
|
emptyBodyStatuses: Object.freeze([]),
|
|
retrySemantics: "KEYED" as const,
|
|
requestBody: "JSON" as const,
|
|
responseBody: "REQUIRED_JSON" as const,
|
|
commandRecovery: Object.freeze({
|
|
mode: "IDEMPOTENCY_REPLAY" as const,
|
|
operationIdentityField: "idempotencyKey",
|
|
}),
|
|
commandEffect,
|
|
projectRequest(input: Readonly<{ name: string }>) {
|
|
return Object.freeze({
|
|
pathValues: Object.freeze({}),
|
|
queryEntries: Object.freeze([]),
|
|
body: Object.freeze({ ...input }),
|
|
});
|
|
},
|
|
}),
|
|
frontend: Object.freeze({
|
|
policyId: "TEST_CREATE_V1",
|
|
requestByteLimit: 32_768,
|
|
responseByteLimit: 32_768,
|
|
totalDeadlineMs: 10_000,
|
|
retryBudget: 0 as const,
|
|
authProfileId: "ANONYMOUS",
|
|
diagnosticsOperation: "test.create",
|
|
}),
|
|
});
|
|
|
|
/**
|
|
* The create command as a package that classifies its effects describes it,
|
|
* the way the HTTP scenario catalog (`tests/mocks/scenarios/catalog.ts`)
|
|
* expects (testing strategy §11.2): 401, 403 and 429 are rejected before any
|
|
* state changes, 400, 422 and the declared `409 CONFLICT` are NOT_APPLIED, and
|
|
* any other problem (`409 IDEMPOTENT_IN_FLIGHT`, 404, 503) stays MAYBE_APPLIED.
|
|
* TEST_CREATE_HTTP_CONTRACT keeps the bare classifier the executor tests
|
|
* extend.
|
|
*/
|
|
export const TEST_CLASSIFIED_CREATE_HTTP_CONTRACT: typeof TEST_CREATE_HTTP_CONTRACT =
|
|
Object.freeze({
|
|
...TEST_CREATE_HTTP_CONTRACT,
|
|
contract: Object.freeze({
|
|
...TEST_CREATE_HTTP_CONTRACT.contract,
|
|
commandEffect: Object.freeze({
|
|
successEffect: "APPLIED_CONFIRMED" as const,
|
|
classifyProblem({
|
|
status,
|
|
problem,
|
|
}: Readonly<{ status: number; problem: TestProblem }>) {
|
|
if (status === 400 || status === 422) return "NOT_APPLIED";
|
|
if (status === 409 && problem.code === "CONFLICT") return "NOT_APPLIED";
|
|
return "MAYBE_APPLIED";
|
|
},
|
|
classifyStatus: () => "NOT_APPLIED" as const,
|
|
}),
|
|
}),
|
|
});
|
|
|
|
/**
|
|
* An event contract an external package could install. The shared
|
|
* contribution below keeps `events` empty, so tests that check event
|
|
* composition put this row into a copy of it.
|
|
*/
|
|
export const TEST_EVENT_CONTRACT: InstalledEventContract<
|
|
Readonly<{ type: string; payload: unknown }>,
|
|
z.output<typeof entitySchema>
|
|
> = Object.freeze({
|
|
eventType: "test.entity.changed",
|
|
envelopeValidator: zodValidator(
|
|
"TestEventEnvelope",
|
|
z.object({ type: z.string().min(1), payload: z.unknown() }).strip(),
|
|
),
|
|
payloadValidator: zodValidator("TestEntity", entitySchema),
|
|
});
|
|
|
|
export const TEST_CONTRACT_CONTRIBUTION: InstalledContractContribution =
|
|
Object.freeze({
|
|
contributionId: "test-http-v1",
|
|
featureId: "test-feature",
|
|
source: Object.freeze({
|
|
kind: "EXTERNAL_PACKAGE" as const,
|
|
package: Object.freeze({
|
|
packageId: "@test/contracts",
|
|
version: "1.0.0",
|
|
digest: `sha256:${"a".repeat(64)}`,
|
|
runtimeProtocolVersion: 1 as const,
|
|
sourceRevision: "abcdef1",
|
|
}),
|
|
}),
|
|
http: Object.freeze([
|
|
TEST_LIST_HTTP_CONTRACT,
|
|
TEST_DETAIL_HTTP_CONTRACT,
|
|
TEST_CREATE_HTTP_CONTRACT,
|
|
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
|
|
events: Object.freeze([]),
|
|
});
|