Files
clean-architecture-frontend…/src/contracts/external-contract-runtime.ts
T

804 lines
26 KiB
TypeScript

/**
* External contract package consumer boundary (§4).
*
* This repository does not own OpenAPI/AsyncAPI source, operation semantics,
* Problem Details meaning or event payload schemas. It owns only the normalized
* descriptor interface, the runtime validator protocol, and the bounds it
* applies before a contribution may be composed.
*/
import { INSTALLED_REST_AUTH_PROFILES } from "./rest-profiles.ts";
import {
defineTrafficBudget,
TRAFFIC_BUDGET_KEYS,
type TrafficBudget,
} from "../platform/traffic/traffic-budget.ts";
import {
createReadOnlyRegistry,
exactOwnDataSnapshot,
type ReadOnlyRegistry,
} from "./read-only-registry.ts";
/** §7.3 hard ceilings. A contribution may lower these, never raise them. */
export const HTTP_EXECUTION_CEILINGS = Object.freeze({
defaultRequestBytes: 262_144,
hardRequestBytes: 1_048_576,
defaultResponseBytes: 1_048_576,
hardResponseBytes: 8_388_608,
problemResponseBytes: 65_536,
pathTemplateBytes: 512,
encodedQueryBytes: 8_192,
examinedHeaderValueBytes: 8_192,
defaultTotalDeadlineMs: 10_000,
hardTotalDeadlineMs: 60_000,
hardRetryCount: 2,
finalUrlBytes: 16_384,
});
export type RuntimeValidationIssue = Readonly<{
path: readonly (string | number)[];
code: string;
}>;
export type RuntimeValidationResult<T> =
| Readonly<{ success: true; data: T }>
| Readonly<{ success: false; issues: readonly RuntimeValidationIssue[] }>;
export interface RuntimeValidator<T> {
readonly schemaId: string;
safeParse(value: unknown): RuntimeValidationResult<T>;
}
/**
* A validator invocation never escapes as a native throw. `THROWN` is the
* `CONTRACT_RUNTIME_FAILURE` signal; `false` success is the ordinary
* `CONTRACT_VALUE_INVALID` signal.
*/
export type ValidatorInvocation<T> =
| Readonly<{ outcome: "VALID"; value: T }>
| Readonly<{ outcome: "INVALID"; issues: readonly RuntimeValidationIssue[] }>
| Readonly<{ outcome: "THROWN" }>;
export function invokeValidator<T>(
validator: RuntimeValidator<T>,
value: unknown,
): ValidatorInvocation<T> {
let result: RuntimeValidationResult<T>;
try {
result = validator.safeParse(value);
} catch {
return Object.freeze({ outcome: "THROWN" as const });
}
if (!result || typeof result !== "object" || !("success" in result)) {
return Object.freeze({ outcome: "THROWN" as const });
}
if (result.success) {
return Object.freeze({ outcome: "VALID" as const, value: result.data });
}
return Object.freeze({
outcome: "INVALID" as const,
issues: Object.freeze([...(result.issues ?? [])]),
});
}
export type MappingResult<T> =
| Readonly<{ ok: true; value: T }>
| Readonly<{
ok: false;
error: Readonly<{ kind: "MAPPING_CONTRACT_VIOLATION"; code: string }>;
}>;
export function mappingViolation(code: string): MappingResult<never> {
return Object.freeze({
ok: false as const,
error: Object.freeze({
kind: "MAPPING_CONTRACT_VIOLATION" as const,
code,
}),
});
}
export type CommandRecoveryDescriptor = Readonly<{
mode: "IDEMPOTENCY_REPLAY" | "INSPECT_OPERATION";
operationIdentityField: string;
inspectOperationId?: string;
}>;
export type CommandEffectClassification =
| "NOT_APPLIED"
| "APPLIED_CONFIRMED"
| "MAYBE_APPLIED";
export interface CommandEffectDescriptor<Problem> {
readonly successEffect: "APPLIED_CONFIRMED";
classifyProblem(
input: Readonly<{ status: number; problem: Problem }>,
): CommandEffectClassification;
}
export type HttpMethod =
| "GET"
| "HEAD"
| "POST"
| "PUT"
| "PATCH"
| "DELETE";
export type RetrySemantics = "SAFE" | "IDEMPOTENT" | "KEYED" | "NEVER";
export interface HttpExecutionPolicy {
readonly policyId: string;
readonly requestByteLimit: number;
readonly responseByteLimit: number;
readonly totalDeadlineMs: number;
readonly retryBudget: 0 | 1 | 2;
readonly authProfileId: string;
readonly diagnosticsOperation: string;
/**
* Spec §11. Optional operation-owned interaction traffic policy. When a
* caller supplies no interaction `ExecutionContext`, the executor creates one
* from this policy (or the bounded platform default), so every logical
* execution carries finite request/retry/concurrency budgets.
*/
readonly traffic?: TrafficBudget;
}
export interface InstalledHttpContract<Input, WireOutput, Problem> {
readonly contract: Readonly<{
operationId: string;
method: HttpMethod;
pathTemplate: string;
inputValidator: RuntimeValidator<Input>;
outputValidator: RuntimeValidator<WireOutput>;
problemValidator: RuntimeValidator<Problem>;
acceptedStatuses: readonly number[];
emptyBodyStatuses: readonly number[];
retrySemantics: RetrySemantics;
requestBody: "NONE" | "JSON";
responseBody: "REQUIRED_JSON" | "OPTIONAL_JSON" | "NONE";
commandRecovery: CommandRecoveryDescriptor | null;
commandEffect: CommandEffectDescriptor<Problem> | null;
/**
* Descriptor-owned projection from canonical application input to the wire
* request. The frontend never re-derives method, path or query semantics.
*/
projectRequest(input: Input): HttpRequestProjection;
}>;
readonly frontend: HttpExecutionPolicy;
}
export type HttpRequestProjection = Readonly<{
/** Ordered path placeholder values keyed by descriptor placeholder name. */
pathValues: Readonly<Record<string, string>>;
/** Descriptor-generated query entry order; array encoding is descriptor-owned. */
queryEntries: readonly (readonly [string, string])[];
/** Canonical JSON body value, or `null` when `requestBody` is `NONE`. */
body: unknown;
}>;
export interface InstalledEventContract<Envelope, Payload> {
readonly eventType: string;
readonly envelopeValidator: RuntimeValidator<Envelope>;
readonly payloadValidator: RuntimeValidator<Payload>;
}
export interface InstalledContractPackageIdentity {
readonly packageId: string;
readonly version: string;
readonly digest: `sha256:${string}`;
readonly runtimeProtocolVersion: 1;
readonly sourceRevision: string;
}
export type ContractContributionSource =
| Readonly<{
kind: "EXTERNAL_PACKAGE";
package: InstalledContractPackageIdentity;
}>
| Readonly<{
kind: "TEMPLATE_FIXTURE";
fixtureId: "REFERENCE_FEATURE_V1";
revision: 1;
}>;
export interface InstalledContractContribution {
readonly contributionId: string;
readonly featureId: string;
readonly source: ContractContributionSource;
readonly http: readonly InstalledHttpContract<unknown, unknown, unknown>[];
readonly events: readonly InstalledEventContract<unknown, unknown>[];
}
export type ContractCompositionFailureCode =
| "CONTRACT_CONTRIBUTION_INVALID"
| "CONTRACT_RUNTIME_PROTOCOL_UNSUPPORTED";
export class ContractContributionError extends Error {
readonly code: ContractCompositionFailureCode;
readonly reason: string;
constructor(reason: string, code: ContractCompositionFailureCode = "CONTRACT_CONTRIBUTION_INVALID") {
super("Installed contract contribution is not composable");
this.name = "ContractContributionError";
this.code = code;
this.reason = reason;
}
}
// §4.9 exact validation vocabulary.
const FEATURE_ID = /^[a-z][a-z0-9-]{0,63}$/;
const CONTRIBUTION_ID = /^[a-z][a-z0-9._-]{0,127}$/;
const PACKAGE_ID =
/^@[a-z0-9][a-z0-9._-]{0,62}\/[a-z0-9][a-z0-9._-]{0,62}$/;
const SEM_VER =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
const DIGEST = /^sha256:[0-9a-f]{64}$/;
const SOURCE_REVISION = /^[0-9a-f]{7,64}$/;
const OPERATION_ID = /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;
/** Whitespace and C0/C1 control characters are rejected in an event type. */
function hasControlOrSpace(value: string): boolean {
for (const character of value) {
const code = character.codePointAt(0) ?? 0;
if (code <= 0x20 || (code >= 0x7f && code <= 0x9f)) return true;
}
return false;
}
const encoder = new TextEncoder();
function utf8Bytes(value: string): number {
return encoder.encode(value).byteLength;
}
function fail(reason: string): never {
throw new ContractContributionError(reason);
}
function assertPackageIdentity(
identity: InstalledContractPackageIdentity,
featureId: string,
): void {
if (!identity || typeof identity !== "object") {
fail(`${featureId}: package identity`);
}
if (identity.runtimeProtocolVersion !== 1) {
throw new ContractContributionError(
`${featureId}: runtime protocol version must be exactly 1`,
"CONTRACT_RUNTIME_PROTOCOL_UNSUPPORTED",
);
}
if (!PACKAGE_ID.test(identity.packageId)) fail(`${featureId}: packageId`);
if (
typeof identity.version !== "string" ||
identity.version !== identity.version.trim() ||
identity.version.startsWith("v") ||
!SEM_VER.test(identity.version)
) {
fail(`${featureId}: package version must be exact SemVer`);
}
if (!DIGEST.test(identity.digest)) fail(`${featureId}: package digest`);
if (!SOURCE_REVISION.test(identity.sourceRevision)) {
fail(`${featureId}: package sourceRevision`);
}
}
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`);
}
}
function assertStatuses(
statuses: readonly number[],
label: string,
): void {
if (!Array.isArray(statuses)) fail(`${label}: status array required`);
if (statuses.length < 1 || statuses.length > 32) {
fail(`${label}: 1..32 statuses required`);
}
for (let index = 0; index < statuses.length; index += 1) {
const status = statuses[index] as number;
if (!Number.isInteger(status) || status < 100 || status > 599) {
fail(`${label}: status out of range`);
}
const previous = statuses[index - 1];
if (index > 0 && previous !== undefined && status <= previous) {
fail(`${label}: statuses must be sorted and unique`);
}
}
}
function assertExecutionPolicy(
policy: HttpExecutionPolicy,
label: string,
): void {
const ceilings = HTTP_EXECUTION_CEILINGS;
if (
!policy ||
typeof policy.policyId !== "string" ||
policy.policyId.length === 0 ||
typeof policy.authProfileId !== "string" ||
policy.authProfileId.length === 0 ||
typeof policy.diagnosticsOperation !== "string" ||
policy.diagnosticsOperation.length === 0
) {
fail(`${label}: frontend execution policy identity`);
}
// §7.7 / VD-23. A declared profile that the installed registry does not own
// is a composition failure; the executor must never resolve it at runtime.
if (!INSTALLED_REST_AUTH_PROFILES.has(policy.authProfileId)) {
fail(`${label}: unknown authProfileId ${policy.authProfileId}`);
}
if (
!Number.isSafeInteger(policy.requestByteLimit) ||
policy.requestByteLimit < 0 ||
policy.requestByteLimit > ceilings.hardRequestBytes
) {
fail(`${label}: requestByteLimit exceeds the hard ceiling`);
}
if (
!Number.isSafeInteger(policy.responseByteLimit) ||
policy.responseByteLimit < 1 ||
policy.responseByteLimit > ceilings.hardResponseBytes
) {
fail(`${label}: responseByteLimit exceeds the hard ceiling`);
}
if (
!Number.isSafeInteger(policy.totalDeadlineMs) ||
policy.totalDeadlineMs < 1 ||
policy.totalDeadlineMs > ceilings.hardTotalDeadlineMs
) {
fail(`${label}: totalDeadlineMs exceeds the hard ceiling`);
}
if (
policy.retryBudget !== 0 &&
policy.retryBudget !== 1 &&
policy.retryBudget !== 2
) {
fail(`${label}: retryBudget must be 0, 1 or 2`);
}
if (policy.traffic !== undefined) {
try {
defineTrafficBudget(policy.traffic);
} catch (error) {
fail(
`${label}: traffic policy ${error instanceof Error ? error.message : "invalid"}`,
);
}
}
}
function assertHttpContract(
installed: InstalledHttpContract<unknown, unknown, unknown>,
featureId: string,
): void {
const contract = installed?.contract;
if (!contract || typeof contract !== "object") {
fail(`${featureId}: http contract descriptor missing`);
}
const label = `${featureId}/${String(contract.operationId)}`;
if (
typeof contract.operationId !== "string" ||
!OPERATION_ID.test(contract.operationId)
) {
fail(`${label}: operationId`);
}
if (
contract.method !== "GET" &&
contract.method !== "HEAD" &&
contract.method !== "POST" &&
contract.method !== "PUT" &&
contract.method !== "PATCH" &&
contract.method !== "DELETE"
) {
fail(`${label}: method`);
}
if (
typeof contract.pathTemplate !== "string" ||
!contract.pathTemplate.startsWith("/") ||
utf8Bytes(contract.pathTemplate) > HTTP_EXECUTION_CEILINGS.pathTemplateBytes ||
contract.pathTemplate.includes("?") ||
contract.pathTemplate.includes("#")
) {
fail(`${label}: pathTemplate`);
}
assertValidator(contract.inputValidator, `${label}.input`);
assertValidator(contract.outputValidator, `${label}.output`);
assertValidator(contract.problemValidator, `${label}.problem`);
if (typeof contract.projectRequest !== "function") {
fail(`${label}: descriptor request projection is required`);
}
if (
contract.retrySemantics !== "SAFE" &&
contract.retrySemantics !== "IDEMPOTENT" &&
contract.retrySemantics !== "KEYED" &&
contract.retrySemantics !== "NEVER"
) {
fail(`${label}: retrySemantics`);
}
if (contract.requestBody !== "NONE" && contract.requestBody !== "JSON") {
fail(`${label}: requestBody`);
}
if (
contract.responseBody !== "REQUIRED_JSON" &&
contract.responseBody !== "OPTIONAL_JSON" &&
contract.responseBody !== "NONE"
) {
fail(`${label}: responseBody`);
}
assertStatuses(contract.acceptedStatuses, `${label}.acceptedStatuses`);
if (contract.emptyBodyStatuses.length > 0) {
assertStatuses(contract.emptyBodyStatuses, `${label}.emptyBodyStatuses`);
const accepted = new Set(contract.acceptedStatuses);
for (const status of contract.emptyBodyStatuses) {
if (!accepted.has(status)) {
fail(`${label}: empty-body status must be an accepted status`);
}
}
}
const isRead = contract.method === "GET" || contract.method === "HEAD";
if (isRead) {
if (contract.commandEffect !== null || contract.commandRecovery !== null) {
fail(`${label}: read operations carry no command descriptors`);
}
if (contract.requestBody !== "NONE") {
fail(`${label}: read operations carry no request body`);
}
} else {
if (!contract.commandEffect) {
fail(`${label}: command operations require a command effect descriptor`);
}
if (contract.commandEffect.successEffect !== "APPLIED_CONFIRMED") {
fail(`${label}: command success effect`);
}
if (typeof contract.commandEffect.classifyProblem !== "function") {
fail(`${label}: command effect classifier is required`);
}
if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) {
fail(`${label}: KEYED commands require a recovery descriptor`);
}
}
if (contract.commandRecovery) {
const recovery = contract.commandRecovery;
if (
(recovery.mode !== "IDEMPOTENCY_REPLAY" &&
recovery.mode !== "INSPECT_OPERATION") ||
!recovery.operationIdentityField ||
(recovery.mode === "INSPECT_OPERATION" && !recovery.inspectOperationId)
) {
fail(`${label}: command recovery descriptor`);
}
}
assertExecutionPolicy(installed.frontend, label);
if (
installed.frontend.retryBudget > 0 &&
contract.retrySemantics === "NEVER"
) {
fail(`${label}: retry budget contradicts NEVER retry semantics`);
}
}
function assertEventContract(
event: InstalledEventContract<unknown, unknown>,
featureId: string,
): void {
const label = `${featureId}/${String(event?.eventType)}`;
if (
typeof event?.eventType !== "string" ||
event.eventType.length === 0 ||
utf8Bytes(event.eventType) > 160 ||
hasControlOrSpace(event.eventType)
) {
fail(`${label}: eventType`);
}
assertValidator(event.envelopeValidator, `${label}.envelope`);
assertValidator(event.payloadValidator, `${label}.payload`);
}
export type ComposedContractContributions = Readonly<{
contributions: readonly InstalledContractContribution[];
/**
* LIVE-03. Read facades over private stores. The executor resolves an
* operation on every request, so an exported `Map` would let any holder of
* the composed singleton delete or replace a validated row after boot.
*/
httpByOperationId: ReadOnlyRegistry<
string,
InstalledHttpContract<unknown, unknown, unknown>
>;
eventByType: ReadOnlyRegistry<
string,
InstalledEventContract<unknown, unknown>
>;
externalPackages: readonly InstalledContractPackageIdentity[];
}>;
const EXECUTION_POLICY_KEYS = [
"policyId",
"requestByteLimit",
"responseByteLimit",
"totalDeadlineMs",
"retryBudget",
"authProfileId",
"diagnosticsOperation",
] as const;
const EXECUTION_POLICY_ALLOWED_KEYS = [
...EXECUTION_POLICY_KEYS,
"traffic",
] as const;
const HTTP_CONTRACT_KEYS = [
"operationId",
"method",
"pathTemplate",
"inputValidator",
"outputValidator",
"problemValidator",
"acceptedStatuses",
"emptyBodyStatuses",
"retrySemantics",
"requestBody",
"responseBody",
"commandRecovery",
"commandEffect",
"projectRequest",
] as const;
const COMMAND_RECOVERY_KEYS = [
"mode",
"operationIdentityField",
"inspectOperationId",
] as const;
/**
* LIVE-03. Composition is the last point at which a contribution row is
* trusted, so the registry keeps an exact own-data copy rather than the
* caller's object. A later mutation of the source — including one that swaps a
* deadline or a credential policy — cannot reach what the executor reads.
*
* Validators and the descriptor-owned `projectRequest` stay by reference: they
* are behaviour the contribution owns, not data this repository re-derives.
*/
function snapshotHttpContract(
installed: InstalledHttpContract<unknown, unknown, unknown>,
label: string,
): InstalledHttpContract<unknown, unknown, unknown> {
const reject = (detail: string): never => fail(`${label}: ${detail}`);
// NS-02. The outer row is snapshotted first, so every nested read below comes
// from an owned object rather than from the caller's, which could answer
// differently on a second read.
const row = exactOwnDataSnapshot<
InstalledHttpContract<unknown, unknown, unknown>
>(installed, ["contract", "frontend"], ["contract", "frontend"], reject);
const policy = exactOwnDataSnapshot<HttpExecutionPolicy>(
row.frontend,
EXECUTION_POLICY_ALLOWED_KEYS,
EXECUTION_POLICY_KEYS,
reject,
);
const frontend: HttpExecutionPolicy =
policy.traffic === undefined
? policy
: Object.freeze({
...policy,
traffic: exactOwnDataSnapshot<TrafficBudget>(
policy.traffic,
TRAFFIC_BUDGET_KEYS,
TRAFFIC_BUDGET_KEYS,
reject,
),
});
const source = exactOwnDataSnapshot<
InstalledHttpContract<unknown, unknown, unknown>["contract"]
>(row.contract, HTTP_CONTRACT_KEYS, HTTP_CONTRACT_KEYS, reject);
const contract = Object.freeze({
...source,
acceptedStatuses: Object.freeze([...source.acceptedStatuses]),
emptyBodyStatuses: Object.freeze([...source.emptyBodyStatuses]),
commandRecovery:
source.commandRecovery === null
? null
: exactOwnDataSnapshot<CommandRecoveryDescriptor>(
source.commandRecovery,
COMMAND_RECOVERY_KEYS,
["mode", "operationIdentityField"],
reject,
),
});
return Object.freeze({ contract, frontend });
}
function snapshotEventContract(
event: InstalledEventContract<unknown, unknown>,
label: string,
): InstalledEventContract<unknown, unknown> {
return exactOwnDataSnapshot<InstalledEventContract<unknown, unknown>>(
event,
["eventType", "envelopeValidator", "payloadValidator"],
["eventType", "envelopeValidator", "payloadValidator"],
(detail) => fail(`${label}: ${detail}`),
);
}
/**
* §4.8–§4.9. The only place installed contributions become a runtime registry.
* Every bound is checked before composition; a violation stops the boot rather
* than degrading into an assumed meaning.
*/
export function composeContractContributions(
contributions: readonly InstalledContractContribution[],
): ComposedContractContributions {
if (!Array.isArray(contributions)) fail("contributions: array required");
const httpByOperationId = new Map<
string,
InstalledHttpContract<unknown, unknown, unknown>
>();
const eventByType = new Map<
string,
InstalledEventContract<unknown, unknown>
>();
const packagesById = new Map<string, InstalledContractPackageIdentity>();
const contributionIds = new Set<string>();
const installedContributions: InstalledContractContribution[] = [];
for (const raw of contributions) {
if (!raw || typeof raw !== "object") {
fail("contribution: object required");
}
// NS-02. Snapshot first, then validate the snapshot, then install exactly
// what was validated. Validating the caller's object and reading it again
// to copy it let a stateful answer pass the ceiling check and still install
// a different deadline, retry budget or auth profile.
const contribution = exactOwnDataSnapshot<InstalledContractContribution>(
raw,
["contributionId", "featureId", "source", "http", "events"],
["contributionId", "featureId", "source", "http", "events"],
(detail) => fail(`contribution: ${detail}`),
);
const contributionId = contribution.contributionId;
if (
typeof contributionId !== "string" ||
!CONTRIBUTION_ID.test(contributionId)
) {
fail(`contributionId: ${String(contributionId)}`);
}
if (contributionIds.has(contributionId)) {
fail(`duplicate contributionId: ${contributionId}`);
}
contributionIds.add(contributionId);
const featureId = contribution?.featureId;
if (typeof featureId !== "string" || !FEATURE_ID.test(featureId)) {
fail(`featureId: ${String(featureId)}`);
}
const rawSource = contribution.source;
if (!rawSource || typeof rawSource !== "object" || !("kind" in rawSource)) {
fail(`${featureId}: source`);
}
if (!Array.isArray(contribution.http) || !Array.isArray(contribution.events)) {
fail(`${featureId}: contribution arrays`);
}
const rejectSource = (detail: string): never =>
fail(`${featureId}: source ${detail}`);
let source: ContractContributionSource;
if (rawSource.kind === "EXTERNAL_PACKAGE") {
const outer = exactOwnDataSnapshot<
Readonly<{ kind: "EXTERNAL_PACKAGE"; package: unknown }>
>(rawSource, ["kind", "package"], ["kind", "package"], rejectSource);
const identity = exactOwnDataSnapshot<InstalledContractPackageIdentity>(
outer.package,
[
"packageId",
"version",
"digest",
"runtimeProtocolVersion",
"sourceRevision",
],
[
"packageId",
"version",
"digest",
"runtimeProtocolVersion",
"sourceRevision",
],
rejectSource,
);
assertPackageIdentity(identity, featureId);
source = Object.freeze({
kind: "EXTERNAL_PACKAGE" as const,
package: identity,
});
const existing = packagesById.get(identity.packageId);
if (
existing &&
(existing.version !== identity.version ||
existing.digest !== identity.digest ||
existing.sourceRevision !== identity.sourceRevision)
) {
fail(
`${featureId}: package ${identity.packageId} has conflicting identities`,
);
}
packagesById.set(identity.packageId, identity);
} else if (rawSource.kind === "TEMPLATE_FIXTURE") {
const fixture = exactOwnDataSnapshot<
Readonly<{
kind: "TEMPLATE_FIXTURE";
fixtureId: "REFERENCE_FEATURE_V1";
revision: 1;
}>
>(
rawSource,
["kind", "fixtureId", "revision"],
["kind", "fixtureId", "revision"],
rejectSource,
);
if (
fixture.fixtureId !== "REFERENCE_FEATURE_V1" ||
fixture.revision !== 1
) {
fail(`${featureId}: template fixture identity`);
}
if (contribution.events.length !== 0) {
fail(`${featureId}: template fixture must not contribute events`);
}
source = fixture;
} else {
fail(`${featureId}: unknown contribution source kind`);
}
const installedHttp: InstalledHttpContract<unknown, unknown, unknown>[] = [];
for (const installed of contribution.http) {
const snapshot = snapshotHttpContract(installed, featureId);
assertHttpContract(snapshot, featureId);
const operationId = snapshot.contract.operationId;
const previous = httpByOperationId.get(operationId);
if (previous) fail(`duplicate operation: ${operationId}`);
httpByOperationId.set(operationId, snapshot);
installedHttp.push(snapshot);
}
const installedEvents: InstalledEventContract<unknown, unknown>[] = [];
for (const event of contribution.events) {
const snapshot = snapshotEventContract(event, featureId);
assertEventContract(snapshot, featureId);
if (eventByType.has(snapshot.eventType)) {
fail(`duplicate event type: ${snapshot.eventType}`);
}
eventByType.set(snapshot.eventType, snapshot);
installedEvents.push(snapshot);
}
// Everything published downstream is the validated snapshot, so no consumer
// can be handed the caller's still-live object.
installedContributions.push(
Object.freeze({
contributionId,
featureId,
source,
http: Object.freeze(installedHttp),
events: Object.freeze(installedEvents),
}),
);
}
const externalPackages = [...packagesById.values()].map((identity) =>
Object.freeze({ ...identity }),
);
return Object.freeze({
contributions: Object.freeze(installedContributions),
httpByOperationId: createReadOnlyRegistry(httpByOperationId),
eventByType: createReadOnlyRegistry(eventByType),
externalPackages: Object.freeze(externalPackages),
});
}