1import * as fs from "fs/promises"
2import * as fsSync from "fs"
3import * as path from "path"
4import { compile } from "json-schema-to-typescript"
5
6const BANNER = `/*
7* This file is autogenerated
8*/\n\n`
9const dirname = __dirname
10
11async function main() {
12 const schemas_path = path.join(dirname, "../../", "crates/theme/schemas")
13 const schema_files = (await fs.readdir(schemas_path)).filter((x) =>
14 x.endsWith(".json")
15 )
16
17 const compiled_types = new Set()
18
19 for (const filename of schema_files) {
20 const file_path = path.join(schemas_path, filename)
21 const file_contents = await fs.readFile(file_path)
22 const schema = JSON.parse(file_contents.toString())
23 const compiled = await compile(schema, schema.title, {
24 bannerComment: "",
25 })
26 const each_type = compiled.split("export")
27 for (const type of each_type) {
28 if (!type) {
29 continue
30 }
31 compiled_types.add("export " + type.trim())
32 }
33 }
34
35 const output = BANNER + Array.from(compiled_types).join("\n\n")
36 const output_path = path.join(dirname, "../../styles/src/types/zed.ts")
37
38 try {
39 const existing = await fs.readFile(output_path)
40 if (existing.toString() == output) {
41 // Skip writing if it hasn't changed
42 console.log("Schemas are up to date")
43 return
44 }
45 } catch (e) {
46 if (e.code !== "ENOENT") {
47 throw e
48 }
49 }
50
51 const types_dic = path.dirname(output_path)
52 if (!fsSync.existsSync(types_dic)) {
53 await fs.mkdir(types_dic)
54 }
55 await fs.writeFile(output_path, output)
56 console.log(`Wrote Typescript types to ${output_path}`)
57}
58
59main().catch((e) => {
60 console.error(e)
61 process.exit(1)
62})