validate.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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} Extend
  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. /** @typedef {(JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend} Schema */
  67. /** @typedef {ErrorObject & { children?: Array<ErrorObject> }} SchemaUtilErrorObject */
  68. /**
  69. * @callback PostFormatter
  70. * @param {string} formattedError
  71. * @param {SchemaUtilErrorObject} error
  72. * @returns {string}
  73. */
  74. /**
  75. * @typedef {Object} ValidationErrorConfiguration
  76. * @property {string=} name
  77. * @property {string=} baseDataPath
  78. * @property {PostFormatter=} postFormatter
  79. */
  80. /**
  81. * @param {SchemaUtilErrorObject} error
  82. * @param {number} idx
  83. * @returns {SchemaUtilErrorObject}
  84. */
  85. function applyPrefix(error, idx) {
  86. // eslint-disable-next-line no-param-reassign
  87. error.instancePath = `[${idx}]${error.instancePath}`;
  88. if (error.children) {
  89. error.children.forEach(err => applyPrefix(err, idx));
  90. }
  91. return error;
  92. }
  93. let skipValidation = false;
  94. // We use `process.env.SKIP_VALIDATION` because you can have multiple `schema-utils` with different version,
  95. // so we want to disable it globally, `process.env` doesn't supported by browsers, so we have the local `skipValidation` variables
  96. // Enable validation
  97. function enableValidation() {
  98. skipValidation = false;
  99. // Disable validation for any versions
  100. if (process && process.env) {
  101. process.env.SKIP_VALIDATION = "n";
  102. }
  103. }
  104. // Disable validation
  105. function disableValidation() {
  106. skipValidation = true;
  107. if (process && process.env) {
  108. process.env.SKIP_VALIDATION = "y";
  109. }
  110. }
  111. // Check if we need to confirm
  112. function needValidate() {
  113. if (skipValidation) {
  114. return false;
  115. }
  116. if (process && process.env && process.env.SKIP_VALIDATION) {
  117. const value = process.env.SKIP_VALIDATION.trim();
  118. if (/^(?:y|yes|true|1|on)$/i.test(value)) {
  119. return false;
  120. }
  121. if (/^(?:n|no|false|0|off)$/i.test(value)) {
  122. return true;
  123. }
  124. }
  125. return true;
  126. }
  127. /**
  128. * @param {Schema} schema
  129. * @param {Array<object> | object} options
  130. * @param {ValidationErrorConfiguration=} configuration
  131. * @returns {void}
  132. */
  133. function validate(schema, options, configuration) {
  134. if (!needValidate()) {
  135. return;
  136. }
  137. let errors = [];
  138. if (Array.isArray(options)) {
  139. for (let i = 0; i <= options.length - 1; i++) {
  140. errors.push(...validateObject(schema, options[i]).map(err => applyPrefix(err, i)));
  141. }
  142. } else {
  143. errors = validateObject(schema, options);
  144. }
  145. if (errors.length > 0) {
  146. throw new _ValidationError.default(errors, schema, configuration);
  147. }
  148. }
  149. /**
  150. * @param {Schema} schema
  151. * @param {Array<object> | object} options
  152. * @returns {Array<SchemaUtilErrorObject>}
  153. */
  154. function validateObject(schema, options) {
  155. // Not need to cache, because `ajv@8` has built-in cache
  156. const compiledSchema = getAjv().compile(schema);
  157. const valid = compiledSchema(options);
  158. if (valid) return [];
  159. return compiledSchema.errors ? filterErrors(compiledSchema.errors) : [];
  160. }
  161. /**
  162. * @param {Array<ErrorObject>} errors
  163. * @returns {Array<SchemaUtilErrorObject>}
  164. */
  165. function filterErrors(errors) {
  166. /** @type {Array<SchemaUtilErrorObject>} */
  167. let newErrors = [];
  168. for (const error of (/** @type {Array<SchemaUtilErrorObject>} */errors)) {
  169. const {
  170. instancePath
  171. } = error;
  172. /** @type {Array<SchemaUtilErrorObject>} */
  173. let children = [];
  174. newErrors = newErrors.filter(oldError => {
  175. if (oldError.instancePath.includes(instancePath)) {
  176. if (oldError.children) {
  177. children = children.concat(oldError.children.slice(0));
  178. }
  179. // eslint-disable-next-line no-undefined, no-param-reassign
  180. oldError.children = undefined;
  181. children.push(oldError);
  182. return false;
  183. }
  184. return true;
  185. });
  186. if (children.length) {
  187. error.children = children;
  188. }
  189. newErrors.push(error);
  190. }
  191. return newErrors;
  192. }