您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

index.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. root = root || { schema: schema, refVal: refVal, refs: refs };
  37. var c = checkCompiling.call(this, schema, root, baseId);
  38. var compilation = this._compilations[c.index];
  39. if (c.compiling) return (compilation.callValidate = callValidate);
  40. var formats = this._formats;
  41. var RULES = this.RULES;
  42. try {
  43. var v = localCompile(schema, root, localRefs, baseId);
  44. compilation.validate = v;
  45. var cv = compilation.callValidate;
  46. if (cv) {
  47. cv.schema = v.schema;
  48. cv.errors = null;
  49. cv.refs = v.refs;
  50. cv.refVal = v.refVal;
  51. cv.root = v.root;
  52. cv.$async = v.$async;
  53. if (opts.sourceCode) cv.source = v.source;
  54. }
  55. return v;
  56. } finally {
  57. endCompiling.call(this, schema, root, baseId);
  58. }
  59. /* @this {*} - custom context, see passContext option */
  60. function callValidate() {
  61. /* jshint validthis: true */
  62. var validate = compilation.validate;
  63. var result = validate.apply(this, arguments);
  64. callValidate.errors = validate.errors;
  65. return result;
  66. }
  67. function localCompile(_schema, _root, localRefs, baseId) {
  68. var isRoot = !_root || (_root && _root.schema == _schema);
  69. if (_root.schema != root.schema)
  70. return compile.call(self, _schema, _root, localRefs, baseId);
  71. var $async = _schema.$async === true;
  72. var sourceCode = validateGenerator({
  73. isTop: true,
  74. schema: _schema,
  75. isRoot: isRoot,
  76. baseId: baseId,
  77. root: _root,
  78. schemaPath: '',
  79. errSchemaPath: '#',
  80. errorPath: '""',
  81. MissingRefError: errorClasses.MissingRef,
  82. RULES: RULES,
  83. validate: validateGenerator,
  84. util: util,
  85. resolve: resolve,
  86. resolveRef: resolveRef,
  87. usePattern: usePattern,
  88. useDefault: useDefault,
  89. useCustomRule: useCustomRule,
  90. opts: opts,
  91. formats: formats,
  92. logger: self.logger,
  93. self: self
  94. });
  95. sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
  96. + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
  97. + sourceCode;
  98. if (opts.processCode) sourceCode = opts.processCode(sourceCode);
  99. // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
  100. var validate;
  101. try {
  102. var makeValidate = new Function(
  103. 'self',
  104. 'RULES',
  105. 'formats',
  106. 'root',
  107. 'refVal',
  108. 'defaults',
  109. 'customRules',
  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. equal,
  124. ucs2length,
  125. ValidationError
  126. );
  127. refVal[0] = validate;
  128. } catch(e) {
  129. self.logger.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. removeLocalRef(ref);
  176. } else {
  177. replaceLocalRef(ref, v);
  178. return resolvedRef(v, refCode);
  179. }
  180. }
  181. function addLocalRef(ref, v) {
  182. var refId = refVal.length;
  183. refVal[refId] = v;
  184. refs[ref] = refId;
  185. return 'refVal' + refId;
  186. }
  187. function removeLocalRef(ref) {
  188. delete refs[ref];
  189. }
  190. function replaceLocalRef(ref, v) {
  191. var refId = refs[ref];
  192. refVal[refId] = v;
  193. }
  194. function resolvedRef(refVal, code) {
  195. return typeof refVal == 'object' || typeof refVal == 'boolean'
  196. ? { code: code, schema: refVal, inline: true }
  197. : { code: code, $async: refVal && !!refVal.$async };
  198. }
  199. function usePattern(regexStr) {
  200. var index = patternsHash[regexStr];
  201. if (index === undefined) {
  202. index = patternsHash[regexStr] = patterns.length;
  203. patterns[index] = regexStr;
  204. }
  205. return 'pattern' + index;
  206. }
  207. function useDefault(value) {
  208. switch (typeof value) {
  209. case 'boolean':
  210. case 'number':
  211. return '' + value;
  212. case 'string':
  213. return util.toQuotedString(value);
  214. case 'object':
  215. if (value === null) return 'null';
  216. var valueStr = stableStringify(value);
  217. var index = defaultsHash[valueStr];
  218. if (index === undefined) {
  219. index = defaultsHash[valueStr] = defaults.length;
  220. defaults[index] = value;
  221. }
  222. return 'default' + index;
  223. }
  224. }
  225. function useCustomRule(rule, schema, parentSchema, it) {
  226. if (self._opts.validateSchema !== false) {
  227. var deps = rule.definition.dependencies;
  228. if (deps && !deps.every(function(keyword) {
  229. return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
  230. }))
  231. throw new Error('parent schema must have all required keywords: ' + deps.join(','));
  232. var validateSchema = rule.definition.validateSchema;
  233. if (validateSchema) {
  234. var valid = validateSchema(schema);
  235. if (!valid) {
  236. var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
  237. if (self._opts.validateSchema == 'log') self.logger.error(message);
  238. else throw new Error(message);
  239. }
  240. }
  241. }
  242. var compile = rule.definition.compile
  243. , inline = rule.definition.inline
  244. , macro = rule.definition.macro;
  245. var validate;
  246. if (compile) {
  247. validate = compile.call(self, schema, parentSchema, it);
  248. } else if (macro) {
  249. validate = macro.call(self, schema, parentSchema, it);
  250. if (opts.validateSchema !== false) self.validateSchema(validate, true);
  251. } else if (inline) {
  252. validate = inline.call(self, it, rule.keyword, schema, parentSchema);
  253. } else {
  254. validate = rule.definition.validate;
  255. if (!validate) return;
  256. }
  257. if (validate === undefined)
  258. throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
  259. var index = customRules.length;
  260. customRules[index] = validate;
  261. return {
  262. code: 'customRule' + index,
  263. validate: validate
  264. };
  265. }
  266. }
  267. /**
  268. * Checks if the schema is currently compiled
  269. * @this Ajv
  270. * @param {Object} schema schema to compile
  271. * @param {Object} root root object
  272. * @param {String} baseId base schema ID
  273. * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
  274. */
  275. function checkCompiling(schema, root, baseId) {
  276. /* jshint validthis: true */
  277. var index = compIndex.call(this, schema, root, baseId);
  278. if (index >= 0) return { index: index, compiling: true };
  279. index = this._compilations.length;
  280. this._compilations[index] = {
  281. schema: schema,
  282. root: root,
  283. baseId: baseId
  284. };
  285. return { index: index, compiling: false };
  286. }
  287. /**
  288. * Removes the schema from 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. */
  294. function endCompiling(schema, root, baseId) {
  295. /* jshint validthis: true */
  296. var i = compIndex.call(this, schema, root, baseId);
  297. if (i >= 0) this._compilations.splice(i, 1);
  298. }
  299. /**
  300. * Index of schema compilation in the currently compiled list
  301. * @this Ajv
  302. * @param {Object} schema schema to compile
  303. * @param {Object} root root object
  304. * @param {String} baseId base schema ID
  305. * @return {Integer} compilation index
  306. */
  307. function compIndex(schema, root, baseId) {
  308. /* jshint validthis: true */
  309. for (var i=0; i<this._compilations.length; i++) {
  310. var c = this._compilations[i];
  311. if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  312. }
  313. return -1;
  314. }
  315. function patternCode(i, patterns) {
  316. return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
  317. }
  318. function defaultCode(i) {
  319. return 'var default' + i + ' = defaults[' + i + '];';
  320. }
  321. function refValCode(i, refVal) {
  322. return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
  323. }
  324. function customRuleCode(i) {
  325. return 'var customRule' + i + ' = customRules[' + i + '];';
  326. }
  327. function vars(arr, statement) {
  328. if (!arr.length) return '';
  329. var code = '';
  330. for (var i=0; i<arr.length; i++)
  331. code += statement(i, arr);
  332. return code;
  333. }