generated from polymech/site-template
65 lines
2.2 KiB
TypeScript
65 lines
2.2 KiB
TypeScript
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { quicktype, InputData, jsonInputForTargetLanguage } from 'quicktype-core';
|
|
|
|
const CONFIG_PATH = path.resolve('./app-config.json');
|
|
const OUTPUT_SCHEMA_PATH = path.resolve('./src/app/config.schema.ts');
|
|
const OUTPUT_DTS_PATH = path.resolve('./src/app/config.d.ts');
|
|
|
|
async function main() {
|
|
console.log(`Reading config from ${CONFIG_PATH}...`);
|
|
const configContent = fs.readFileSync(CONFIG_PATH, 'utf8');
|
|
|
|
// 1. Generate TypeScript Definitions (d.ts) FIRST
|
|
console.log('Generating TypeScript definitions...');
|
|
|
|
const tsInput = jsonInputForTargetLanguage("ts");
|
|
await tsInput.addSource({
|
|
name: "AppConfig",
|
|
samples: [configContent]
|
|
});
|
|
|
|
const tsInputData = new InputData();
|
|
tsInputData.addInput(tsInput);
|
|
|
|
const tsResult = await quicktype({
|
|
inputData: tsInputData,
|
|
lang: "ts",
|
|
rendererOptions: {
|
|
"just-types": "true",
|
|
"acronym-style": "original"
|
|
}
|
|
});
|
|
|
|
const tsCode = tsResult.lines.join('\n');
|
|
fs.writeFileSync(OUTPUT_DTS_PATH, tsCode);
|
|
console.log(`Wrote TypeScript definitions to ${OUTPUT_DTS_PATH}`);
|
|
|
|
// 2. Generate Zod Schema from Types using ts-to-zod
|
|
console.log('Generating Zod schema from types...');
|
|
|
|
try {
|
|
const { execSync } = await import('child_process');
|
|
// ts-to-zod <input> <output>
|
|
// Use relative paths to avoid Windows path concatenation issues with ts-to-zod
|
|
const relDts = path.relative(process.cwd(), OUTPUT_DTS_PATH);
|
|
const relSchema = path.relative(process.cwd(), OUTPUT_SCHEMA_PATH);
|
|
|
|
execSync(`npx ts-to-zod "${relDts}" "${relSchema}"`, { stdio: 'inherit', cwd: process.cwd() });
|
|
|
|
// Append export type AppConfig
|
|
fs.appendFileSync(OUTPUT_SCHEMA_PATH, `\nexport type AppConfig = z.infer<typeof appConfigSchema>;\n`);
|
|
|
|
console.log(`Wrote Zod schema to ${OUTPUT_SCHEMA_PATH}`);
|
|
} catch (error) {
|
|
console.error('Failed to generate Zod schema:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
main().catch(err => {
|
|
console.error('Error fetching/generating config:', err);
|
|
process.exit(1);
|
|
});
|