import { existsSync, readFileSync, readdirSync } from "node:fs"; import { resolve, relative } from "node:path"; import SwaggerParser from "@apidevtools/swagger-parser"; import { parse } from "yaml"; import { assert, expect, it } from "vitest"; import { velocityAccessRequestSchema, velocityConnectionRequestSchema } from "@minecraft-account-manager/contracts"; import { assertResponse, assertSchema, loadContract } from "@/test/openapi-contract"; const root = resolve(process.cwd(), "../.."); const canonical = resolve(root, "openapi.yaml"); it("publishes a valid OpenAPI 3.1 contract covering every application API", async () => { expect(existsSync(canonical), "root openapi.yaml must exist").toBe(true); const doc = parse(readFileSync(canonical, "utf8")); expect(doc.openapi).toBe("3.1.0"); await SwaggerParser.validate(structuredClone(doc)); const api = resolve(process.cwd(), "src/app/api"); const routes = readdirSync(api, { recursive: true, withFileTypes: true }) .filter((entry) => entry.isFile() && entry.name === "route.ts") .map((entry) => relative(api, resolve(entry.parentPath, entry.name)).replace(/\/route\.ts$/, "").replace(/\[([^\]]+)\]/g, "{$1}")) .filter((path) => !["route.ts", "{...path}", "auth/{...nextauth}"].includes(path)) .map((path) => `/api/${path}`); expect(Object.keys(doc.paths).filter((path) => path.startsWith("/api/")).sort()).toEqual(routes.sort()); for (const path of routes) { const source = readFileSync(resolve(api, path.slice(5).replace(/\{([^}]+)\}/g, "[$1]"), "route.ts"), "utf8"); const methods = [...source.matchAll(/export (?:async )?(?:function|const) (GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\b/g)].map((match) => match[1]!.toLowerCase()); for (const method of methods) expect(doc.paths[path][method], `${method} ${path} must be documented`).toBeDefined(); if (methods.includes("get")) expect(doc.paths[path].head).toBeDefined(); } const ids = new Set(); for (const [path, item] of Object.entries(doc.paths) as [string, Record>][]) { for (const [method, operation] of Object.entries(item)) { if (!["get", "head", "post", "put", "patch", "delete", "options"].includes(method)) continue; expect(operation.summary, `${method} ${path}`).toBeTruthy(); expect(operation.description).toBeTruthy(); expect(ids.has(operation.operationId as string)).toBe(false); ids.add(operation.operationId as string); expect(operation.operationId).toBeTruthy(); if (path.startsWith("/api/suggestions") || path === "/api/admin/whoami") { expect(operation.security).toEqual([{ AdminSession: [] }, { AdminBearer: [] }]); } else if (path.startsWith("/api/velocity") && method === "post") { expect(operation.security).toEqual([{ VelocitySecret: [] }]); } } } }); it("validates examples as JSON Schema 2020-12 and against real Velocity request parsers", async () => { const doc = await loadContract(); for (const item of Object.values(doc.paths)) for (const operation of Object.values(item)) { for (const response of Object.values(operation.responses)) { for (const content of Object.values(response.content ?? {})) { for (const example of Object.values(content.examples ?? {})) assertSchema(content.schema, example.value); } } for (const content of Object.values(operation.requestBody?.content ?? {})) { for (const example of Object.values(content.examples ?? {})) assertSchema(content.schema, example.value); } } for (const [kind, schema] of [["access", velocityAccessRequestSchema], ["connection", velocityConnectionRequestSchema]] as const) { const content = doc.paths[`/api/velocity/${kind}`]?.post?.requestBody?.content["application/json"]; assert(content); for (const example of Object.values(content.examples ?? {})) expect(schema.safeParse(example.value).success).toBe(true); } }); it("contract checking rejects wrong status, media type and response data", async () => { await expect(assertResponse("/api/admin/whoami", "get", Response.json({ authenticationMethod: "bearer", subject: null, name: null, email: null }, { headers: { "cache-control": "no-store" } }))).rejects.toThrow(); await expect(assertResponse("/api/admin/whoami", "get", new Response("{}", { headers: { "cache-control": "no-store" } }))).rejects.toThrow(); await expect(assertResponse("/api/admin/whoami", "get", Response.json({}, { status: 418 }))).rejects.toThrow(); const wrongStatus = Response.json({ type: "urn:error:unauthorized", title: "Unauthorized", status: 403 }, { status: 401, headers: { "content-type": "application/problem+json", "cache-control": "no-store", "www-authenticate": 'Bearer realm="admin-api"' } }); await expect(assertResponse("/api/admin/whoami", "get", wrongStatus)).rejects.toThrow(); }); it("rejects an invalid OpenAPI document (not just parseable YAML)", async () => { await expect(SwaggerParser.validate({ openapi: "3.1.0", info: { title: "Broken", version: "1" }, paths: { "/broken": { get: { responses: { "200": { description: "ok", content: { "application/json": { schema: { $ref: "#/components/schemas/Missing" } } } } } } } } } as never)).rejects.toThrow(); });