-
Notifications
You must be signed in to change notification settings - Fork 91
/
ZSchema.js
409 lines (359 loc) · 11.9 KB
/
ZSchema.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
"use strict";
require("./Polyfills");
var get = require("lodash.get");
var Report = require("./Report");
var FormatValidators = require("./FormatValidators");
var JsonValidation = require("./JsonValidation");
var SchemaCache = require("./SchemaCache");
var SchemaCompilation = require("./SchemaCompilation");
var SchemaValidation = require("./SchemaValidation");
var Utils = require("./Utils");
var Draft4Schema = require("./schemas/schema.json");
var Draft4HyperSchema = require("./schemas/hyper-schema.json");
/**
* default options
*/
var defaultOptions = {
// default timeout for all async tasks
asyncTimeout: 2000,
// force additionalProperties and additionalItems to be defined on "object" and "array" types
forceAdditional: false,
// assume additionalProperties and additionalItems are defined as "false" where appropriate
assumeAdditional: false,
// do case insensitive comparison for enums
enumCaseInsensitiveComparison: false,
// force items to be defined on "array" types
forceItems: false,
// force minItems to be defined on "array" types
forceMinItems: false,
// force maxItems to be defined on "array" types
forceMaxItems: false,
// force minLength to be defined on "string" types
forceMinLength: false,
// force maxLength to be defined on "string" types
forceMaxLength: false,
// force properties or patternProperties to be defined on "object" types
forceProperties: false,
// ignore references that cannot be resolved (remote schemas) // TODO: make sure this is only for remote schemas, not local ones
ignoreUnresolvableReferences: false,
// disallow usage of keywords that this validator can't handle
noExtraKeywords: false,
// disallow usage of schema's without "type" defined
noTypeless: false,
// disallow zero length strings in validated objects
noEmptyStrings: false,
// disallow zero length arrays in validated objects
noEmptyArrays: false,
// forces "uri" format to be in fully rfc3986 compliant
strictUris: false,
// turn on some of the above
strictMode: false,
// report error paths as an array of path segments to get to the offending node
reportPathAsArray: false,
// stop validation as soon as an error is found
breakOnFirstError: false,
// check if schema follows best practices and common sense
pedanticCheck: false,
// ignore unknown formats (do not report them as an error)
ignoreUnknownFormats: false,
// function to be called on every schema
customValidator: null
};
function normalizeOptions(options) {
var normalized;
// options
if (typeof options === "object") {
var keys = Object.keys(options),
idx = keys.length,
key;
// check that the options are correctly configured
while (idx--) {
key = keys[idx];
if (defaultOptions[key] === undefined) {
throw new Error("Unexpected option passed to constructor: " + key);
}
}
// copy the default options into passed options
keys = Object.keys(defaultOptions);
idx = keys.length;
while (idx--) {
key = keys[idx];
if (options[key] === undefined) {
options[key] = Utils.clone(defaultOptions[key]);
}
}
normalized = options;
} else {
normalized = Utils.clone(defaultOptions);
}
if (normalized.strictMode === true) {
normalized.forceAdditional = true;
normalized.forceItems = true;
normalized.forceMaxLength = true;
normalized.forceProperties = true;
normalized.noExtraKeywords = true;
normalized.noTypeless = true;
normalized.noEmptyStrings = true;
normalized.noEmptyArrays = true;
}
return normalized;
}
/**
* @class
*
* @param {*} [options]
*/
function ZSchema(options) {
this.cache = {};
this.referenceCache = [];
this.validateOptions = {};
this.options = normalizeOptions(options);
// Disable strict validation for the built-in schemas
var metaschemaOptions = normalizeOptions({ });
this.setRemoteReference("http://json-schema.org/draft-04/schema", Draft4Schema, metaschemaOptions);
this.setRemoteReference("http://json-schema.org/draft-04/hyper-schema", Draft4HyperSchema, metaschemaOptions);
}
/**
* instance methods
*
* @param {*} schema
*
* @returns {boolean}
*/
ZSchema.prototype.compileSchema = function (schema) {
var report = new Report(this.options);
schema = SchemaCache.getSchema.call(this, report, schema);
SchemaCompilation.compileSchema.call(this, report, schema);
this.lastReport = report;
return report.isValid();
};
/**
*
* @param {*} schema
*
* @returns {boolean}
*/
ZSchema.prototype.validateSchema = function (schema) {
if (Array.isArray(schema) && schema.length === 0) {
throw new Error(".validateSchema was called with an empty array");
}
var report = new Report(this.options);
schema = SchemaCache.getSchema.call(this, report, schema);
var compiled = SchemaCompilation.compileSchema.call(this, report, schema);
if (compiled) { SchemaValidation.validateSchema.call(this, report, schema); }
this.lastReport = report;
return report.isValid();
};
/**
*
* @param {*} json
* @param {*} schema
* @param {*} [options]
* @param {function(*, *)} [callback]
*
* @returns {boolean}
*/
ZSchema.prototype.validate = function (json, schema, options, callback) {
if (Utils.whatIs(options) === "function") {
callback = options;
options = {};
}
if (!options) { options = {}; }
this.validateOptions = options;
var whatIs = Utils.whatIs(schema);
if (whatIs !== "string" && whatIs !== "object") {
var e = new Error("Invalid .validate call - schema must be a string or object but " + whatIs + " was passed!");
if (callback) {
process.nextTick(function () {
callback(e, false);
});
return;
}
throw e;
}
var foundError = false;
var report = new Report(this.options);
report.json = json;
if (typeof schema === "string") {
var schemaName = schema;
schema = SchemaCache.getSchema.call(this, report, schemaName);
if (!schema) {
throw new Error("Schema with id '" + schemaName + "' wasn't found in the validator cache!");
}
} else {
schema = SchemaCache.getSchema.call(this, report, schema);
}
var compiled = false;
if (!foundError) {
compiled = SchemaCompilation.compileSchema.call(this, report, schema);
}
if (!compiled) {
this.lastReport = report;
foundError = true;
}
var validated = false;
if (!foundError) {
validated = SchemaValidation.validateSchema.call(this, report, schema);
}
if (!validated) {
this.lastReport = report;
foundError = true;
}
if (options.schemaPath) {
report.rootSchema = schema;
schema = get(schema, options.schemaPath);
if (!schema) {
throw new Error("Schema path '" + options.schemaPath + "' wasn't found in the schema!");
}
}
if (!foundError) {
JsonValidation.validate.call(this, report, schema, json);
}
if (callback) {
report.processAsyncTasks(this.options.asyncTimeout, callback);
return;
} else if (report.asyncTasks.length > 0) {
throw new Error("This validation has async tasks and cannot be done in sync mode, please provide callback argument.");
}
// assign lastReport so errors are retrievable in sync mode
this.lastReport = report;
return report.isValid();
};
ZSchema.prototype.getLastError = function () {
if (this.lastReport.errors.length === 0) {
return null;
}
var e = new Error();
e.name = "z-schema validation error";
e.message = this.lastReport.commonErrorMessage;
e.details = this.lastReport.errors;
return e;
};
ZSchema.prototype.getLastErrors = function () {
return this.lastReport && this.lastReport.errors.length > 0 ? this.lastReport.errors : null;
};
ZSchema.prototype.getMissingReferences = function (arr) {
arr = arr || this.lastReport.errors;
var res = [],
idx = arr.length;
while (idx--) {
var error = arr[idx];
if (error.code === "UNRESOLVABLE_REFERENCE") {
var reference = error.params[0];
if (res.indexOf(reference) === -1) {
res.push(reference);
}
}
if (error.inner) {
res = res.concat(this.getMissingReferences(error.inner));
}
}
return res;
};
ZSchema.prototype.getMissingRemoteReferences = function () {
var missingReferences = this.getMissingReferences(),
missingRemoteReferences = [],
idx = missingReferences.length;
while (idx--) {
var remoteReference = SchemaCache.getRemotePath(missingReferences[idx]);
if (remoteReference && missingRemoteReferences.indexOf(remoteReference) === -1) {
missingRemoteReferences.push(remoteReference);
}
}
return missingRemoteReferences;
};
ZSchema.prototype.setRemoteReference = function (uri, schema, validationOptions) {
if (typeof schema === "string") {
schema = JSON.parse(schema);
} else {
schema = Utils.cloneDeep(schema);
}
if (validationOptions) {
schema.__$validationOptions = normalizeOptions(validationOptions);
}
SchemaCache.cacheSchemaByUri.call(this, uri, schema);
};
ZSchema.prototype.getResolvedSchema = function (schema) {
var report = new Report(this.options);
schema = SchemaCache.getSchema.call(this, report, schema);
// clone before making any modifications
schema = Utils.cloneDeep(schema);
var visited = [];
// clean-up the schema and resolve references
var cleanup = function (schema) {
var key,
typeOf = Utils.whatIs(schema);
if (typeOf !== "object" && typeOf !== "array") {
return;
}
if (schema.___$visited) {
return;
}
schema.___$visited = true;
visited.push(schema);
if (schema.$ref && schema.__$refResolved) {
var from = schema.__$refResolved;
var to = schema;
delete schema.$ref;
delete schema.__$refResolved;
for (key in from) {
if (from.hasOwnProperty(key)) {
to[key] = from[key];
}
}
}
for (key in schema) {
if (schema.hasOwnProperty(key)) {
if (key.indexOf("__$") === 0) {
delete schema[key];
} else {
cleanup(schema[key]);
}
}
}
};
cleanup(schema);
visited.forEach(function (s) {
delete s.___$visited;
});
this.lastReport = report;
if (report.isValid()) {
return schema;
} else {
throw this.getLastError();
}
};
/**
*
* @param {*} schemaReader
*
* @returns {void}
*/
ZSchema.prototype.setSchemaReader = function (schemaReader) {
return ZSchema.setSchemaReader(schemaReader);
};
ZSchema.prototype.getSchemaReader = function () {
return ZSchema.schemaReader;
};
ZSchema.schemaReader = undefined;
/*
static methods
*/
ZSchema.setSchemaReader = function (schemaReader) {
ZSchema.schemaReader = schemaReader;
};
ZSchema.registerFormat = function (formatName, validatorFunction) {
FormatValidators[formatName] = validatorFunction;
};
ZSchema.unregisterFormat = function (formatName) {
delete FormatValidators[formatName];
};
ZSchema.getRegisteredFormats = function () {
return Object.keys(FormatValidators);
};
ZSchema.getDefaultOptions = function () {
return Utils.cloneDeep(defaultOptions);
};
ZSchema.schemaSymbol = Utils.schemaSymbol;
ZSchema.jsonSymbol = Utils.jsonSymbol;
module.exports = ZSchema;