import { readFile, mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import process from "node:process"; import { fileURLToPath } from "node:url"; const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); const schemaPath = path.join( rootDir, "packages/plugin-contract/schema/plugin-contract.schema.json", ); const generatedTypesPath = path.join( rootDir, "packages/plugin-contract/src/generated/plugin-contract.ts", ); const electronBundlePath = path.join( rootDir, "electron/plugins/generated/plugin-contract.schema.json", ); const checkOnly = process.argv.includes("--check"); const schemaText = await readFile(schemaPath, "utf8"); const schema = JSON.parse(schemaText); if (schema.$schema !== "https://json-schema.org/draft/2020-12/schema") { throw new Error("Plugin contract must use JSON Schema 2020-12"); } if (!schema.$id?.includes("/0.1.0-internal/")) { throw new Error("Plugin contract $id must include the internal API version"); } if (!schema.$defs || typeof schema.$defs !== "object") { throw new Error("Plugin contract must define $defs"); } function quoteProperty(name) { return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : JSON.stringify(name); } function literal(value) { return JSON.stringify(value); } function referenceName(reference) { const prefix = "#/$defs/"; if (typeof reference !== "string" || !reference.startsWith(prefix)) { throw new Error(`Unsupported schema reference: ${String(reference)}`); } return decodeURIComponent(reference.slice(prefix.length)); } function schemaTypeToTs(node, level = 0) { if (node === true) return "unknown"; if (node === false) return "never"; if (!node || typeof node !== "object") return "unknown"; if ("$ref" in node) return referenceName(node.$ref); if ("const" in node) return literal(node.const); if (Array.isArray(node.enum)) return node.enum.map(literal).join(" | ") || "never"; for (const keyword of ["oneOf", "anyOf"]) { if (Array.isArray(node[keyword])) { return node[keyword].map((entry) => `(${schemaTypeToTs(entry, level)})`).join(" | "); } } if (Array.isArray(node.allOf)) { return node.allOf.map((entry) => `(${schemaTypeToTs(entry, level)})`).join(" & "); } if (Array.isArray(node.type)) { return node.type.map((entry) => schemaTypeToTs({ ...node, type: entry }, level)).join(" | "); } if (node.type === "null") return "null"; if (node.type === "string") return "string"; if (node.type === "number" || node.type === "integer") return "number"; if (node.type === "boolean") return "boolean"; if (node.type === "array") { return `Array<${schemaTypeToTs(node.items ?? true, level)}>`; } if (node.type === "object" || node.properties || node.additionalProperties) { const properties = node.properties ?? {}; const entries = Object.entries(properties); const required = new Set(node.required ?? []); const additional = node.additionalProperties; if (entries.length === 0) { if (additional && typeof additional === "object") { return `{ [key: string]: ${schemaTypeToTs(additional, level)} }`; } return additional === false ? "Record" : "Record"; } const indent = " ".repeat(level + 1); const closingIndent = " ".repeat(level); const body = entries.map(([name, propertySchema]) => { const optional = required.has(name) ? "" : "?"; return `${indent}${quoteProperty(name)}${optional}: ${schemaTypeToTs(propertySchema, level + 1)};`; }); let objectType = `{\n${body.join("\n")}\n${closingIndent}}`; if (additional && typeof additional === "object") { objectType = `(${objectType} & Record)`; } return objectType; } return "unknown"; } const definitionNames = Object.keys(schema.$defs).sort((left, right) => left.localeCompare(right, "en"), ); const generatedTypes = [ "// This file is generated from schema/plugin-contract.schema.json.", "// Run `npm run generate:plugin-contract` after changing the contract.", "// Do not edit this file directly.", "", ...definitionNames.flatMap((name) => [ `export type ${name} = ${schemaTypeToTs(schema.$defs[name])};`, "", ]), ].join("\n"); const normalizedSchema = `${JSON.stringify(schema, null, 2)}\n`; async function assertCurrent(filePath, expected, label) { let actual; try { actual = await readFile(filePath, "utf8"); } catch { throw new Error(`${label} is missing. Run npm run generate:plugin-contract.`); } if (actual !== expected) { throw new Error(`${label} is out of date. Run npm run generate:plugin-contract.`); } } if (checkOnly) { await assertCurrent(generatedTypesPath, generatedTypes, "Generated plugin TypeScript contract"); await assertCurrent(electronBundlePath, normalizedSchema, "Electron plugin schema bundle"); console.log("Plugin contract generated artifacts are current."); } else { await mkdir(path.dirname(generatedTypesPath), { recursive: true }); await mkdir(path.dirname(electronBundlePath), { recursive: true }); await Promise.all([ writeFile(generatedTypesPath, generatedTypes, "utf8"), writeFile(electronBundlePath, normalizedSchema, "utf8"), ]); console.log("Generated plugin TypeScript contract and Electron schema bundle."); }