validate.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. Object.defineProperty(exports, "ValidationError", {
  6. enumerable: true,
  7. get: function () {
  8. return _ValidationError.default;
  9. }
  10. });
  11. exports.disableValidation = disableValidation;
  12. exports.enableValidation = enableValidation;
  13. exports.needValidate = needValidate;
  14. exports.validate = validate;
  15. var _ValidationError = _interopRequireDefault(require("./ValidationError"));
  16. var _memorize = _interopRequireDefault(require("./util/memorize"));
  17. function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
  18. const getAjv = (0, _memorize.default)(() => {
  19. // Use CommonJS require for ajv libs so TypeScript consumers aren't locked into esModuleInterop (see #110).
  20. // eslint-disable-next-line global-require
  21. const Ajv = require("ajv").default;
  22. // eslint-disable-next-line global-require
  23. const ajvKeywords = require("ajv-keywords").default;
  24. // eslint-disable-next-line global-require
  25. const addFormats = require("ajv-formats").default;
  26. /**
  27. * @type {Ajv}
  28. */
  29. const ajv = new Ajv({
  30. strict: false,
  31. allErrors: true,
  32. verbose: true,
  33. $data: true
  34. });
  35. ajvKeywords(ajv, ["instanceof", "patternRequired"]);
  36. // TODO set `{ keywords: true }` for the next major release and remove `keywords/limit.js`
  37. addFormats(ajv, {
  38. keywords: false
  39. });
  40. // Custom keywords
  41. // eslint-disable-next-line global-require
  42. const addAbsolutePathKeyword = require("./keywords/absolutePath").default;
  43. addAbsolutePathKeyword(ajv);
  44. // eslint-disable-next-line global-require
  45. const addLimitKeyword = require("./keywords/limit").default;
  46. addLimitKeyword(ajv);
  47. const addUndefinedAsNullKeyword =
  48. // eslint-disable-next-line global-require
  49. require("./keywords/undefinedAsNull").default;
  50. addUndefinedAsNullKeyword(ajv);
  51. return ajv;
  52. });
  53. /** @typedef {import("json-schema").JSONSchema4} JSONSchema4 */
  54. /** @typedef {import("json-schema").JSONSchema6} JSONSchema6 */
  55. /** @typedef {import("json-schema").JSONSchema7} JSONSchema7 */
  56. /** @typedef {import("ajv").ErrorObject} ErrorObject */
  57. /**
  58. * @typedef {Object} ExtendedSchema
  59. * @property {(string | number)=} formatMinimum
  60. * @property {(string | number)=} formatMaximum
  61. * @property {(string | boolean)=} formatExclusiveMinimum
  62. * @property {(string | boolean)=} formatExclusiveMaximum
  63. * @property {string=} link
  64. * @property {boolean=} undefinedAsNull
  65. */
  66. // TODO remove me in the next major release
  67. /** @typedef {ExtendedSchema} Extend */
  68. /** @typedef {(JSONSchema4 | JSONSchema6 | JSONSchema7) & ExtendedSchema} Schema */
  69. /** @typedef {ErrorObject & { children?: Array<ErrorObject> }} SchemaUtilErrorObject */
  70. /**
  71. * @callback PostFormatter
  72. * @param {string} formattedError
  73. * @param {SchemaUtilErrorObject} error
  74. * @returns {string}
  75. */
  76. /**
  77. * @typedef {Object} ValidationErrorConfiguration
  78. * @property {string=} name
  79. * @property {string=} baseDataPath
  80. * @property {PostFormatter=} postFormatter
  81. */
  82. /**
  83. * @param {SchemaUtilErrorObject} error
  84. * @param {number} idx
  85. * @returns {SchemaUtilErrorObject}
  86. */
  87. function applyPrefix(error, idx) {
  88. // eslint-disable-next-line no-param-reassign
  89. error.instancePath = `[${idx}]${error.instancePath}`;
  90. if (error.children) {
  91. error.children.forEach(err => applyPrefix(err, idx));
  92. }
  93. return error;
  94. }
  95. let skipValidation = false;
  96. // We use `process.env.SKIP_VALIDATION` because you can have multiple `schema-utils` with different version,
  97. // so we want to disable it globally, `process.env` doesn't supported by browsers, so we have the local `skipValidation` variables
  98. // Enable validation
  99. function enableValidation() {
  100. skipValidation = false;
  101. // Disable validation for any versions
  102. if (process && process.env) {
  103. process.env.SKIP_VALIDATION = "n";
  104. }
  105. }
  106. // Disable validation
  107. function disableValidation() {
  108. skipValidation = true;
  109. if (process && process.env) {
  110. process.env.SKIP_VALIDATION = "y";
  111. }
  112. }
  113. // Check if we need to confirm
  114. function needValidate() {
  115. if (skipValidation) {
  116. return false;
  117. }
  118. if (process && process.env && process.env.SKIP_VALIDATION) {
  119. const value = process.env.SKIP_VALIDATION.trim();
  120. if (/^(?:y|yes|true|1|on)$/i.test(value)) {
  121. return false;
  122. }
  123. if (/^(?:n|no|false|0|off)$/i.test(value)) {
  124. return true;
  125. }
  126. }
  127. return true;
  128. }
  129. /**
  130. * @param {Schema} schema
  131. * @param {Array<object> | object} options
  132. * @param {ValidationErrorConfiguration=} configuration
  133. * @returns {void}
  134. */
  135. function validate(schema, options, configuration) {
  136. if (!needValidate()) {
  137. return;
  138. }
  139. let errors = [];
  140. if (Array.isArray(options)) {
  141. for (let i = 0; i <= options.length - 1; i++) {
  142. errors.push(...validateObject(schema, options[i]).map(err => applyPrefix(err, i)));
  143. }
  144. } else {
  145. errors = validateObject(schema, options);
  146. }
  147. if (errors.length > 0) {
  148. throw new _ValidationError.default(errors, schema, configuration);
  149. }
  150. }
  151. /**
  152. * @param {Schema} schema
  153. * @param {Array<object> | object} options
  154. * @returns {Array<SchemaUtilErrorObject>}
  155. */
  156. function validateObject(schema, options) {
  157. // Not need to cache, because `ajv@8` has built-in cache
  158. const compiledSchema = getAjv().compile(schema);
  159. const valid = compiledSchema(options);
  160. if (valid) return [];
  161. return compiledSchema.errors ? filterErrors(compiledSchema.errors) : [];
  162. }
  163. /**
  164. * @param {Array<ErrorObject>} errors
  165. * @returns {Array<SchemaUtilErrorObject>}
  166. */
  167. function filterErrors(errors) {
  168. /** @type {Array<SchemaUtilErrorObject>} */
  169. let newErrors = [];
  170. for (const error of (/** @type {Array<SchemaUtilErrorObject>} */errors)) {
  171. const {
  172. instancePath
  173. } = error;
  174. /** @type {Array<SchemaUtilErrorObject>} */
  175. let children = [];
  176. newErrors = newErrors.filter(oldError => {
  177. if (oldError.instancePath.includes(instancePath)) {
  178. if (oldError.children) {
  179. children = children.concat(oldError.children.slice(0));
  180. }
  181. // eslint-disable-next-line no-undefined, no-param-reassign
  182. oldError.children = undefined;
  183. children.push(oldError);
  184. return false;
  185. }
  186. return true;
  187. });
  188. if (children.length) {
  189. error.children = children;
  190. }
  191. newErrors.push(error);
  192. }
  193. return newErrors;
  194. }