import { mkdir, readFile, writeFile } from "node:fs/promises"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const schemaDirectory = resolve(packageRoot, "protocol/schemas"); const outputPath = resolve( packageRoot, "src/protocol/generated/schema-bundle.ts", ); const schemaNames = [ "identity", "capabilities", "command", "provider-descriptor", "provider-event", "workspace-diff", "workspace-file-reference", "semantic-tool", "usage", "stop-reason", "terminal", "question-set", "question-response", "question-adapter-fixture", "request", "result", "event", "fixture", ]; const schemas = await Promise.all( schemaNames.map(async (name) => ({ name, value: JSON.parse( await readFile(resolve(schemaDirectory, `${name}.schema.json`), "utf8"), ), })), ); const identifier = (name) => name.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase()); const declarations = schemas .map( ({ name, value }) => `export const ${identifier(name)}Schema = ${JSON.stringify(value, null, 2)} as const;`, ) .join("\n\n"); const bundle = schemaNames .map((name) => ` ${JSON.stringify(name)}: ${identifier(name)}Schema,`) .join("\n"); const generated = `// Generated by scripts/generate-protocol-schema-module.mjs. Do not edit.\n\n${declarations}\n\nexport const prpSchemaBundle = {\n${bundle}\n} as const;\n`; if (process.argv.includes("--check")) { const current = await readFile(outputPath, "utf8").catch(() => ""); if (current !== generated) { process.stderr.write( "Generated PRP schema module is stale. Run pnpm generate:protocol-types.\n", ); process.exitCode = 1; } else { process.stdout.write( "Generated PRP schema module matches the JSON Schema sources.\n", ); } } else { await mkdir(dirname(outputPath), { recursive: true }); await writeFile(outputPath, generated); process.stdout.write("Generated PRP schema module.\n"); }