ajv.js 15 KB

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