Skip to content

Commit ded83f7

Browse files
committed
Add new file for generating JSON schema from TypeScript file
- Added a new TypeScript file `generate.ts` to handle the generation of JSON schema from a given TypeScript file. The script validates input parameters, generates a UUID, creates the schema configuration, and writes the resulting JSON schema to an output file.
1 parent dc16d55 commit ded83f7

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/util/generate.ts

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import fs from "fs";
2+
import path, { dirname } from "path";
3+
import { Config, createGenerator } from "ts-json-schema-generator";
4+
import { fileURLToPath } from "url";
5+
6+
const file = process.argv[2];
7+
if (!file) {
8+
console.error("No file path provided");
9+
process.exit(1);
10+
} else if (!fs.existsSync(file)) {
11+
console.error("Provided path does not exist");
12+
process.exit(1);
13+
} else if (!fs.lstatSync(file).isFile()) {
14+
console.error("Provided path is not a file");
15+
process.exit(1);
16+
} else if (!file.endsWith(".ts")) {
17+
console.error("Provided file is not a typescript file");
18+
process.exit(1);
19+
}
20+
const rootType = process.argv[3].trim();
21+
if (!rootType) {
22+
console.error("No root type provided");
23+
process.exit(1);
24+
} else if (rootType.length === 0) {
25+
console.error("Root type cannot be empty");
26+
process.exit(1);
27+
}
28+
29+
const __filename = fileURLToPath(import.meta.url);
30+
const __dirname = dirname(__filename);
31+
const projectRoot = path.resolve(__dirname, "../../");
32+
const srcRoot = path.join(projectRoot, "src");
33+
const tsconfig = path.join(projectRoot, "tsconfig.json");
34+
35+
function generate(file: string, rootType: string = "JsonCanvas") {
36+
const relativePath = path.relative(__dirname, file);
37+
const config: Config = {
38+
path: relativePath,
39+
tsconfig: tsconfig,
40+
type: rootType,
41+
topRef: true,
42+
additionalProperties: false,
43+
sortProps: true,
44+
};
45+
46+
const outputPath = path.join(projectRoot, "jsoncanvas.schema.json");
47+
const gnerator = createGenerator(config);
48+
const schema = gnerator.createSchema(config.type);
49+
const schemaString = JSON.stringify(schema, null, 2);
50+
fs.writeFileSync(outputPath, schemaString);
51+
}
52+
53+
generate(file);

0 commit comments

Comments
 (0)