|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import { writeFileSync } from "node:fs"; |
| 4 | +import { join } from "node:path"; |
| 5 | +import { createGenerator } from "ts-json-schema-generator"; |
| 6 | + |
| 7 | +const __dirname = new URL(".", import.meta.url).pathname; |
| 8 | +const packageRoot = join(__dirname, "..", "src"); |
| 9 | + |
| 10 | +/** |
| 11 | + * post-process the schema recursively to: |
| 12 | + * 1. replace any key named `defaultValue` with `default` |
| 13 | + * 1. remove any backticks from the value |
| 14 | + * 1. attempt to parsing the value as JSON (falling back, if not) |
| 15 | + */ |
| 16 | +const postProcess = <T>(item: T): T => { |
| 17 | + if (typeof item !== "object" || item === null) { |
| 18 | + return item; |
| 19 | + } |
| 20 | + if (Array.isArray(item)) { |
| 21 | + return item.map(postProcess) as unknown as T; |
| 22 | + } |
| 23 | + return Object.fromEntries( |
| 24 | + Object.entries(item).map(([key, value]) => { |
| 25 | + if (key === "defaultValue" && typeof value === "string") { |
| 26 | + const replaced = value.replaceAll(/`/g, ""); |
| 27 | + try { |
| 28 | + return ["default", JSON.parse(replaced)]; |
| 29 | + } catch (e) { |
| 30 | + return ["default", replaced]; |
| 31 | + } |
| 32 | + } |
| 33 | + return [key, postProcess(value)]; |
| 34 | + }) |
| 35 | + ) as T; |
| 36 | +}; |
| 37 | + |
| 38 | +const create = (fileName: string, typeName: string) => { |
| 39 | + const generator = createGenerator({ |
| 40 | + path: join(packageRoot, "index.ts"), |
| 41 | + tsconfig: join(__dirname, "../tsconfig.json"), |
| 42 | + type: "Schema", |
| 43 | + extraTags: ["defaultValue"], |
| 44 | + }); |
| 45 | + const schema = postProcess(generator.createSchema(typeName)); |
| 46 | + const filePath = join(__dirname, "..", "schemas", fileName); |
| 47 | + writeFileSync(filePath, JSON.stringify(schema, null, 2)); |
| 48 | +}; |
| 49 | + |
| 50 | +create("schema.v1.json", "SchemaV1"); |
| 51 | +create("schema.v2.json", "Schema"); |
| 52 | +create("schema.json", "Schema"); |
0 commit comments