import { writeFile } from "node:fs/promises"; import { resolve } from "node:path"; import openapiTS, { astToString, COMMENT_HEADER } from "openapi-typescript"; const schemaUrl = process.env.OPENAPI_SCHEMA_URL ?? "http://127.0.0.1:8000/openapi.json"; const outputPath = resolve("src/api/schema.generated.ts"); const requiredPaths = ["/api/v1/demo/status", "/api/v1/demo/search"]; const response = await fetch(schemaUrl, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(10_000), }); if (!response.ok) { throw new Error(`OpenAPI schema request failed with HTTP ${response.status}`); } const schema = await response.json(); if (typeof schema !== "object" || schema === null || !("paths" in schema)) { throw new Error("OpenAPI response does not contain a paths object"); } const paths = schema.paths; if (typeof paths !== "object" || paths === null) { throw new Error("OpenAPI paths value is invalid"); } for (const path of requiredPaths) { if (!(path in paths)) { throw new Error(`Required API path is missing: ${path}`); } } const ast = await openapiTS(schema, { alphabetize: true, immutable: true, }); await writeFile(outputPath, `${COMMENT_HEADER}${astToString(ast)}`, "utf8"); console.log(`Generated ${outputPath} from ${schemaUrl}`);