index.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. 'use strict';
  2. var resolve = require('./resolve')
  3. , util = require('./util')
  4. , errorClasses = require('./error_classes')
  5. , stableStringify = require('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('./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. self: self
  92. });
  93. sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
  94. + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
  95. + sourceCode;
  96. if (opts.processCode) sourceCode = opts.processCode(sourceCode);
  97. // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
  98. var validate;
  99. try {
  100. var makeValidate = new Function(
  101. 'self',
  102. 'RULES',
  103. 'formats',
  104. 'root',
  105. 'refVal',
  106. 'defaults',
  107. 'customRules',
  108. 'co',
  109. 'equal',
  110. 'ucs2length',
  111. 'ValidationError',
  112. sourceCode
  113. );
  114. validate = makeValidate(
  115. self,
  116. RULES,
  117. formats,
  118. root,
  119. refVal,
  120. defaults,
  121. customRules,
  122. co,
  123. equal,
  124. ucs2length,
  125. ValidationError
  126. );
  127. refVal[0] = validate;
  128. } catch(e) {
  129. console.error('Error compiling schema, function code:', sourceCode);
  130. throw e;
  131. }
  132. validate.schema = _schema;
  133. validate.errors = null;
  134. validate.refs = refs;
  135. validate.refVal = refVal;
  136. validate.root = isRoot ? validate : _root;
  137. if ($async) validate.$async = true;
  138. if (opts.sourceCode === true) {
  139. validate.source = {
  140. code: sourceCode,
  141. patterns: patterns,
  142. defaults: defaults
  143. };
  144. }
  145. return validate;
  146. }
  147. function resolveRef(baseId, ref, isRoot) {
  148. ref = resolve.url(baseId, ref);
  149. var refIndex = refs[ref];
  150. var _refVal, refCode;
  151. if (refIndex !== undefined) {
  152. _refVal = refVal[refIndex];
  153. refCode = 'refVal[' + refIndex + ']';
  154. return resolvedRef(_refVal, refCode);
  155. }
  156. if (!isRoot && root.refs) {
  157. var rootRefId = root.refs[ref];
  158. if (rootRefId !== undefined) {
  159. _refVal = root.refVal[rootRefId];
  160. refCode = addLocalRef(ref, _refVal);
  161. return resolvedRef(_refVal, refCode);
  162. }
  163. }
  164. refCode = addLocalRef(ref);
  165. var v = resolve.call(self, localCompile, root, ref);
  166. if (v === undefined) {
  167. var localSchema = localRefs && localRefs[ref];
  168. if (localSchema) {
  169. v = resolve.inlineRef(localSchema, opts.inlineRefs)
  170. ? localSchema
  171. : compile.call(self, localSchema, root, localRefs, baseId);
  172. }
  173. }
  174. if (v !== undefined) {
  175. replaceLocalRef(ref, v);
  176. return resolvedRef(v, refCode);
  177. }
  178. }
  179. function addLocalRef(ref, v) {
  180. var refId = refVal.length;
  181. refVal[refId] = v;
  182. refs[ref] = refId;
  183. return 'refVal' + refId;
  184. }
  185. function replaceLocalRef(ref, v) {
  186. var refId = refs[ref];
  187. refVal[refId] = v;
  188. }
  189. function resolvedRef(refVal, code) {
  190. return typeof refVal == 'object' || typeof refVal == 'boolean'
  191. ? { code: code, schema: refVal, inline: true }
  192. : { code: code, $async: refVal && refVal.$async };
  193. }
  194. function usePattern(regexStr) {
  195. var index = patternsHash[regexStr];
  196. if (index === undefined) {
  197. index = patternsHash[regexStr] = patterns.length;
  198. patterns[index] = regexStr;
  199. }
  200. return 'pattern' + index;
  201. }
  202. function useDefault(value) {
  203. switch (typeof value) {
  204. case 'boolean':
  205. case 'number':
  206. return '' + value;
  207. case 'string':
  208. return util.toQuotedString(value);
  209. case 'object':
  210. if (value === null) return 'null';
  211. var valueStr = stableStringify(value);
  212. var index = defaultsHash[valueStr];
  213. if (index === undefined) {
  214. index = defaultsHash[valueStr] = defaults.length;
  215. defaults[index] = value;
  216. }
  217. return 'default' + index;
  218. }
  219. }
  220. function useCustomRule(rule, schema, parentSchema, it) {
  221. var validateSchema = rule.definition.validateSchema;
  222. if (validateSchema && self._opts.validateSchema !== false) {
  223. var valid = validateSchema(schema);
  224. if (!valid) {
  225. var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
  226. if (self._opts.validateSchema == 'log') console.error(message);
  227. else throw new Error(message);
  228. }
  229. }
  230. var compile = rule.definition.compile
  231. , inline = rule.definition.inline
  232. , macro = rule.definition.macro;
  233. var validate;
  234. if (compile) {
  235. validate = compile.call(self, schema, parentSchema, it);
  236. } else if (macro) {
  237. validate = macro.call(self, schema, parentSchema, it);
  238. if (opts.validateSchema !== false) self.validateSchema(validate, true);
  239. } else if (inline) {
  240. validate = inline.call(self, it, rule.keyword, schema, parentSchema);
  241. } else {
  242. validate = rule.definition.validate;
  243. if (!validate) return;
  244. }
  245. if (validate === undefined)
  246. throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
  247. var index = customRules.length;
  248. customRules[index] = validate;
  249. return {
  250. code: 'customRule' + index,
  251. validate: validate
  252. };
  253. }
  254. }
  255. /**
  256. * Checks if the schema is currently compiled
  257. * @this Ajv
  258. * @param {Object} schema schema to compile
  259. * @param {Object} root root object
  260. * @param {String} baseId base schema ID
  261. * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
  262. */
  263. function checkCompiling(schema, root, baseId) {
  264. /* jshint validthis: true */
  265. var index = compIndex.call(this, schema, root, baseId);
  266. if (index >= 0) return { index: index, compiling: true };
  267. index = this._compilations.length;
  268. this._compilations[index] = {
  269. schema: schema,
  270. root: root,
  271. baseId: baseId
  272. };
  273. return { index: index, compiling: false };
  274. }
  275. /**
  276. * Removes the schema from the currently compiled list
  277. * @this Ajv
  278. * @param {Object} schema schema to compile
  279. * @param {Object} root root object
  280. * @param {String} baseId base schema ID
  281. */
  282. function endCompiling(schema, root, baseId) {
  283. /* jshint validthis: true */
  284. var i = compIndex.call(this, schema, root, baseId);
  285. if (i >= 0) this._compilations.splice(i, 1);
  286. }
  287. /**
  288. * Index of schema compilation in the currently compiled list
  289. * @this Ajv
  290. * @param {Object} schema schema to compile
  291. * @param {Object} root root object
  292. * @param {String} baseId base schema ID
  293. * @return {Integer} compilation index
  294. */
  295. function compIndex(schema, root, baseId) {
  296. /* jshint validthis: true */
  297. for (var i=0; i<this._compilations.length; i++) {
  298. var c = this._compilations[i];
  299. if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  300. }
  301. return -1;
  302. }
  303. function patternCode(i, patterns) {
  304. return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
  305. }
  306. function defaultCode(i) {
  307. return 'var default' + i + ' = defaults[' + i + '];';
  308. }
  309. function refValCode(i, refVal) {
  310. return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
  311. }
  312. function customRuleCode(i) {
  313. return 'var customRule' + i + ' = customRules[' + i + '];';
  314. }
  315. function vars(arr, statement) {
  316. if (!arr.length) return '';
  317. var code = '';
  318. for (var i=0; i<arr.length; i++)
  319. code += statement(i, arr);
  320. return code;
  321. }