import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import SwaggerParser from "@apidevtools/swagger-parser"; import Ajv2020 from "ajv/dist/2020"; import addFormats from "ajv-formats"; import { parse } from "yaml"; import { assert, expect } from "vitest"; type Schema = Record; type ResponseContract = { headers?: Record; content?: Record }>; }; type Operation = { security?: Record[]; responses: Record; requestBody?: { content: Record }> } }; export type Contract = { paths: Record> }; const ajv = new Ajv2020({ strict: false, allErrors: true }); addFormats(ajv); let contract: Promise | undefined; export function loadContract() { return contract ??= SwaggerParser.dereference(parse(readFileSync(resolve(process.cwd(), "../../openapi.yaml"), "utf8"))).then((doc) => doc as unknown as Contract); } export function assertSchema(schema: Schema, value: unknown) { const validate = ajv.compile(schema); expect(validate(value), JSON.stringify(validate.errors)).toBe(true); } /** Clone preserves the body for existing behavior assertions. Never mock handlers. */ export async function assertResponse(path: string, method: string, response: Response) { const doc = await loadContract(); const operation = doc.paths[path]?.[method.toLowerCase()]; assert(operation, `undocumented operation: ${method} ${path}`); const expected = operation.responses[String(response.status)]; assert(expected, `undocumented HTTP ${response.status}: ${method} ${path}`); for (const [name, header] of Object.entries(expected.headers ?? {})) { const value = response.headers.get(name); if (name.toLowerCase() === "retry-after" && value === null) continue; expect(value, `missing ${name}`).not.toBeNull(); assertSchema(header.schema, header.schema.type === "integer" ? Number(value) : value); } const body = response.clone(); if (!expected.content) { expect(await body.text()).toBe(""); return; } const mediaType = response.headers.get("content-type")?.split(";", 1)[0]; expect(mediaType).toBeTruthy(); const content = expected.content[mediaType!]; assert(content, `undocumented Content-Type: ${mediaType}`); const value = await body.json(); assertSchema(content.schema, value); if (mediaType === "application/problem+json") expect(value.status).toBe(response.status); }