Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. var validateSchema = rule.definition.validateSchema;
  227. if (validateSchema && self._opts.validateSchema !== false) {
  228. var valid = validateSchema(schema);
  229. if (!valid) {
  230. var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
  231. if (self._opts.validateSchema == 'log') self.logger.error(message);
  232. else throw new Error(message);
  233. }
  234. }
  235. var compile = rule.definition.compile
  236. , inline = rule.definition.inline
  237. , macro = rule.definition.macro;
  238. var validate;
  239. if (compile) {
  240. validate = compile.call(self, schema, parentSchema, it);
  241. } else if (macro) {
  242. validate = macro.call(self, schema, parentSchema, it);
  243. if (opts.validateSchema !== false) self.validateSchema(validate, true);
  244. } else if (inline) {
  245. validate = inline.call(self, it, rule.keyword, schema, parentSchema);
  246. } else {
  247. validate = rule.definition.validate;
  248. if (!validate) return;
  249. }
  250. if (validate === undefined)
  251. throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
  252. var index = customRules.length;
  253. customRules[index] = validate;
  254. return {
  255. code: 'customRule' + index,
  256. validate: validate
  257. };
  258. }
  259. }
  260. /**
  261. * Checks if the schema is currently compiled
  262. * @this Ajv
  263. * @param {Object} schema schema to compile
  264. * @param {Object} root root object
  265. * @param {String} baseId base schema ID
  266. * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
  267. */
  268. function checkCompiling(schema, root, baseId) {
  269. /* jshint validthis: true */
  270. var index = compIndex.call(this, schema, root, baseId);
  271. if (index >= 0) return { index: index, compiling: true };
  272. index = this._compilations.length;
  273. this._compilations[index] = {
  274. schema: schema,
  275. root: root,
  276. baseId: baseId
  277. };
  278. return { index: index, compiling: false };
  279. }
  280. /**
  281. * Removes the schema from the currently compiled list
  282. * @this Ajv
  283. * @param {Object} schema schema to compile
  284. * @param {Object} root root object
  285. * @param {String} baseId base schema ID
  286. */
  287. function endCompiling(schema, root, baseId) {
  288. /* jshint validthis: true */
  289. var i = compIndex.call(this, schema, root, baseId);
  290. if (i >= 0) this._compilations.splice(i, 1);
  291. }
  292. /**
  293. * Index of schema compilation in the currently compiled list
  294. * @this Ajv
  295. * @param {Object} schema schema to compile
  296. * @param {Object} root root object
  297. * @param {String} baseId base schema ID
  298. * @return {Integer} compilation index
  299. */
  300. function compIndex(schema, root, baseId) {
  301. /* jshint validthis: true */
  302. for (var i=0; i<this._compilations.length; i++) {
  303. var c = this._compilations[i];
  304. if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
  305. }
  306. return -1;
  307. }
  308. function patternCode(i, patterns) {
  309. return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
  310. }
  311. function defaultCode(i) {
  312. return 'var default' + i + ' = defaults[' + i + '];';
  313. }
  314. function refValCode(i, refVal) {
  315. return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
  316. }
  317. function customRuleCode(i) {
  318. return 'var customRule' + i + ' = customRules[' + i + '];';
  319. }
  320. function vars(arr, statement) {
  321. if (!arr.length) return '';
  322. var code = '';
  323. for (var i=0; i<arr.length; i++)
  324. code += statement(i, arr);
  325. return code;
  326. }