문제 - 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
263 lines
8.8 KiB
TypeScript
263 lines
8.8 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import {
|
|
ContractContributionError,
|
|
composeContractContributions,
|
|
invokeValidator,
|
|
unvalidatedPayload,
|
|
type InstalledContractContribution,
|
|
type RuntimeValidator,
|
|
} from "../../src/contracts/external-contract-runtime.ts";
|
|
import {
|
|
TEST_CONTRACT_CONTRIBUTION,
|
|
TEST_EVENT_CONTRACT,
|
|
} from "../helpers/external-contract-fixture.ts";
|
|
|
|
function contribution(
|
|
contributionId: string,
|
|
http: InstalledContractContribution["http"],
|
|
): InstalledContractContribution & Readonly<{ contributionId: string }> {
|
|
return Object.freeze({
|
|
...TEST_CONTRACT_CONTRIBUTION,
|
|
contributionId,
|
|
http: Object.freeze([...http]),
|
|
});
|
|
}
|
|
|
|
function captureContributionError(operation: () => unknown): ContractContributionError {
|
|
try {
|
|
operation();
|
|
} catch (error) {
|
|
expect(error).toBeInstanceOf(ContractContributionError);
|
|
return error as ContractContributionError;
|
|
}
|
|
throw new Error("Expected contract composition to fail.");
|
|
}
|
|
|
|
describe("external contract contribution composition", () => {
|
|
it("allows one feature to install multiple uniquely identified contributions", () => {
|
|
const operations = TEST_CONTRACT_CONTRIBUTION.http;
|
|
const composed = composeContractContributions([
|
|
contribution("test-read-contracts", operations.slice(0, 2)),
|
|
contribution("test-command-contracts", operations.slice(2)),
|
|
]);
|
|
|
|
expect(composed.contributions).toHaveLength(2);
|
|
expect(composed.httpByOperationId.size).toBe(3);
|
|
});
|
|
|
|
it("rejects duplicate contribution identities even across different feature entries", () => {
|
|
const first = contribution(
|
|
"test-contracts",
|
|
TEST_CONTRACT_CONTRIBUTION.http.slice(0, 1),
|
|
);
|
|
const second = contribution(
|
|
"test-contracts",
|
|
TEST_CONTRACT_CONTRIBUTION.http.slice(1),
|
|
);
|
|
|
|
const error = captureContributionError(() =>
|
|
composeContractContributions([first, second]),
|
|
);
|
|
expect(error.reason).toContain("duplicate contributionId");
|
|
});
|
|
|
|
it("maps malformed source values to the closed composition error", () => {
|
|
const malformed = {
|
|
...contribution("malformed-source", []),
|
|
source: null,
|
|
} as unknown as InstalledContractContribution;
|
|
|
|
const error = captureContributionError(() =>
|
|
composeContractContributions([malformed]),
|
|
);
|
|
expect(error.reason).toContain("source");
|
|
});
|
|
|
|
it("rejects method and body vocabulary outside the runtime protocol", () => {
|
|
const installed = TEST_CONTRACT_CONTRIBUTION.http[0]!;
|
|
const malformedOperation = {
|
|
...installed,
|
|
contract: { ...installed.contract, method: "TRACE" },
|
|
} as unknown as InstalledContractContribution["http"][number];
|
|
|
|
const error = captureContributionError(() =>
|
|
composeContractContributions([
|
|
contribution("invalid-http-vocabulary", [malformedOperation]),
|
|
]),
|
|
);
|
|
expect(error.reason).toContain("method");
|
|
});
|
|
});
|
|
|
|
// 07-06 (MX1, MX9, MX6). The write-API rules the composer teaches through its
|
|
// error messages. TEST_CONTRACT_CONTRIBUTION composing in the first block is
|
|
// the valid control.
|
|
describe("write operation rules", () => {
|
|
const [listRow, , createRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
|
|
InstalledContractContribution["http"][number],
|
|
InstalledContractContribution["http"][number],
|
|
InstalledContractContribution["http"][number],
|
|
];
|
|
|
|
function reasonFor(row: object): string {
|
|
return captureContributionError(() =>
|
|
composeContractContributions([
|
|
contribution("write-rule", [
|
|
row as InstalledContractContribution["http"][number],
|
|
]),
|
|
]),
|
|
).reason;
|
|
}
|
|
|
|
// The executor decides "write" by `commandEffect !== null`, not by method,
|
|
// so this rule is the only thing keeping a GET from running as a command.
|
|
it("rejects command descriptors on a read operation", () => {
|
|
expect(
|
|
reasonFor({
|
|
...listRow,
|
|
contract: { ...listRow.contract, commandEffect: createRow.contract.commandEffect },
|
|
}),
|
|
).toBe("test-feature/TEST_LIST_ENTITIES: read operations carry no command descriptors");
|
|
});
|
|
|
|
it("requires a recovery descriptor on a KEYED command", () => {
|
|
expect(
|
|
reasonFor({
|
|
...createRow,
|
|
contract: { ...createRow.contract, commandRecovery: null },
|
|
}),
|
|
).toBe("test-feature/TEST_CREATE_ENTITY: KEYED commands require a recovery descriptor");
|
|
});
|
|
|
|
it("rejects a retry budget on a NEVER-retry operation", () => {
|
|
expect(
|
|
reasonFor({
|
|
...createRow,
|
|
contract: { ...createRow.contract, retrySemantics: "NEVER" },
|
|
frontend: { ...createRow.frontend, retryBudget: 1 },
|
|
}),
|
|
).toBe("test-feature/TEST_CREATE_ENTITY: retry budget contradicts NEVER retry semantics");
|
|
});
|
|
});
|
|
|
|
// The sample feature's own cases (its fixture composes, a second one does not)
|
|
// live in tests/features so they leave with the sample.
|
|
describe("template fixture provenance (07-04, §4.8)", () => {
|
|
it("rejects a fixture copied into a product feature, which would leave the contract set silently", () => {
|
|
const copied = Object.freeze({
|
|
...contribution("order-http-v1", TEST_CONTRACT_CONTRIBUTION.http),
|
|
featureId: "order",
|
|
source: Object.freeze({
|
|
kind: "TEMPLATE_FIXTURE" as const,
|
|
fixtureId: "REFERENCE_FEATURE_V1" as const,
|
|
revision: 1 as const,
|
|
}),
|
|
});
|
|
const error = captureContributionError(() =>
|
|
composeContractContributions([copied]),
|
|
);
|
|
expect(error.reason).toMatch(
|
|
/^order: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to .+ only; pin an EXTERNAL_PACKAGE$/u,
|
|
);
|
|
});
|
|
});
|
|
|
|
// 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",
|
|
safeParse: () => result as never,
|
|
});
|
|
|
|
it.each([
|
|
["non-array issues", { success: false, issues: 5 }],
|
|
["object issues", { success: false, issues: {} }],
|
|
["non-boolean success", { success: "no", data: "unchecked" }],
|
|
["throwing issues getter", {
|
|
success: false,
|
|
get issues(): never {
|
|
throw new Error("hostile");
|
|
},
|
|
}],
|
|
])("reports THROWN for a result with %s", (_label, result) => {
|
|
expect(invokeValidator(returning(result), {})).toEqual({ outcome: "THROWN" });
|
|
});
|
|
|
|
it("keeps well-formed results", () => {
|
|
expect(invokeValidator(returning({ success: true, data: 1 }), {})).toEqual({
|
|
outcome: "VALID",
|
|
value: 1,
|
|
});
|
|
expect(
|
|
invokeValidator(returning({ success: false, issues: [{ path: [], code: "X" }] }), {}),
|
|
).toEqual({ outcome: "INVALID", issues: [{ path: [], code: "X" }] });
|
|
});
|
|
});
|