UNPKG

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