-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundle.js
117 lines (101 loc) · 2.7 KB
/
bundle.js
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const path = require("path");
const util = require("util");
const fs = require("fs");
const Bundler = require("@hyperjump/json-schema-bundle");
const resolveUri = require("@jridgewell/resolve-uri");
const parseURI = require("parse-uri");
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
const mkdir = util.promisify(fs.mkdir);
const glob = util.promisify(require("glob"));
function normalizeRef(ref) {
const uri = parseURI(ref);
return uri.relative
.replace(/^\/mason-registry\.json\//, "")
.replaceAll("/", ":");
}
function normalizeKeys(schema) {
for (const key in schema) {
const new_key = normalizeRef(key);
schema[new_key] = schema[key];
delete schema[new_key].$id;
delete schema[key];
}
}
function expandRefs(schema, id) {
if (typeof schema !== "object") {
return;
}
if (Array.isArray(schema)) {
for (const item of schema) {
expandRefs(item, id);
}
return;
}
for (let [key, value] of Object.entries(schema)) {
if (key == "$defs") {
schema.definitions = value;
delete schema.$defs;
} else if (key == "$ref") {
value = value.replace(/\$defs/, "definitions");
schema.$ref = resolveUri(value, id);
}
expandRefs(value, schema.$id ?? id);
}
}
function normalizeRefs(schema) {
if (typeof schema !== "object") {
return;
}
if (Array.isArray(schema)) {
for (const item of schema) {
normalizeRefs(item);
}
return;
}
for (const [key, value] of Object.entries(schema)) {
delete value.$id;
if (key == "$ref") {
const uri = parseURI(value);
schema.$ref = "#/definitions/" + normalizeRef(uri.path) + uri.anchor;
} else {
normalizeRefs(value);
}
}
}
function draft07Compat(schema) {
const originalId = schema.$id;
expandRefs(schema, originalId);
normalizeKeys(schema.definitions);
normalizeRefs(schema);
schema.$id = originalId;
schema.$schema = "http://json-schema.org/draft-07/schema#";
}
async function main() {
for (const schema of await glob(
path.join(
path.resolve(__dirname, "schemas"),
"{components,enums}/**/*.json",
),
{},
)) {
console.log("Adding schema", schema);
Bundler.add(JSON.parse(await readFile(schema)));
}
const main = await Bundler.get(
`file://${path.resolve(__dirname, "schemas", "package.schema.json")}`,
);
console.log("Bundling…");
const schema = await Bundler.bundle(main);
draft07Compat(schema);
const outDir = path.resolve(__dirname, "out");
await mkdir(outDir);
await writeFile(
path.resolve(outDir, "package.schema.json"),
JSON.stringify(schema, null, 2),
);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});