js-rln/scripts/schema_validator_codegen.js

78 lines
2.1 KiB
JavaScript
Raw Normal View History

import { writeFileSync } from "fs";
import { join } from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";
import Ajv from "ajv";
import addFormats from "ajv-formats";
import standaloneCode from "ajv/dist/standalone/index.js";
import keystoreSchema from "./nwaku_keystore.json" assert { type: "json" };
import credentialSchema from "./nwaku_keystore_credential.json" assert { type: "json" };
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Generate a function that validates the Keystore schema.
// Write the function to a file in the source.
const OUTPUT_DIR = join(__dirname, "../src/keystore");
const OUTPUT_KEYSTORE_FILE = join(
OUTPUT_DIR,
"keystore_validation_generated.ts"
);
const OUTPUT_CREDENTIALS_FILE = join(
OUTPUT_DIR,
"credential_validation_generated.ts"
);
// Initialize ajv instance
let ajv = new Ajv({
schemas: [keystoreSchema],
code: {
source: true,
esm: true,
},
});
addFormats(ajv);
// The output code is minified vanilla javascript and uses the cute pattern of attaching errors to the exported function as a property.
// The easiest way to treat this is to just ts-ignore the whole output and wrap the function with a handcrafted type.
const keystoreModuleCode =
`
/* eslint eslint-comments/no-unlimited-disable: "off" */
// This file was generated by /scripts/schema-validation-codegen.ts
// Do not modify this file by hand.
/* eslint-disable */
// @ts-ignore
` +
standaloneCode(ajv, {
Keystore: "#/definitions/Keystore",
});
ajv = new Ajv({
schemas: [credentialSchema],
code: {
source: true,
esm: true,
},
});
addFormats(ajv);
const credentialModuleCode =
`
/* eslint eslint-comments/no-unlimited-disable: "off" */
// This file was generated by /scripts/schema-validation-codegen.ts
// Do not modify this file by hand.
/* eslint-disable */
// @ts-ignore
` +
standaloneCode(ajv, {
Credential: "#/definitions/Credential",
});
writeFileSync(OUTPUT_KEYSTORE_FILE, keystoreModuleCode);
writeFileSync(OUTPUT_CREDENTIALS_FILE, credentialModuleCode);