|
| 1 | +import $RefParser from '@apidevtools/json-schema-ref-parser'; |
| 2 | +import { writeFileSync } from 'fs'; |
| 3 | +import { basename, extname } from 'path'; |
| 4 | + |
| 5 | +const inputFile = process.argv[2]; |
| 6 | +const outputFile = process.argv[3] |
| 7 | + |
| 8 | +if (!inputFile || !outputFile) { |
| 9 | + console.error('Usage: node scripts/schema-to-data.js <inputPath> <outputPath>'); |
| 10 | + process.exit(1); |
| 11 | +} |
| 12 | + |
| 13 | +function processProperty(name, prop, required = []) { |
| 14 | + const base = { |
| 15 | + name, |
| 16 | + required: required.includes(name), |
| 17 | + description: prop.description || '', |
| 18 | + default: prop.default ?? null, |
| 19 | + enum: prop.enum || null, |
| 20 | + properties: null, |
| 21 | + variants: null, |
| 22 | + }; |
| 23 | + |
| 24 | + if (prop.type && prop.type !== 'object') { |
| 25 | + return { ...base, type: prop.type }; |
| 26 | + } |
| 27 | + |
| 28 | + if (prop.type === 'object' || prop.properties) { |
| 29 | + return { |
| 30 | + ...base, |
| 31 | + type: 'object', |
| 32 | + properties: processSchema(prop), |
| 33 | + }; |
| 34 | + } |
| 35 | + |
| 36 | + if (prop.type === 'array' && prop.items) { |
| 37 | + const items = prop.items; |
| 38 | + return { |
| 39 | + ...base, |
| 40 | + type: 'array', |
| 41 | + items: items.properties |
| 42 | + ? { type: 'object', properties: processSchema(items) } |
| 43 | + : { type: items.type || 'any' }, |
| 44 | + }; |
| 45 | + } |
| 46 | + |
| 47 | + const combiner = ['anyOf', 'oneOf', 'allOf'].find(k => prop[k]); |
| 48 | + if (combiner) { |
| 49 | + return { |
| 50 | + ...base, |
| 51 | + type: combiner, |
| 52 | + variants: prop[combiner].map((variant, i) => ({ |
| 53 | + name: variant.title || `Option ${i + 1}`, |
| 54 | + description: variant.description || '', |
| 55 | + type: variant.type || 'object', |
| 56 | + properties: variant.properties ? processSchema(variant) : null, |
| 57 | + })), |
| 58 | + }; |
| 59 | + } |
| 60 | + |
| 61 | + return { ...base, type: 'any' }; |
| 62 | +} |
| 63 | + |
| 64 | +function processSchema(schema) { |
| 65 | + return Object.entries(schema.properties || {}).map(([name, prop]) => |
| 66 | + processProperty(name, prop, schema.required || []) |
| 67 | + ); |
| 68 | +} |
| 69 | + |
| 70 | +try { |
| 71 | + const schema = await $RefParser.dereference(inputFile); |
| 72 | + |
| 73 | + const data = { |
| 74 | + title: schema.title || '', |
| 75 | + description: schema.description || '', |
| 76 | + properties: processSchema(schema), |
| 77 | + }; |
| 78 | + |
| 79 | + writeFileSync(outputFile, JSON.stringify(data, null, 2)); |
| 80 | + console.log(`Written to ${outputFile}`); |
| 81 | +} catch (err) { |
| 82 | + console.error('Failed to process schema:', err.message); |
| 83 | + process.exit(1); |
| 84 | +} |
0 commit comments