index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. 'use strict';
  2. var resolve = require('./resolve')
  3. , util = require('./util')
  4. , errorClasses = require('./error_classes')
  5. , stableStringify = require('fast-json-stable-stringify');
  6. var validateGenerator = require('../dotjs/validate');
  7. /**
  8. * Functions below are used inside compiled validations function
  9. */
  10. var ucs2length = util.ucs2length;
  11. var equal = require('fast-deep-equal');
  12. // this error is thrown by async schemas to return validation errors via exception
  13. var ValidationError = errorClasses.Validation;
  14. module.exports = compile;
  15. /**
  16. * Compiles schema to validation function
  17. * @this Ajv
  18. * @param {Object} schema schema object
  19. * @param {Object} root object with information about the root schema for this schema
  20. * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
  21. * @param {String} baseId base ID for IDs in the schema
  22. * @return {Function} validation function
  23. */
  24. function compile(schema, root, localRefs, baseId) {
  25. /* jshint validthis: true, evil: true */
  26. /* eslint no-shadow: 0 */
  27. var self = this
  28. , opts = this._opts
  29. , refVal = [ undefined ]
  30. , refs = {}
  31. , patterns = []
  32. , patternsHash = {}
  33. , defaults = []
  34. , defaultsHash = {}
  35. , customRules = [];
  36. function patternCode(i, patterns) {
  37. var regExpCode = opts.regExp ? 'regExp' : 'new RegExp';
  38. return 'var pattern' + i + ' = ' + regExpCode + '(' + util.toQuotedString(patterns[i]) + ');';
  39. }
  40. root = root || { schema: schema, refVal: refVal, refs: refs };
  41. var c = checkCompiling.call(this, schema, root, baseId);
  42. var compilation = this._compilations[c.index];
  43. if (c.compiling) return (compilation.callValidate = callValidate);
  44. var formats = this._formats;
  45. var RULES = this.RULES;
  46. try {
  47. var v = localCompile(schema, root, localRefs, baseId);
  48. compilation.validate = v;
  49. var cv = compilation.callValidate;
  50. if (cv) {
  51. cv.schema = v.schema;
  52. cv.errors = null;
  53. cv.refs = v.refs;
  54. cv.refVal = v.refVal;
  55. cv.root = v.root;
  56. cv.$async = v.$async;
  57. if (opts.sourceCode) cv.source = v.source;
  58. }
  59. return v;
  60. } finally {
  61. endCompiling.call(this, schema, root, baseId);
  62. }
  63. /* @this {*} - custom context, see passContext option */
  64. function callValidate() {
  65. /* jshint validthis: true */
  66. var validate = compilation.validate;
  67. var result = validate.apply(this, arguments);
  68. callValidate.errors = validate.errors;
  69. return result;
  70. }
  71. function localCompile(_schema, _root, localRefs, baseId) {
  72. var isRoot = !_root || (_root && _root.schema == _schema);
  73. if (_root.schema != root.schema)
  74. return compile.call(self, _schema, _root, localRefs, baseId);
  75. var $async = _schema.$async === true;
  76. var sourceCode = validateGenerator({
  77. isTop: true,
  78. schema: _schema,
  79. isRoot: isRoot,
  80. baseId: baseId,
  81. root: _root,
  82. schemaPath: '',
  83. errSchemaPath: '#',
  84. errorPath: '""',
  85. MissingRefError: errorClasses.MissingRef,
  86. RULES: RULES,
  87. validate: validateGenerator,
  88. util: util,
  89. resolve: resolve,
  90. resolveRef: resolveRef,
  91. usePattern: usePattern,
  92. useDefault: useDefault,
  93. useCustomRule: useCustomRule,
  94. opts: opts,
  95. formats: formats,
  96. logger: self.logger,
  97. self: self
  98. });
  99. sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
  100. + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
  101. + sourceCode;
  102. if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
  103. // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
  104. var validate;
  105. try {
  106. var makeValidate = new Function(
  107. 'self',
  108. 'RULES',
  109. 'formats',
  110. 'root',
  111. 'refVal',
  112. 'defaults',
  113. 'customRules',
  114. 'equal',
  115. 'ucs2length',
  116. 'ValidationError',
  117. 'regExp',
  118. sourceCode
  119. );
  120. validate = makeValidate(
  121. self,
  122. RULES,
  123. formats,
  124. root,
  125. refVal,
  126. defaults,
  127. customRules,
  128. equal,
  129. ucs2length,
  130. ValidationError,
  131. opts.regExp
  132. );
  133. refVal[0] = validate;
  134. } catch(e) {
  135. self.logger.error('Error compiling schema, function code:', sourceCode);
  136. throw e;
  137. }
  138. validate.schema = _schema;
  139. validate.errors = null;
  140. validate.refs = refs;
  141. validate.refVal = refVal;
  142. validate.root = isRoot ? validate : _root;
  143. if ($async) validate.$async = true;
  144. if (opts.sourceCode === true) {
  145. validate.source = {
  146. code: sourceCode,
  147. patterns: patterns,
  148. defaults: defaults
  149. };
  150. }
  151. return validate;
  152. }
  153. function resolveRef(baseId, ref, isRoot) {
  154. ref = resolve.url(baseId, ref);
  155. var refIndex = refs[ref];
  156. var _refVal, refCode;
  157. if (refIndex !== undefined) {
  158. _refVal = refVal[refIndex];
  159. refCode = 'refVal[' + refIndex + ']';
  160. return resolvedRef(_refVal, refCode);
  161. }
  162. if (!isRoot && root.refs) {
  163. var rootRefId = root.refs[ref];
  164. if (rootRefId !== undefined) {
  165. _refVal = root.refVal[rootRefId];
  166. refCode = addLocalRef(ref, _refVal);
  167. return resolvedRef(_refVal, refCode);
  168. }
  169. }
  170. refCode = addLocalRef(ref);
  171. var v = resolve.call(self, localCompile, root, ref);
  172. if (v === undefined) {
  173. var localSchema = localRefs && localRefs[ref];
  174. if (localSchema) {
  175. v = resolve.inlineRef(localSchema, opts.inlineRefs)
  176. ? localSchema
  177. : compile.call(self, localSchema, root, localRefs, baseId);
  178. }
  179. }
  180. if (v === undefined) {
  181. removeLocalRef(ref);
  182. } else {
  183. replaceLocalRef(ref, v);
  184. return resolvedRef(v, refCode);
  185. }
  186. }
  187. function addLocalRef(ref, v) {
  188. var refId = refVal.length;
  189. refVal[refId] = v;
  190. refs[ref] = refId;
  191. return 'refVal' + refId;
  192. }
  193. function removeLocalRef(ref) {
  194. delete refs[ref];
  195. }
  196. function replaceLocalRef(ref, v) {
  197. var refId = refs[ref];
  198. refVal[refId] = v;
  199. }
  200. function resolvedRef(refVal, code) {
  201. return typeof refVal == 'object' || typeof refVal == 'boolean'
  202. ? { code: code, schema: refVal, inline: true }
  203. : { code: code, $async: refVal && !!refVal.$async };
  204. }
  205. function usePattern(regexStr) {
  206. var index = patternsHash[regexStr];
  207. if (index === undefined) {
  208. index = patternsHash[regexStr] = patterns.length;
  209. patterns[index] = regexStr;
  210. }
  211. return 'pattern' + index;
  212. }
  213. function useDefault(value) {
  214. switch (typeof value) {
  215. case 'boolean':
  216. case 'number':
  217. return '' + value;
  218. case 'string':
  219. return util.toQuotedString(value);
  220. case 'object':
  221. if (value === null) return 'null';
  222. var valueStr = stableStringify(value);
  223. var index = defaultsHash[valueStr];
  224. if (index === undefined) {
  225. index = defaultsHash[valueStr] = defaults.length;
  226. defaults[index] = value;
  227. }
  228. return 'default' + index;
  229. }
  230. }
  231. function useCustomRule(rule, schema, parentSchema, it) {
  232. if (self._opts.validateSchema !== false) {
  233. var deps = rule.definition.dependencies;
  234. if (deps && !deps.every(function(keyword) {
  235. return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
  236. }))
  237. throw new Error('parent schema must have all required keywords: ' + deps.join(','));
  238. var validateSchema = rule.definition.validateSchema;
  239. if (validateSchema) {
  240. var valid = validateSchema(schema);
  241. if (!valid) {
  242. var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
  243. if (self._opts.validateSchema == 'log') self.logger.error(message);
  244. else throw new Error(message);
  245. }
  246. }
  247. }
  248. var compile = rule.definition.compile
  249. , inline = rule.definition.inline
  250. , macro = rule.definition.macro;
  251. var validate;
  252. if (compile) {
  253. validate = compile.call(self, schema, parentSchema, it);
  254. } else if (macro) {
  255. validate = macro.call(self, schema, parentSchema, it);
  256. if (opts.validateSchema !== false) self.validateSchema(validate, true);
  257. } else if (inline) {
  258. validate = inline.call(self, it, rule.keyword, schema, parentSchema);
  259. } else {
  260. validate = rule.definition.validate;
  261. if (!validate) return;
  262. }
  263. if (validate === undefined)
  264. throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
  265. var index = customRules.length;
  266. customRules[index] = validate;
  267. return {
  268. code: 'customRule' + index,
  269. validate: validate
  270. };
  271. }
  272. }
  273. /**
  274. * Checks if the schema is currently compiled
  275. * @this Ajv
  276. * @param {Object} schema schema to compile
  277. * @param {Object} root root object
  278. * @param {String} baseId base schema ID
  279. * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
  280. */
  281. function checkCompiling(schema, root, baseId) {
  282. /* jshint validthis: true */
  283. var index = compIndex.call(this, schema, root, baseId);
  284. if (index >= 0) return { index: index, compiling: true };
  285. index = this._compilations.length;
  286. this._compilations[index] = {
  287. schema: schema,
  288. root: root,
  289. baseId: baseId
  290. };
  291. return { index: index, compiling: false };
  292. }
  293. /**
  294. * Removes the schema from the currently compiled list
  295. * @this Ajv
  296. * @param {Object} schema schema to compile
  297. * @param {Object} root root object
  298. * @param {String} baseId base schema ID
  299. */
  300. function endCompiling(schema, root, baseId) {
  301. /* jshint validthis: true */
  302. var i = compIndex.call(this, schema, root, baseId);
  303. if (i >= 0) this._compilations.splice(i, 1);
  304. }
  305. /**
  306. * Index of schema compilation in the currently compiled list
  307. * @this Ajv
  308. * @param {Object} schema schema to compile
  309. * @param {Object} root root object
  310. * @param {String} baseId base schema ID
  311. * @return {Integer} compilation index
  312. */
  313. function compIndex(schema, root, baseId) {
  314. /* jshint validthis: true */
  315. for (var i=0; i<this._compilations.length; i++) {
  316. var c = this._compilations[i];
  317. if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  318. }
  319. return -1;
  320. }
  321. function defaultCode(i) {
  322. return 'var default' + i + ' = defaults[' + i + '];';
  323. }
  324. function refValCode(i, refVal) {
  325. return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
  326. }
  327. function customRuleCode(i) {
  328. return 'var customRule' + i + ' = customRules[' + i + '];';
  329. }
  330. function vars(arr, statement) {
  331. if (!arr.length) return '';
  332. var code = '';
  333. for (var i=0; i<arr.length; i++)
  334. code += statement(i, arr);
  335. return code;
  336. }