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
239 lines (202 loc) · 7.76 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
const contentTypeParser = require("content-type");
const curry = require("just-curry-it");
const Pact = require("@hyperjump/pact");
const JsonPointer = require("@hyperjump/json-pointer");
const { jsonTypeOf, splitUrl, safeResolveUrl } = require("./common");
const fetch = require("./fetch");
const Reference = require("./reference");
// Config
const config = {};
const configAlias = {};
const setConfig = (schemaVersion, key, value) => {
if (!config[schemaVersion]) {
config[schemaVersion] = {};
}
config[schemaVersion][key] = value;
};
const getConfig = (schemaVersion, key) => {
const configVersion = schemaVersion in configAlias ? configAlias[schemaVersion] : schemaVersion;
if (configVersion in config) {
return config[configVersion][key];
}
};
// Schema Management
const schemaStore = {};
const schemaStoreAlias = {};
const add = (schema, url = "", defaultSchemaVersion = "") => {
schema = JSON.parse(JSON.stringify(schema));
// Schema Version
const schemaVersion = splitUrl(schema["$schema"] || defaultSchemaVersion)[0];
if (!schemaVersion) {
throw Error("Couldn't determine schema version");
}
delete schema["$schema"];
// Identifier
const baseToken = getConfig(schemaVersion, "baseToken");
const anchorToken = getConfig(schemaVersion, "anchorToken");
const externalId = splitUrl(url)[0];
if (!externalId && !splitUrl(schema[baseToken] || "")[0]) {
throw Error("Couldn't determine an identifier for the schema");
}
const internalUrl = safeResolveUrl(externalId, schema[baseToken] || "");
const [id, fragment] = splitUrl(internalUrl);
delete schema[baseToken];
if (fragment && baseToken === anchorToken) {
schema[anchorToken] = anchorToken !== baseToken ? encodeURI(fragment) : `#${encodeURI(fragment)}`;
}
if (externalId) {
schemaStoreAlias[externalId] = id;
}
// recursiveAnchor
const dynamicAnchors = {};
const recursiveAnchorToken = getConfig(schemaVersion, "recursiveAnchorToken");
if (schema[recursiveAnchorToken] === true) {
dynamicAnchors[""] = `${id}#`;
schema[anchorToken] = "";
delete schema[recursiveAnchorToken];
}
// Vocabulary
let vocabulary;
const vocabularyToken = getConfig(schemaVersion, "vocabularyToken");
if (jsonTypeOf(schema[vocabularyToken], "object")) {
configAlias[id] = schemaVersion;
vocabulary = schema[vocabularyToken];
delete schema[vocabularyToken];
} else {
configAlias[id] = schemaVersion;
vocabulary = { [schemaVersion]: true };
}
// Store Schema
const anchors = { "": "" };
schemaStore[id] = {
id: id,
schemaVersion: schemaVersion,
schema: processSchema(schema, id, schemaVersion, JsonPointer.nil, anchors, dynamicAnchors),
anchors: anchors,
dynamicAnchors: dynamicAnchors,
vocabulary: vocabulary,
validated: false
};
return schemaStore[id];
};
const processSchema = (subject, id, schemaVersion, pointer, anchors, dynamicAnchors) => {
if (jsonTypeOf(subject, "object")) {
const embeddedSchemaVersion = typeof subject["$schema"] === "string" ? splitUrl(subject["$schema"])[0] : schemaVersion;
const embeddedEmbeddedToken = getConfig(embeddedSchemaVersion, "embeddedToken");
const embeddedAnchorToken = getConfig(embeddedSchemaVersion, "anchorToken");
if (typeof subject[embeddedEmbeddedToken] === "string" && (embeddedEmbeddedToken !== embeddedAnchorToken || subject[embeddedEmbeddedToken][0] !== "#")) {
const ref = safeResolveUrl(id, subject[embeddedEmbeddedToken]);
subject[embeddedEmbeddedToken] = ref;
add(subject, ref, schemaVersion);
return Reference.cons(subject[embeddedEmbeddedToken], subject);
}
const anchorToken = getConfig(schemaVersion, "anchorToken");
const dynamicAnchorToken = getConfig(schemaVersion, "dynamicAnchorToken");
if (typeof subject[dynamicAnchorToken] === "string") {
dynamicAnchors[subject[dynamicAnchorToken]] = `${id}#${encodeURI(pointer)}`;
anchors[subject[dynamicAnchorToken]] = pointer;
delete subject[dynamicAnchorToken];
}
const embeddedToken = getConfig(schemaVersion, "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(schemaVersion, "jrefToken");
if (typeof subject[jrefToken] === "string") {
return Reference.cons(subject[jrefToken], subject);
}
for (let key in subject) {
subject[key] = processSchema(subject[key], id, schemaVersion, JsonPointer.append(key, pointer), anchors, dynamicAnchors);
}
return subject;
} else if (Array.isArray(subject)) {
return subject.map((item, ndx) => processSchema(item, id, schemaVersion, 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: "",
schemaVersion: undefined,
vocabulary: {},
pointer: JsonPointer.nil,
schema: undefined,
value: undefined,
anchors: {},
dynamicAnchors: {},
validated: true
});
const get = async (url, contextDoc = nil) => {
const resolvedUrl = safeResolveUrl(uri(contextDoc), url);
const [id, fragment] = splitUrl(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}`);
}
if (response.headers.has("content-type")) {
const contentType = contentTypeParser.parse(response.headers.get("content-type")).type;
if (contentType !== "application/schema+json") {
throw Error(`${id} is not a schema. Found a document with media type: ${contentType}`);
}
}
add(await response.json(), 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;
module.exports = {
setConfig, getConfig,
add, get, markValidated,
uri, value, getAnchorPointer, typeOf, has, step, keys, entries, map, length
};