index.js 10 KB

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