This repository has been archived by the owner on May 3, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
schema.js
331 lines (281 loc) · 11.3 KB
/
schema.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
const curry = require("just-curry-it");
const Pact = require("@hyperjump/pact");
const JsonPointer = require("@hyperjump/json-pointer");
const { jsonTypeOf, resolveUrl, urlFragment, pathRelative } = require("./common");
const fetch = require("./fetch");
const Reference = require("./reference");
const MediaTypes = require("./media-types");
const core201909Id = "https://json-schema.org/draft/2019-09/vocab/core";
const core202012Id = "https://json-schema.org/draft/2020-12/vocab/core";
// Config
const config = {};
const dialectJsonSchemaVersion = {};
const setConfig = (jsonSchemaVersion, key, value) => {
dialectJsonSchemaVersion[jsonSchemaVersion] = jsonSchemaVersion;
if (!config[jsonSchemaVersion]) {
config[jsonSchemaVersion] = {};
}
config[jsonSchemaVersion][key] = value;
};
const getConfig = (dialectId, key) => {
const jsonSchemaVersion = dialectJsonSchemaVersion[dialectId];
return config[jsonSchemaVersion]?.[key];
};
// Schema Management
const schemaStore = {};
const schemaStoreAlias = {};
const add = (schema, url = "", defaultSchemaVersion = "") => {
schema = JSON.parse(JSON.stringify(schema));
const externalId = resolveUrl(url, "");
// Dialect / JSON Schema Version
const dialectId = resolveUrl(schema["$schema"] || defaultSchemaVersion, "");
if (!dialectId) {
throw Error("Couldn't determine schema dialect");
}
delete schema["$schema"];
// Determine JSON Schema version
if (!(dialectId in dialectJsonSchemaVersion)) {
if (schema?.$vocabulary?.[core201909Id] === true && dialectId === getSchemaIdentifier(schema, externalId, core201909Id)[0]) {
// Self describing 2019-09 meta-schema
dialectJsonSchemaVersion[dialectId] = core201909Id;
} else if (schema?.$vocabulary?.[core202012Id] === true && dialectId === getSchemaIdentifier(schema, externalId, core202012Id)[0]) {
// Self describing 2020-12 meta-schema
dialectJsonSchemaVersion[dialectId] = core202012Id;
} else {
// Need to look at meta-schema to determine version
const metaSchema = schemaStore[dialectId];
if (!metaSchema) {
throw Error(`Couldn't determine JSON Schema version for dialect: '${dialectId}'`);
} else if (metaSchema.vocabulary[core201909Id] === true) {
dialectJsonSchemaVersion[dialectId] = core201909Id;
} else if (metaSchema.vocabulary[core202012Id] === true) {
dialectJsonSchemaVersion[dialectId] = core202012Id;
} else {
// Assume the jsonSchemaVersion is the meta-schema's dialectId (non-standard behavior)
dialectJsonSchemaVersion[dialectId] = dialectJsonSchemaVersion[metaSchema.dialectId];
}
}
}
// Internal Identifier
const [id, fragment] = getSchemaIdentifier(schema, externalId, dialectJsonSchemaVersion[dialectId]);
if (!id) {
throw Error("Couldn't determine an identifier for the schema");
}
const baseToken = getConfig(dialectId, "baseToken");
delete schema[baseToken];
if (externalId) {
schemaStoreAlias[externalId] = id;
}
const anchorToken = getConfig(dialectId, "anchorToken");
if (fragment && baseToken === anchorToken) {
schema[anchorToken] = anchorToken !== baseToken ? encodeURI(fragment) : `#${encodeURI(fragment)}`;
}
// recursiveAnchor
const dynamicAnchors = {};
const recursiveAnchorToken = getConfig(dialectId, "recursiveAnchorToken");
if (schema[recursiveAnchorToken] === true) {
dynamicAnchors[""] = `${id}#`;
schema[anchorToken] = "";
delete schema[recursiveAnchorToken];
}
// Vocabulary
let vocabulary;
const vocabularyToken = getConfig(dialectId, "vocabularyToken");
if (jsonTypeOf(schema[vocabularyToken], "object")) {
vocabulary = schema[vocabularyToken];
delete schema[vocabularyToken];
} else {
vocabulary = { [dialectJsonSchemaVersion[dialectId]]: true };
}
// Store Schema
const anchors = { "": "" };
schemaStore[id] = {
id: id,
dialectId: dialectId,
schema: processSchema(schema, id, dialectId, JsonPointer.nil, anchors, dynamicAnchors),
anchors: anchors,
dynamicAnchors: dynamicAnchors,
vocabulary: vocabulary,
validated: false
};
return id;
};
const getSchemaIdentifier = (schema, externalId, jsonSchemaVersion) => {
const baseToken = config[jsonSchemaVersion]?.["baseToken"];
const internalUrl = resolveUrl(externalId, schema[baseToken] || "");
return [resolveUrl(internalUrl, ""), urlFragment(internalUrl)];
};
const processSchema = (subject, id, dialectId, pointer, anchors, dynamicAnchors) => {
if (jsonTypeOf(subject, "object")) {
const embeddedSchemaDialectId = typeof subject.$schema === "string" ? resolveUrl(subject.$schema, "") : dialectId;
const embeddedEmbeddedToken = getConfig(embeddedSchemaDialectId, "embeddedToken");
const embeddedAnchorToken = getConfig(embeddedSchemaDialectId, "anchorToken");
if (typeof subject[embeddedEmbeddedToken] === "string" && (embeddedEmbeddedToken !== embeddedAnchorToken || subject[embeddedEmbeddedToken][0] !== "#")) {
const ref = resolveUrl(id, subject[embeddedEmbeddedToken]);
const embeddedBaseToken = getConfig(embeddedSchemaDialectId, "baseToken");
subject[embeddedBaseToken] = ref;
add(subject, ref, dialectId);
return Reference.cons(subject[embeddedEmbeddedToken], subject);
}
const anchorToken = getConfig(dialectId, "anchorToken");
const dynamicAnchorToken = getConfig(dialectId, "dynamicAnchorToken");
if (typeof subject[dynamicAnchorToken] === "string") {
dynamicAnchors[subject[dynamicAnchorToken]] = `${id}#${encodeURI(pointer)}`;
anchors[subject[dynamicAnchorToken]] = pointer;
delete subject[dynamicAnchorToken];
}
const embeddedToken = getConfig(dialectId, "embeddedToken");
if (typeof subject[anchorToken] === "string") {
const anchor = anchorToken !== embeddedToken ? subject[anchorToken] : subject[anchorToken].slice(1);
anchors[anchor] = pointer;
delete subject[anchorToken];
}
const jrefToken = getConfig(dialectId, "jrefToken");
if (typeof subject[jrefToken] === "string") {
return Reference.cons(subject[jrefToken], subject);
}
for (const key in subject) {
subject[key] = processSchema(subject[key], id, dialectId, JsonPointer.append(key, pointer), anchors, dynamicAnchors);
}
return subject;
} else if (Array.isArray(subject)) {
return subject.map((item, ndx) => processSchema(item, id, dialectId, JsonPointer.append(ndx, pointer), anchors, dynamicAnchors));
} else {
return subject;
}
};
const hasStoredSchema = (id) => id in schemaStore || id in schemaStoreAlias;
const getStoredSchema = (id) => schemaStore[schemaStoreAlias[id]] || schemaStore[id];
const markValidated = (id) => {
schemaStore[id].validated = true;
};
// Schema Retrieval
const nil = Object.freeze({
id: "",
dialectId: undefined,
vocabulary: {},
pointer: JsonPointer.nil,
schema: undefined,
value: undefined,
anchors: {},
dynamicAnchors: {},
validated: true
});
const get = async (url, contextDoc = nil) => {
const resolvedUrl = resolveUrl(uri(contextDoc), url);
const id = resolveUrl(resolvedUrl, "");
const fragment = urlFragment(resolvedUrl);
if (!hasStoredSchema(id)) {
const response = await fetch(id, { headers: { Accept: "application/schema+json" } });
if (response.status >= 400) {
await response.text(); // Sometimes node hangs without this hack
throw Error(`Failed to retrieve schema with id: ${id}`);
}
const [schema, defaultDialectId] = await MediaTypes.parse(response);
// Make sure the meta-schema is loaded if this isn't a known dialect
const dialectId = resolveUrl(schema.$schema, "") || defaultDialectId;
if (id !== dialectId && !(dialectId in dialectJsonSchemaVersion)) {
await get(dialectId);
}
add(schema, id);
}
const storedSchema = getStoredSchema(id);
const pointer = fragment[0] !== "/" ? getAnchorPointer(storedSchema, fragment) : fragment;
const doc = Object.freeze({
...storedSchema,
pointer: pointer,
value: JsonPointer.get(pointer, storedSchema.schema)
});
return followReferences(doc);
};
const followReferences = (doc) => Reference.isReference(doc.value) ? get(Reference.href(doc.value), doc) : doc;
const getAnchorPointer = (schema, fragment) => {
if (!(fragment in schema.anchors)) {
throw Error(`No such anchor '${encodeURI(schema.id)}#${encodeURI(fragment)}'`);
}
return schema.anchors[fragment];
};
// Utility Functions
const uri = (doc) => `${doc.id}#${encodeURI(doc.pointer)}`;
const value = (doc) => Reference.isReference(doc.value) ? Reference.value(doc.value) : doc.value;
const has = (key, doc) => key in value(doc);
const typeOf = (doc, type) => jsonTypeOf(value(doc), type);
const step = (key, doc) => {
const storedSchema = getStoredSchema(doc.id);
const nextDoc = Object.freeze({
...doc,
pointer: JsonPointer.append(key, doc.pointer),
value: value(doc)[key],
validated: storedSchema.validated
});
return followReferences(nextDoc);
};
const keys = (doc) => Object.keys(value(doc));
const entries = (doc) => Pact.pipeline([
value,
Object.keys,
Pact.map(async (key) => [key, await step(key, doc)]),
Pact.all
], doc);
const map = curry((fn, doc) => Pact.pipeline([
value,
Pact.map(async (item, ndx) => fn(await step(ndx, doc), ndx)),
Pact.all
], doc));
const length = (doc) => value(doc).length;
const toSchemaDefaultOptions = {
parentId: "",
parentDialect: "",
includeEmbedded: true
};
const toSchema = (schemaDoc, options = {}) => {
const fullOptions = { ...toSchemaDefaultOptions, ...options };
const schema = JSON.parse(JSON.stringify(schemaDoc.schema, (key, value) => {
if (!Reference.isReference(value)) {
return value;
}
const refValue = Reference.value(value);
const embeddedDialect = typeof refValue.$schema === "string" ? resolveUrl(refValue.$schema, "") : schemaDoc.dialectId;
const embeddedToken = getConfig(embeddedDialect, "embeddedToken");
if (!fullOptions.includeEmbedded && embeddedToken in refValue) {
return;
} else {
return Reference.value(value);
}
}));
const dynamicAnchorToken = getConfig(schemaDoc.dialectId, "dynamicAnchorToken");
Object.entries(schemaDoc.dynamicAnchors)
.forEach(([anchor, uri]) => {
const pointer = JsonPointer.append(dynamicAnchorToken, urlFragment(uri));
JsonPointer.assign(pointer, schema, anchor);
});
const anchorToken = getConfig(schemaDoc.dialectId, "anchorToken");
Object.entries(schemaDoc.anchors)
.filter(([anchor]) => anchor !== "" && !(anchor in schemaDoc.dynamicAnchors))
.forEach(([anchor, pointer]) => {
const anchorPointer = JsonPointer.append(anchorToken, pointer);
JsonPointer.assign(anchorPointer, schema, anchor);
});
const baseToken = getConfig(schemaDoc.dialectId, "baseToken");
const id = relativeUri(fullOptions.parentId, schemaDoc.id);
const dialect = fullOptions.parentDialect === schemaDoc.dialectId ? "" : schemaDoc.dialectId;
return {
...(id && { [baseToken]: id }),
...(dialect && { $schema: dialect }),
...schema
};
};
const relativeUri = (from, to) => {
if (to.startsWith("file://")) {
const pathToSchema = from.slice(7, from.lastIndexOf("/"));
return from === "" ? "" : pathRelative(pathToSchema, to.slice(7));
} else {
return to;
}
};
module.exports = {
setConfig, getConfig,
add, get, markValidated,
uri, value, getAnchorPointer, typeOf, has, step, keys, entries, map, length,
toSchema
};