CultLib/packages/cultnet-ts/tools/generate-swarm-contracts.mjs
2026-05-30 00:39:39 +01:00

84 lines
2.9 KiB
JavaScript

import { mkdir, readFile, 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 repoRoot = path.resolve(__dirname, "..");
const manifestPath = path.join(repoRoot, "contracts", "swarm-contracts.manifest.json");
const outputPath = path.join(repoRoot, "src", "generated", "swarm-contracts.generated.ts");
/**
* @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}`,
);
}