import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { compile } from "json-schema-to-typescript"; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const packageRoot = path.resolve(__dirname, ".."); const cultLibRoot = path.resolve(packageRoot, "..", ".."); const manifestPath = path.join(packageRoot, "tools", "swarm-contracts.manifest.json"); const outputPath = path.join(packageRoot, "src", "generated", "swarm-contracts.generated.ts"); // CultLib/contracts/cultnet is the single source of CultNet schema contracts // (REC-032). cultnet-ts is a standalone npm package (published or vendored by // Heimdall independent of the CultLib checkout), so it cannot import schemas // that live outside its own package tree. Mirror the canonical contracts into // a package-local, gitignored copy every time this generator runs, so `dist` // and `contracts` both ship self-contained. Wipe first: a stale local file // left behind after a schema is deleted upstream must not survive as drift. const sourceContractsDir = path.join(cultLibRoot, "contracts", "cultnet"); const localContractsDir = path.join(packageRoot, "contracts", "cultnet"); await rm(localContractsDir, { recursive: true, force: true }); await mkdir(path.dirname(localContractsDir), { recursive: true }); await cp(sourceContractsDir, localContractsDir, { recursive: true }); /** * @typedef {{ * schemaPath: string; * typeName: string; * contractExportName: string; * validateExportName: string; * parseExportName: string; * }} ContractManifestEntry */ /** @type {{ contracts: ContractManifestEntry[] }} */ const manifest = JSON.parse(await readFile(manifestPath, "utf8")); const importLines = [ 'import { defineJsonSchemaContract } from "../json-schema-contract";', ]; const sections = [ "// Generated by tools/generate-swarm-contracts.mjs. Do not hand-edit this file unless you enjoy losing arguments with a machine.", ]; for (const entry of manifest.contracts) { const absoluteSchemaPath = path.resolve(path.dirname(manifestPath), entry.schemaPath); const schema = JSON.parse(await readFile(absoluteSchemaPath, "utf8")); const schemaForTypes = structuredClone(schema); delete schemaForTypes.title; const schemaImportName = toIdentifier(`${entry.contractExportName}Schema`); const relativeImportPath = path.relative(path.dirname(outputPath), absoluteSchemaPath).replace(/\\/g, "/"); importLines.push(`import ${schemaImportName} from "${ensureRelativeModule(relativeImportPath)}";`); const rawTypeSource = await compile(schemaForTypes, entry.typeName, { bannerComment: "", style: { singleQuote: true, semi: true, }, }); const typeSource = rewriteRootTypeName(rawTypeSource, entry.typeName); sections.push(typeSource.trim()); sections.push(` export const ${entry.contractExportName} = defineJsonSchemaContract<${entry.typeName}>({ schemaId: ${JSON.stringify(schema.$id ?? entry.typeName)}, schema: ${schemaImportName}, }); export function ${entry.validateExportName}(value: unknown): value is ${entry.typeName} { return ${entry.contractExportName}.validate(value); } export function ${entry.parseExportName}(value: unknown): ${entry.typeName} { return ${entry.contractExportName}.parse(value); }`.trim()); } const output = `${importLines.join("\n")}\n\n${sections.join("\n\n")}\n`; await mkdir(path.dirname(outputPath), { recursive: true }); await writeFile(outputPath, output, "utf8"); function ensureRelativeModule(value) { return value.startsWith(".") ? value : `./${value}`; } function toIdentifier(value) { return value.replace(/[^a-zA-Z0-9_$]/g, "_"); } function rewriteRootTypeName(typeSource, desiredTypeName) { return typeSource.replace( /export\s+(interface|type)\s+([A-Za-z0-9_$]+)/u, (_match, kind) => `export ${kind} ${desiredTypeName}`, ); }