Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ajv.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. 'use strict';
  2. var compileSchema = require('./compile')
  3. , resolve = require('./compile/resolve')
  4. , Cache = require('./cache')
  5. , SchemaObject = require('./compile/schema_obj')
  6. , stableStringify = require('fast-json-stable-stringify')
  7. , formats = require('./compile/formats')
  8. , rules = require('./compile/rules')
  9. , $dataMetaSchema = require('./data')
  10. , util = require('./compile/util');
  11. module.exports = Ajv;
  12. Ajv.prototype.validate = validate;
  13. Ajv.prototype.compile = compile;
  14. Ajv.prototype.addSchema = addSchema;
  15. Ajv.prototype.addMetaSchema = addMetaSchema;
  16. Ajv.prototype.validateSchema = validateSchema;
  17. Ajv.prototype.getSchema = getSchema;
  18. Ajv.prototype.removeSchema = removeSchema;
  19. Ajv.prototype.addFormat = addFormat;
  20. Ajv.prototype.errorsText = errorsText;
  21. Ajv.prototype._addSchema = _addSchema;
  22. Ajv.prototype._compile = _compile;
  23. Ajv.prototype.compileAsync = require('./compile/async');
  24. var customKeyword = require('./keyword');
  25. Ajv.prototype.addKeyword = customKeyword.add;
  26. Ajv.prototype.getKeyword = customKeyword.get;
  27. Ajv.prototype.removeKeyword = customKeyword.remove;
  28. var errorClasses = require('./compile/error_classes');
  29. Ajv.ValidationError = errorClasses.Validation;
  30. Ajv.MissingRefError = errorClasses.MissingRef;
  31. Ajv.$dataMetaSchema = $dataMetaSchema;
  32. var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
  33. var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ];
  34. var META_SUPPORT_DATA = ['/properties'];
  35. /**
  36. * Creates validator instance.
  37. * Usage: `Ajv(opts)`
  38. * @param {Object} opts optional options
  39. * @return {Object} ajv instance
  40. */
  41. function Ajv(opts) {
  42. if (!(this instanceof Ajv)) return new Ajv(opts);
  43. opts = this._opts = util.copy(opts) || {};
  44. setLogger(this);
  45. this._schemas = {};
  46. this._refs = {};
  47. this._fragments = {};
  48. this._formats = formats(opts.format);
  49. var schemaUriFormat = this._schemaUriFormat = this._formats['uri-reference'];
  50. this._schemaUriFormatFunc = function (str) { return schemaUriFormat.test(str); };
  51. this._cache = opts.cache || new Cache;
  52. this._loadingSchemas = {};
  53. this._compilations = [];
  54. this.RULES = rules();
  55. this._getId = chooseGetId(opts);
  56. opts.loopRequired = opts.loopRequired || Infinity;
  57. if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
  58. if (opts.serialize === undefined) opts.serialize = stableStringify;
  59. this._metaOpts = getMetaSchemaOptions(this);
  60. if (opts.formats) addInitialFormats(this);
  61. addDraft6MetaSchema(this);
  62. if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
  63. addInitialSchemas(this);
  64. }
  65. /**
  66. * Validate data using schema
  67. * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
  68. * @this Ajv
  69. * @param {String|Object} schemaKeyRef key, ref or schema object
  70. * @param {Any} data to be validated
  71. * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
  72. */
  73. function validate(schemaKeyRef, data) {
  74. var v;
  75. if (typeof schemaKeyRef == 'string') {
  76. v = this.getSchema(schemaKeyRef);
  77. if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
  78. } else {
  79. var schemaObj = this._addSchema(schemaKeyRef);
  80. v = schemaObj.validate || this._compile(schemaObj);
  81. }
  82. var valid = v(data);
  83. if (v.$async !== true) this.errors = v.errors;
  84. return valid;
  85. }
  86. /**
  87. * Create validating function for passed schema.
  88. * @this Ajv
  89. * @param {Object} schema schema object
  90. * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
  91. * @return {Function} validating function
  92. */
  93. function compile(schema, _meta) {
  94. var schemaObj = this._addSchema(schema, undefined, _meta);
  95. return schemaObj.validate || this._compile(schemaObj);
  96. }
  97. /**
  98. * Adds schema to the instance.
  99. * @this Ajv
  100. * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
  101. * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
  102. * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
  103. * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
  104. * @return {Ajv} this for method chaining
  105. */
  106. function addSchema(schema, key, _skipValidation, _meta) {
  107. if (Array.isArray(schema)){
  108. for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
  109. return this;
  110. }
  111. var id = this._getId(schema);
  112. if (id !== undefined && typeof id != 'string')
  113. throw new Error('schema id must be string');
  114. key = resolve.normalizeId(key || id);
  115. checkUnique(this, key);
  116. this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
  117. return this;
  118. }
  119. /**
  120. * Add schema that will be used to validate other schemas
  121. * options in META_IGNORE_OPTIONS are alway set to false
  122. * @this Ajv
  123. * @param {Object} schema schema object
  124. * @param {String} key optional schema key
  125. * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
  126. * @return {Ajv} this for method chaining
  127. */
  128. function addMetaSchema(schema, key, skipValidation) {
  129. this.addSchema(schema, key, skipValidation, true);
  130. return this;
  131. }
  132. /**
  133. * Validate schema
  134. * @this Ajv
  135. * @param {Object} schema schema to validate
  136. * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
  137. * @return {Boolean} true if schema is valid
  138. */
  139. function validateSchema(schema, throwOrLogError) {
  140. var $schema = schema.$schema;
  141. if ($schema !== undefined && typeof $schema != 'string')
  142. throw new Error('$schema must be a string');
  143. $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
  144. if (!$schema) {
  145. this.logger.warn('meta-schema not available');
  146. this.errors = null;
  147. return true;
  148. }
  149. var currentUriFormat = this._formats.uri;
  150. this._formats.uri = typeof currentUriFormat == 'function'
  151. ? this._schemaUriFormatFunc
  152. : this._schemaUriFormat;
  153. var valid;
  154. try { valid = this.validate($schema, schema); }
  155. finally { this._formats.uri = currentUriFormat; }
  156. if (!valid && throwOrLogError) {
  157. var message = 'schema is invalid: ' + this.errorsText();
  158. if (this._opts.validateSchema == 'log') this.logger.error(message);
  159. else throw new Error(message);
  160. }
  161. return valid;
  162. }
  163. function defaultMeta(self) {
  164. var meta = self._opts.meta;
  165. self._opts.defaultMeta = typeof meta == 'object'
  166. ? self._getId(meta) || meta
  167. : self.getSchema(META_SCHEMA_ID)
  168. ? META_SCHEMA_ID
  169. : undefined;
  170. return self._opts.defaultMeta;
  171. }
  172. /**
  173. * Get compiled schema from the instance by `key` or `ref`.
  174. * @this Ajv
  175. * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
  176. * @return {Function} schema validating function (with property `schema`).
  177. */
  178. function getSchema(keyRef) {
  179. var schemaObj = _getSchemaObj(this, keyRef);
  180. switch (typeof schemaObj) {
  181. case 'object': return schemaObj.validate || this._compile(schemaObj);
  182. case 'string': return this.getSchema(schemaObj);
  183. case 'undefined': return _getSchemaFragment(this, keyRef);
  184. }
  185. }
  186. function _getSchemaFragment(self, ref) {
  187. var res = resolve.schema.call(self, { schema: {} }, ref);
  188. if (res) {
  189. var schema = res.schema
  190. , root = res.root
  191. , baseId = res.baseId;
  192. var v = compileSchema.call(self, schema, root, undefined, baseId);
  193. self._fragments[ref] = new SchemaObject({
  194. ref: ref,
  195. fragment: true,
  196. schema: schema,
  197. root: root,
  198. baseId: baseId,
  199. validate: v
  200. });
  201. return v;
  202. }
  203. }
  204. function _getSchemaObj(self, keyRef) {
  205. keyRef = resolve.normalizeId(keyRef);
  206. return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
  207. }
  208. /**
  209. * Remove cached schema(s).
  210. * If no parameter is passed all schemas but meta-schemas are removed.
  211. * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
  212. * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
  213. * @this Ajv
  214. * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
  215. * @return {Ajv} this for method chaining
  216. */
  217. function removeSchema(schemaKeyRef) {
  218. if (schemaKeyRef instanceof RegExp) {
  219. _removeAllSchemas(this, this._schemas, schemaKeyRef);
  220. _removeAllSchemas(this, this._refs, schemaKeyRef);
  221. return this;
  222. }
  223. switch (typeof schemaKeyRef) {
  224. case 'undefined':
  225. _removeAllSchemas(this, this._schemas);
  226. _removeAllSchemas(this, this._refs);
  227. this._cache.clear();
  228. return this;
  229. case 'string':
  230. var schemaObj = _getSchemaObj(this, schemaKeyRef);
  231. if (schemaObj) this._cache.del(schemaObj.cacheKey);
  232. delete this._schemas[schemaKeyRef];
  233. delete this._refs[schemaKeyRef];
  234. return this;
  235. case 'object':
  236. var serialize = this._opts.serialize;
  237. var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
  238. this._cache.del(cacheKey);
  239. var id = this._getId(schemaKeyRef);
  240. if (id) {
  241. id = resolve.normalizeId(id);
  242. delete this._schemas[id];
  243. delete this._refs[id];
  244. }
  245. }
  246. return this;
  247. }
  248. function _removeAllSchemas(self, schemas, regex) {
  249. for (var keyRef in schemas) {
  250. var schemaObj = schemas[keyRef];
  251. if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
  252. self._cache.del(schemaObj.cacheKey);
  253. delete schemas[keyRef];
  254. }
  255. }
  256. }
  257. /* @this Ajv */
  258. function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
  259. if (typeof schema != 'object' && typeof schema != 'boolean')
  260. throw new Error('schema should be object or boolean');
  261. var serialize = this._opts.serialize;
  262. var cacheKey = serialize ? serialize(schema) : schema;
  263. var cached = this._cache.get(cacheKey);
  264. if (cached) return cached;
  265. shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
  266. var id = resolve.normalizeId(this._getId(schema));
  267. if (id && shouldAddSchema) checkUnique(this, id);
  268. var willValidate = this._opts.validateSchema !== false && !skipValidation;
  269. var recursiveMeta;
  270. if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
  271. this.validateSchema(schema, true);
  272. var localRefs = resolve.ids.call(this, schema);
  273. var schemaObj = new SchemaObject({
  274. id: id,
  275. schema: schema,
  276. localRefs: localRefs,
  277. cacheKey: cacheKey,
  278. meta: meta
  279. });
  280. if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
  281. this._cache.put(cacheKey, schemaObj);
  282. if (willValidate && recursiveMeta) this.validateSchema(schema, true);
  283. return schemaObj;
  284. }
  285. /* @this Ajv */
  286. function _compile(schemaObj, root) {
  287. if (schemaObj.compiling) {
  288. schemaObj.validate = callValidate;
  289. callValidate.schema = schemaObj.schema;
  290. callValidate.errors = null;
  291. callValidate.root = root ? root : callValidate;
  292. if (schemaObj.schema.$async === true)
  293. callValidate.$async = true;
  294. return callValidate;
  295. }
  296. schemaObj.compiling = true;
  297. var currentOpts;
  298. if (schemaObj.meta) {
  299. currentOpts = this._opts;
  300. this._opts = this._metaOpts;
  301. }
  302. var v;
  303. try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
  304. catch(e) {
  305. delete schemaObj.validate;
  306. throw e;
  307. }
  308. finally {
  309. schemaObj.compiling = false;
  310. if (schemaObj.meta) this._opts = currentOpts;
  311. }
  312. schemaObj.validate = v;
  313. schemaObj.refs = v.refs;
  314. schemaObj.refVal = v.refVal;
  315. schemaObj.root = v.root;
  316. return v;
  317. /* @this {*} - custom context, see passContext option */
  318. function callValidate() {
  319. /* jshint validthis: true */
  320. var _validate = schemaObj.validate;
  321. var result = _validate.apply(this, arguments);
  322. callValidate.errors = _validate.errors;
  323. return result;
  324. }
  325. }
  326. function chooseGetId(opts) {
  327. switch (opts.schemaId) {
  328. case 'auto': return _get$IdOrId;
  329. case 'id': return _getId;
  330. default: return _get$Id;
  331. }
  332. }
  333. /* @this Ajv */
  334. function _getId(schema) {
  335. if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
  336. return schema.id;
  337. }
  338. /* @this Ajv */
  339. function _get$Id(schema) {
  340. if (schema.id) this.logger.warn('schema id ignored', schema.id);
  341. return schema.$id;
  342. }
  343. function _get$IdOrId(schema) {
  344. if (schema.$id && schema.id && schema.$id != schema.id)
  345. throw new Error('schema $id is different from id');
  346. return schema.$id || schema.id;
  347. }
  348. /**
  349. * Convert array of error message objects to string
  350. * @this Ajv
  351. * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
  352. * @param {Object} options optional options with properties `separator` and `dataVar`.
  353. * @return {String} human readable string with all errors descriptions
  354. */
  355. function errorsText(errors, options) {
  356. errors = errors || this.errors;
  357. if (!errors) return 'No errors';
  358. options = options || {};
  359. var separator = options.separator === undefined ? ', ' : options.separator;
  360. var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
  361. var text = '';
  362. for (var i=0; i<errors.length; i++) {
  363. var e = errors[i];
  364. if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
  365. }
  366. return text.slice(0, -separator.length);
  367. }
  368. /**
  369. * Add custom format
  370. * @this Ajv
  371. * @param {String} name format name
  372. * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
  373. * @return {Ajv} this for method chaining
  374. */
  375. function addFormat(name, format) {
  376. if (typeof format == 'string') format = new RegExp(format);
  377. this._formats[name] = format;
  378. return this;
  379. }
  380. function addDraft6MetaSchema(self) {
  381. var $dataSchema;
  382. if (self._opts.$data) {
  383. $dataSchema = require('./refs/data.json');
  384. self.addMetaSchema($dataSchema, $dataSchema.$id, true);
  385. }
  386. if (self._opts.meta === false) return;
  387. var metaSchema = require('./refs/json-schema-draft-07.json');
  388. if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
  389. self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
  390. self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
  391. }
  392. function addInitialSchemas(self) {
  393. var optsSchemas = self._opts.schemas;
  394. if (!optsSchemas) return;
  395. if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
  396. else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
  397. }
  398. function addInitialFormats(self) {
  399. for (var name in self._opts.formats) {
  400. var format = self._opts.formats[name];
  401. self.addFormat(name, format);
  402. }
  403. }
  404. function checkUnique(self, id) {
  405. if (self._schemas[id] || self._refs[id])
  406. throw new Error('schema with key or id "' + id + '" already exists');
  407. }
  408. function getMetaSchemaOptions(self) {
  409. var metaOpts = util.copy(self._opts);
  410. for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
  411. delete metaOpts[META_IGNORE_OPTIONS[i]];
  412. return metaOpts;
  413. }
  414. function setLogger(self) {
  415. var logger = self._opts.logger;
  416. if (logger === false) {
  417. self.logger = {log: noop, warn: noop, error: noop};
  418. } else {
  419. if (logger === undefined) logger = console;
  420. if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
  421. throw new Error('logger must implement log, warn and error methods');
  422. self.logger = logger;
  423. }
  424. }
  425. function noop() {}