Files
xo-cash-utils/scripts/generate-schema.js
2026-01-25 12:51:34 +00:00

58 lines
2.1 KiB
JavaScript

#!/usr/bin/env node
import { execSync } from 'child_process';
import { readFileSync, writeFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = join(__dirname, '..');
// exec helper
const exec = (command, options = {}) => {
const defaultOptions = {
stdio: 'inherit',
cwd: rootDir,
shell: true,
...options,
};
return execSync(command, defaultOptions);
};
try {
const schemaPath = join(rootDir, 'source/parser/xo-template.schema.json');
const validatorPath = join(rootDir, 'source/parser/ajv/validate-xo-template.js');
const tsconfigPath = join(rootDir, 'tsconfig.json');
// Point directly to the dist file - the type is exported at the end via barrel export
const templatePath = join(rootDir, 'node_modules/@xo-cash/types/dist/index.d.ts');
// Generate schema JSON (write to file directly instead of shell redirection)
// Using --no-type-check to skip type checking and --expose all to find types exported via barrel exports
const schemaContent = execSync(
`ts-json-schema-generator --no-ref-encode --no-type-check --expose all --tsconfig "${tsconfigPath}" --path "${templatePath}" --type "XOTemplate"`,
{ encoding: 'utf8', cwd: rootDir },
);
writeFileSync(schemaPath, schemaContent, 'utf8');
// Compile validator with AJV
exec(`ajv compile -s "${schemaPath}" --allowUnionTypes --all-errors -o "${validatorPath}"`);
// Transform the generated validator code
let code = readFileSync(validatorPath, 'utf8');
code = code
.replace(/"use strict";module\.exports = [^;]+;module\.exports\.default = [^;]+;/, 'export default validate20;')
.replace(/;const /g, ';\nconst ')
.replace(/;function /g, ';\nfunction ')
.replace(/\}function /g, '}\nfunction ');
writeFileSync(validatorPath, code, 'utf8');
console.log('Schema generation complete!');
} catch (error) {
console.error('Error generating schema:', error.message);
process.exit(1);
}