summaryrefslogtreecommitdiff
path: root/extension/scripts/typegen.js
blob: 793eb08d87474e25a93981d66f41f013e8fe957b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const fs = require("fs");
const path = require("path");
const { compile } = require("json-schema-to-typescript");

function generateTypesForFile(inputPath, outputPath) {
  let schema = JSON.parse(fs.readFileSync(inputPath, "utf8"));
  let name = path.parse(path.basename(inputPath)).name;
  // This is to solve the issue of json-schema-to-typescript not supporting $ref at the top-level, which is what Pydantic generates for recursive types
  if ("$ref" in schema) {
    let temp = schema["$ref"];
    delete schema["$ref"];
    schema["allOf"] = [{ $ref: temp }];
  }

  compile(schema, name)
    .then((ts) => {
      fs.writeFileSync(path.join(outputPath, name + ".d.ts"), ts);
    })
    .catch((e) => {
      console.log("Error generating types for " + name);
      throw e;
    });
}

function generateAllSchemas(inputDir, outputDir) {
  // get the current directory
  try {
    fs.readdirSync(inputDir).forEach((file) => {
      if (file.endsWith(".json")) {
        generateTypesForFile(path.join(inputDir, file), outputDir);
      }
    });
  } catch (e) {
    console.log(
      "Make sure you are running this script from the extension/ directory."
    );
    throw e;
  }
}

function deleteAllInDir(dir) {
  fs.readdirSync(dir).forEach((file) => {
    if (file.endsWith(".d.ts")) {
      fs.unlinkSync(path.join(dir, file));
    }
  });
}

const OUTPUT_DIR = path.join("schema");
const INPUT_DIR = path.join("..", "schema", "json");
if (!fs.existsSync(INPUT_DIR)) {
  throw new Error(`Input directory does not exist: ${INPUT_DIR}`);
}

if (!fs.existsSync(OUTPUT_DIR)) {
  throw new Error(`Output directory does not exist: ${OUTPUT_DIR}`);
}

deleteAllInDir(OUTPUT_DIR);
generateAllSchemas(INPUT_DIR, OUTPUT_DIR);