Files
clean-architecture-frontend…/tests/helpers/external-contract-fixture.ts
T
DongHyeonka 56272e86d5 fix(contracts)!: HTTP descriptor의 responseEnvelope를 필수 칸으로 둔다
문제: responseEnvelope는 descriptor의 선택 칸이고 없으면 "NONE"이다.
1103/16-01 수정은 계약 조립이 한 기여 안에서 값이 섞이면 거부하고,
refusedBeforeWrite가 있는 쓰기에 Envelope를 요구하게 했다. 그러나 읽기만
있는 기여(기본 생성 판)나 refusedBeforeWrite 없는 쓰기에서 줄을 모두 빼면
조립은 통과하고(모두 같은 NONE), 짝 백엔드의 Envelope를 DTO로 읽어
SCHEMA_MISMATCH로 깨지는 것은 손글씨 gateway 테스트만 잡는다. 지난 완료
기준("줄을 지우면 check:types가 실패한다")을 채우지 못했다.

고른 방법(1103 대안 (b)): InstalledHttpContract의 contract.responseEnvelope를
필수로 바꾼다. 생성 기능·참조 기능·예제의 descriptor는 모두
`satisfies InstalledHttpContract<...>`라 줄을 지우면 tsc가 그 자리에서
실패한다. 줄이 없던 descriptor에 "NONE" as const를 적었다: 참조 기능 셋,
tests/helpers/external-contract-fixture.ts 셋,
tests/contract/reusable-capability/feature-http-binding.test.ts,
scripts/drill-runbook.ts. 값은 전과 같아 FE-REG-API 행과 레지스트리 기준선은
바뀌지 않는다. 조립(external-contract-runtime.ts)은 그대로 빠진 값을 NONE으로
읽는다: TypeScript 밖에서 만든 descriptor를 런타임에 거부하지 않는다.
생성기 주석의 "줄을 지운다" 안내를 "NONE을 적는다"로, 매뉴얼 01(3단계,
짝 백엔드가 아닌 백엔드), errors.md, 계약 문서 4.1절을 같은 뜻으로 고쳤다.
테스트: external-contract-runtime.test.ts에 줄을 뺀 descriptor 선언 위
@ts-expect-error를 두었다. 타입이 다시 선택 칸이 되면 그 지시문이 쓰이지
않아 check:types:test가 실패한다. 같은 테스트가 런타임 조립은 NONE으로
읽는지도 본다.
버린 대안: (c) 기여 단위 기본값 — 규칙이 하나 는다. (d)만으로 두기 — 모두
빠진 경우를 못 막는다. 조립에서 빠진 키를 거부 — JS로 만든 계약 패키지가
런타임에 깨지고, 빠진 값을 일부러 다루는 테스트를 모두 바꿔야 한다.

위험·한계: descriptor를 직접 쓰는 다운스트림 코드는 줄을 더할 때까지
check:types가 실패한다. 모든 operation에 같은 틀린 값을 적는 것(짝 백엔드인데
모두 "NONE")은 여전히 타입도 조립도 통과한다(매뉴얼 "못 잡음"). 이 노트북에서
tsc를 돌리지 못해, 놓친 descriptor가 있으면 desktop check:types가 알려 준다.

검증: desktop batch에서 확인.
corepack pnpm check:types
node scripts/run-vitest.ts run tests/unit/external-contract-runtime.test.ts
tests/features/reference-feature tests/unit/api-operation-rows.test.ts
corepack pnpm check:registries (compatibility 변화 없음 기대)

BREAKING CHANGE: src/contracts/external-contract-runtime.ts의
  InstalledHttpContract에서 contract.responseEnvelope가 필수다. 이 줄이 없는
  descriptor는 check:types에서 실패한다. 감싸지 않는 백엔드는
  responseEnvelope: "NONE" as const, 짝 백엔드(Envelope)는 "ENVELOPE_V1" as const를
  operation마다 적는다. 런타임 동작은 같다.
Refs: 1103/16-01
2026-11-06 02:12:06 +09:00

242 lines
7.4 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,
responseEnvelope: "NONE" 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,
responseEnvelope: "NONE" 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,
responseEnvelope: "NONE" 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([]),
});