@rjsf/validator-ajv8 5.0.0-beta.8 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,46 @@
1
1
  import toPath from 'lodash-es/toPath';
2
- import { ERRORS_KEY, isObject as isObject$1, getDefaultFormState, mergeValidationData, REF_KEY } from '@rjsf/utils';
2
+ import isObject from 'lodash-es/isObject';
3
+ import clone from 'lodash-es/clone';
4
+ import { ADDITIONAL_PROPERTY_FLAG, RJSF_ADDITONAL_PROPERTIES_FLAG, ErrorSchemaBuilder, ERRORS_KEY, getUiOptions, PROPERTIES_KEY, getDefaultFormState, mergeValidationData, REF_KEY } from '@rjsf/utils';
5
+ import get from 'lodash-es/get';
3
6
  import Ajv from 'ajv';
4
7
  import addFormats from 'ajv-formats';
5
- import isObject from 'lodash-es/isObject';
6
8
 
7
- const AJV_CONFIG = {
9
+ function _extends() {
10
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
11
+ for (var i = 1; i < arguments.length; i++) {
12
+ var source = arguments[i];
13
+ for (var key in source) {
14
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
15
+ target[key] = source[key];
16
+ }
17
+ }
18
+ }
19
+ return target;
20
+ };
21
+ return _extends.apply(this, arguments);
22
+ }
23
+ function _objectWithoutPropertiesLoose(source, excluded) {
24
+ if (source == null) return {};
25
+ var target = {};
26
+ var sourceKeys = Object.keys(source);
27
+ var key, i;
28
+ for (i = 0; i < sourceKeys.length; i++) {
29
+ key = sourceKeys[i];
30
+ if (excluded.indexOf(key) >= 0) continue;
31
+ target[key] = source[key];
32
+ }
33
+ return target;
34
+ }
35
+
36
+ var AJV_CONFIG = {
8
37
  allErrors: true,
9
- multipleOfPrecision: 8
38
+ multipleOfPrecision: 8,
39
+ strict: false,
40
+ verbose: true
10
41
  };
11
- const COLOR_FORMAT_REGEX = /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/;
12
- const DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
42
+ var COLOR_FORMAT_REGEX = /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/;
43
+ var DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
13
44
  /** Creates an Ajv version 8 implementation object with standard support for the 'color` and `data-url` custom formats.
14
45
  * If `additionalMetaSchemas` are provided then the Ajv instance is modified to add each of the meta schemas in the
15
46
  * list. If `customFormats` are provided then those additional formats are added to the list of supported formats. If
@@ -23,44 +54,45 @@ const DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base
23
54
  * @param [customFormats] - The set of additional custom formats that the validator will support
24
55
  * @param [ajvOptionsOverrides={}] - The set of validator config override options
25
56
  * @param [ajvFormatOptions] - The `ajv-format` options to use when adding formats to `ajv`; pass `false` to disable it
57
+ * @param [AjvClass] - The `Ajv` class to use when creating the validator instance
26
58
  */
27
-
28
- function createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions) {
59
+ function createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions, AjvClass) {
29
60
  if (ajvOptionsOverrides === void 0) {
30
61
  ajvOptionsOverrides = {};
31
62
  }
32
-
33
- const ajv = new Ajv({ ...AJV_CONFIG,
34
- ...ajvOptionsOverrides
35
- });
36
-
37
- if (typeof ajvFormatOptions !== "boolean") {
63
+ if (AjvClass === void 0) {
64
+ AjvClass = Ajv;
65
+ }
66
+ var ajv = new AjvClass(_extends({}, AJV_CONFIG, ajvOptionsOverrides));
67
+ if (ajvFormatOptions) {
38
68
  addFormats(ajv, ajvFormatOptions);
39
- } // add custom formats
40
-
41
-
69
+ } else if (ajvFormatOptions !== false) {
70
+ addFormats(ajv);
71
+ }
72
+ // add custom formats
42
73
  ajv.addFormat("data-url", DATA_URL_FORMAT_REGEX);
43
- ajv.addFormat("color", COLOR_FORMAT_REGEX); // add more schemas to validate against
44
-
74
+ ajv.addFormat("color", COLOR_FORMAT_REGEX);
75
+ // Add RJSF-specific additional properties keywords so Ajv doesn't report errors if strict is enabled.
76
+ ajv.addKeyword(ADDITIONAL_PROPERTY_FLAG);
77
+ ajv.addKeyword(RJSF_ADDITONAL_PROPERTIES_FLAG);
78
+ // add more schemas to validate against
45
79
  if (Array.isArray(additionalMetaSchemas)) {
46
80
  ajv.addMetaSchema(additionalMetaSchemas);
47
- } // add more custom formats to validate against
48
-
49
-
81
+ }
82
+ // add more custom formats to validate against
50
83
  if (isObject(customFormats)) {
51
- Object.keys(customFormats).forEach(formatName => {
84
+ Object.keys(customFormats).forEach(function (formatName) {
52
85
  ajv.addFormat(formatName, customFormats[formatName]);
53
86
  });
54
87
  }
55
-
56
88
  return ajv;
57
89
  }
58
90
 
59
- const ROOT_SCHEMA_PREFIX = "__rjsf_rootSchema";
91
+ var _excluded = ["instancePath", "keyword", "params", "schemaPath", "parentSchema"];
92
+ var ROOT_SCHEMA_PREFIX = "__rjsf_rootSchema";
60
93
  /** `ValidatorType` implementation that uses the AJV 8 validation mechanism.
61
94
  */
62
-
63
- class AJV8Validator {
95
+ var AJV8Validator = /*#__PURE__*/function () {
64
96
  /** The AJV instance to use for all validations
65
97
  *
66
98
  * @private
@@ -76,16 +108,15 @@ class AJV8Validator {
76
108
  * @param options - The `CustomValidatorOptionsType` options that are used to create the AJV instance
77
109
  * @param [localizer] - If provided, is used to localize a list of Ajv `ErrorObject`s
78
110
  */
79
- constructor(options, localizer) {
111
+ function AJV8Validator(options, localizer) {
80
112
  this.ajv = void 0;
81
113
  this.localizer = void 0;
82
- const {
83
- additionalMetaSchemas,
84
- customFormats,
85
- ajvOptionsOverrides,
86
- ajvFormatOptions
87
- } = options;
88
- this.ajv = createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions);
114
+ var additionalMetaSchemas = options.additionalMetaSchemas,
115
+ customFormats = options.customFormats,
116
+ ajvOptionsOverrides = options.ajvOptionsOverrides,
117
+ ajvFormatOptions = options.ajvFormatOptions,
118
+ AjvClass = options.AjvClass;
119
+ this.ajv = createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions, AjvClass);
89
120
  this.localizer = localizer;
90
121
  }
91
122
  /** Transforms a ajv validation errors list:
@@ -107,82 +138,54 @@ class AJV8Validator {
107
138
  * @param errors - The list of RJSFValidationError objects
108
139
  * @private
109
140
  */
110
-
111
-
112
- toErrorSchema(errors) {
113
- if (!errors.length) {
114
- return {};
115
- }
116
-
117
- return errors.reduce((errorSchema, error) => {
118
- const {
119
- property,
120
- message
121
- } = error;
122
- const path = toPath(property);
123
- let parent = errorSchema; // If the property is at the root (.level1) then toPath creates
124
- // an empty array element at the first index. Remove it.
125
-
126
- if (path.length > 0 && path[0] === "") {
127
- path.splice(0, 1);
128
- }
129
-
130
- for (const segment of path.slice(0)) {
131
- if (!(segment in parent)) {
132
- parent[segment] = {};
141
+ var _proto = AJV8Validator.prototype;
142
+ _proto.toErrorSchema = function toErrorSchema(errors) {
143
+ var builder = new ErrorSchemaBuilder();
144
+ if (errors.length) {
145
+ errors.forEach(function (error) {
146
+ var property = error.property,
147
+ message = error.message;
148
+ var path = toPath(property);
149
+ // If the property is at the root (.level1) then toPath creates
150
+ // an empty array element at the first index. Remove it.
151
+ if (path.length > 0 && path[0] === "") {
152
+ path.splice(0, 1);
133
153
  }
134
-
135
- parent = parent[segment];
136
- }
137
-
138
- if (Array.isArray(parent.__errors)) {
139
- // We store the list of errors for this node in a property named __errors
140
- // to avoid name collision with a possible sub schema field named
141
- // 'errors' (see `validate.createErrorHandler`).
142
- parent.__errors = parent.__errors.concat(message);
143
- } else {
144
154
  if (message) {
145
- parent.__errors = [message];
155
+ builder.addErrors(message, path);
146
156
  }
147
- }
148
-
149
- return errorSchema;
150
- }, {});
157
+ });
158
+ }
159
+ return builder.ErrorSchema;
151
160
  }
152
161
  /** Converts an `errorSchema` into a list of `RJSFValidationErrors`
153
162
  *
154
163
  * @param errorSchema - The `ErrorSchema` instance to convert
155
164
  * @param [fieldPath=[]] - The current field path, defaults to [] if not specified
156
- */
157
-
158
-
159
- toErrorList(errorSchema, fieldPath) {
165
+ */;
166
+ _proto.toErrorList = function toErrorList(errorSchema, fieldPath) {
167
+ var _this = this;
160
168
  if (fieldPath === void 0) {
161
169
  fieldPath = [];
162
170
  }
163
-
164
171
  if (!errorSchema) {
165
172
  return [];
166
173
  }
167
-
168
- let errorList = [];
169
-
174
+ var errorList = [];
170
175
  if (ERRORS_KEY in errorSchema) {
171
- errorList = errorList.concat(errorSchema.__errors.map(message => {
172
- const property = "." + fieldPath.join(".");
176
+ errorList = errorList.concat(errorSchema[ERRORS_KEY].map(function (message) {
177
+ var property = "." + fieldPath.join(".");
173
178
  return {
174
- property,
175
- message,
179
+ property: property,
180
+ message: message,
176
181
  stack: property + " " + message
177
182
  };
178
183
  }));
179
184
  }
180
-
181
- return Object.keys(errorSchema).reduce((acc, key) => {
185
+ return Object.keys(errorSchema).reduce(function (acc, key) {
182
186
  if (key !== ERRORS_KEY) {
183
- acc = acc.concat(this.toErrorList(errorSchema[key], [...fieldPath, key]));
187
+ acc = acc.concat(_this.toErrorList(errorSchema[key], [].concat(fieldPath, [key])));
184
188
  }
185
-
186
189
  return acc;
187
190
  }, errorList);
188
191
  }
@@ -190,100 +193,141 @@ class AJV8Validator {
190
193
  *
191
194
  * @param formData - The form data around which the error handler is created
192
195
  * @private
193
- */
194
-
195
-
196
- createErrorHandler(formData) {
197
- const handler = {
196
+ */;
197
+ _proto.createErrorHandler = function createErrorHandler(formData) {
198
+ var _this2 = this;
199
+ var handler = {
198
200
  // We store the list of errors for this node in a property named __errors
199
201
  // to avoid name collision with a possible sub schema field named
200
202
  // 'errors' (see `utils.toErrorSchema`).
201
203
  __errors: [],
202
-
203
- addError(message) {
204
+ addError: function addError(message) {
204
205
  this.__errors.push(message);
205
206
  }
206
-
207
207
  };
208
-
209
- if (isObject$1(formData)) {
210
- const formObject = formData;
211
- return Object.keys(formObject).reduce((acc, key) => {
212
- return { ...acc,
213
- [key]: this.createErrorHandler(formObject[key])
214
- };
208
+ if (Array.isArray(formData)) {
209
+ return formData.reduce(function (acc, value, key) {
210
+ var _extends2;
211
+ return _extends({}, acc, (_extends2 = {}, _extends2[key] = _this2.createErrorHandler(value), _extends2));
215
212
  }, handler);
216
213
  }
217
-
218
- if (Array.isArray(formData)) {
219
- return formData.reduce((acc, value, key) => {
220
- return { ...acc,
221
- [key]: this.createErrorHandler(value)
222
- };
214
+ if (isObject(formData)) {
215
+ var formObject = formData;
216
+ return Object.keys(formObject).reduce(function (acc, key) {
217
+ var _extends3;
218
+ return _extends({}, acc, (_extends3 = {}, _extends3[key] = _this2.createErrorHandler(formObject[key]), _extends3));
223
219
  }, handler);
224
220
  }
225
-
226
221
  return handler;
227
222
  }
228
223
  /** Unwraps the `errorHandler` structure into the associated `ErrorSchema`, stripping the `addError` functions from it
229
224
  *
230
225
  * @param errorHandler - The `FormValidation` error handling structure
231
226
  * @private
232
- */
233
-
234
-
235
- unwrapErrorHandler(errorHandler) {
236
- return Object.keys(errorHandler).reduce((acc, key) => {
227
+ */;
228
+ _proto.unwrapErrorHandler = function unwrapErrorHandler(errorHandler) {
229
+ var _this3 = this;
230
+ return Object.keys(errorHandler).reduce(function (acc, key) {
231
+ var _extends5;
237
232
  if (key === "addError") {
238
233
  return acc;
239
234
  } else if (key === ERRORS_KEY) {
240
- return { ...acc,
241
- [key]: errorHandler[key]
242
- };
235
+ var _extends4;
236
+ return _extends({}, acc, (_extends4 = {}, _extends4[key] = errorHandler[key], _extends4));
243
237
  }
244
-
245
- return { ...acc,
246
- [key]: this.unwrapErrorHandler(errorHandler[key])
247
- };
238
+ return _extends({}, acc, (_extends5 = {}, _extends5[key] = _this3.unwrapErrorHandler(errorHandler[key]), _extends5));
248
239
  }, {});
249
240
  }
250
241
  /** Transforming the error output from ajv to format used by @rjsf/utils.
251
242
  * At some point, components should be updated to support ajv.
252
243
  *
253
244
  * @param errors - The list of AJV errors to convert to `RJSFValidationErrors`
254
- * @private
255
- */
256
-
257
-
258
- transformRJSFValidationErrors(errors) {
245
+ * @protected
246
+ */;
247
+ _proto.transformRJSFValidationErrors = function transformRJSFValidationErrors(errors, uiSchema) {
259
248
  if (errors === void 0) {
260
249
  errors = [];
261
250
  }
262
-
263
- if (errors === null) {
264
- return [];
265
- }
266
-
267
- return errors.map(e => {
268
- const {
269
- instancePath,
270
- keyword,
271
- message,
272
- params,
273
- schemaPath
274
- } = e;
275
- const property = instancePath.replace(/\//g, "."); // put data in expected format
276
-
251
+ return errors.map(function (e) {
252
+ var instancePath = e.instancePath,
253
+ keyword = e.keyword,
254
+ params = e.params,
255
+ schemaPath = e.schemaPath,
256
+ parentSchema = e.parentSchema,
257
+ rest = _objectWithoutPropertiesLoose(e, _excluded);
258
+ var _rest$message = rest.message,
259
+ message = _rest$message === void 0 ? "" : _rest$message;
260
+ var property = instancePath.replace(/\//g, ".");
261
+ var stack = (property + " " + message).trim();
262
+ if ("missingProperty" in params) {
263
+ property = property ? property + "." + params.missingProperty : params.missingProperty;
264
+ var currentProperty = params.missingProperty;
265
+ var uiSchemaTitle = getUiOptions(get(uiSchema, "" + property.replace(/^\./, ""))).title;
266
+ if (uiSchemaTitle) {
267
+ message = message.replace(currentProperty, uiSchemaTitle);
268
+ } else {
269
+ var parentSchemaTitle = get(parentSchema, [PROPERTIES_KEY, currentProperty, "title"]);
270
+ if (parentSchemaTitle) {
271
+ message = message.replace(currentProperty, parentSchemaTitle);
272
+ }
273
+ }
274
+ stack = message;
275
+ } else {
276
+ var _uiSchemaTitle = getUiOptions(get(uiSchema, "" + property.replace(/^\./, ""))).title;
277
+ if (_uiSchemaTitle) {
278
+ stack = ("'" + _uiSchemaTitle + "' " + message).trim();
279
+ } else {
280
+ var _parentSchemaTitle = parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.title;
281
+ if (_parentSchemaTitle) {
282
+ stack = ("'" + _parentSchemaTitle + "' " + message).trim();
283
+ }
284
+ }
285
+ }
286
+ // put data in expected format
277
287
  return {
278
288
  name: keyword,
279
- property,
280
- message,
281
- params,
282
- stack: (property + " " + message).trim(),
283
- schemaPath
289
+ property: property,
290
+ message: message,
291
+ params: params,
292
+ stack: stack,
293
+ schemaPath: schemaPath
284
294
  };
285
295
  });
286
296
  }
297
+ /** Runs the pure validation of the `schema` and `formData` without any of the RJSF functionality. Provided for use
298
+ * by the playground. Returns the `errors` from the validation
299
+ *
300
+ * @param schema - The schema against which to validate the form data * @param schema
301
+ * @param formData - The form data to validate
302
+ */;
303
+ _proto.rawValidation = function rawValidation(schema, formData) {
304
+ var compilationError = undefined;
305
+ var compiledValidator;
306
+ if (schema["$id"]) {
307
+ compiledValidator = this.ajv.getSchema(schema["$id"]);
308
+ }
309
+ try {
310
+ if (compiledValidator === undefined) {
311
+ compiledValidator = this.ajv.compile(schema);
312
+ }
313
+ compiledValidator(formData);
314
+ } catch (err) {
315
+ compilationError = err;
316
+ }
317
+ var errors;
318
+ if (compiledValidator) {
319
+ if (typeof this.localizer === "function") {
320
+ this.localizer(compiledValidator.errors);
321
+ }
322
+ errors = compiledValidator.errors || undefined;
323
+ // Clear errors to prevent persistent errors, see #1104
324
+ compiledValidator.errors = null;
325
+ }
326
+ return {
327
+ errors: errors,
328
+ validationError: compilationError
329
+ };
330
+ }
287
331
  /** This function processes the `formData` with an optional user contributed `customValidate` function, which receives
288
332
  * the form data and a `errorHandler` function that will be used to add custom validation errors for each field. Also
289
333
  * supports a `transformErrors` function that will take the raw AJV validation errors, prior to custom validation and
@@ -293,64 +337,41 @@ class AJV8Validator {
293
337
  * @param schema - The schema against which to validate the form data
294
338
  * @param [customValidate] - An optional function that is used to perform custom validation
295
339
  * @param [transformErrors] - An optional function that is used to transform errors after AJV validation
296
- */
297
-
298
-
299
- validateFormData(formData, schema, customValidate, transformErrors) {
300
- // Include form data with undefined values, which is required for validation.
301
- const rootSchema = schema;
302
- const newFormData = getDefaultFormState(this, schema, formData, rootSchema, true);
303
- let validationError = null;
304
-
305
- try {
306
- this.ajv.validate(schema, newFormData);
307
- } catch (err) {
308
- validationError = err;
309
- }
310
-
311
- if (typeof this.localizer === "function") {
312
- this.localizer(this.ajv.errors);
313
- }
314
-
315
- let errors = this.transformRJSFValidationErrors(this.ajv.errors); // Clear errors to prevent persistent errors, see #1104
316
-
317
- this.ajv.errors = null;
318
- const noProperMetaSchema = validationError && validationError.message && typeof validationError.message === "string" && validationError.message.includes("no schema with key or ref ");
319
-
320
- if (noProperMetaSchema) {
321
- errors = [...errors, {
322
- stack: validationError.message
323
- }];
340
+ * @param [uiSchema] - An optional uiSchema that is passed to `transformErrors` and `customValidate`
341
+ */;
342
+ _proto.validateFormData = function validateFormData(formData, schema, customValidate, transformErrors, uiSchema) {
343
+ var rawErrors = this.rawValidation(schema, formData);
344
+ var invalidSchemaError = rawErrors.validationError;
345
+ var errors = this.transformRJSFValidationErrors(rawErrors.errors, uiSchema);
346
+ if (invalidSchemaError) {
347
+ errors = [].concat(errors, [{
348
+ stack: invalidSchemaError.message
349
+ }]);
324
350
  }
325
-
326
351
  if (typeof transformErrors === "function") {
327
- errors = transformErrors(errors);
352
+ errors = transformErrors(errors, uiSchema);
328
353
  }
329
-
330
- let errorSchema = this.toErrorSchema(errors);
331
-
332
- if (noProperMetaSchema) {
333
- errorSchema = { ...errorSchema,
334
- ...{
335
- $schema: {
336
- __errors: [validationError.message]
337
- }
354
+ var errorSchema = this.toErrorSchema(errors);
355
+ if (invalidSchemaError) {
356
+ errorSchema = _extends({}, errorSchema, {
357
+ $schema: {
358
+ __errors: [invalidSchemaError.message]
338
359
  }
339
- };
360
+ });
340
361
  }
341
-
342
362
  if (typeof customValidate !== "function") {
343
363
  return {
344
- errors,
345
- errorSchema
364
+ errors: errors,
365
+ errorSchema: errorSchema
346
366
  };
347
367
  }
348
-
349
- const errorHandler = customValidate(newFormData, this.createErrorHandler(newFormData));
350
- const userErrorSchema = this.unwrapErrorHandler(errorHandler);
368
+ // Include form data with undefined values, which is required for custom validation.
369
+ var newFormData = getDefaultFormState(this, schema, formData, schema, true);
370
+ var errorHandler = customValidate(newFormData, this.createErrorHandler(newFormData), uiSchema);
371
+ var userErrorSchema = this.unwrapErrorHandler(errorHandler);
351
372
  return mergeValidationData(this, {
352
- errors,
353
- errorSchema
373
+ errors: errors,
374
+ errorSchema: errorSchema
354
375
  }, userErrorSchema);
355
376
  }
356
377
  /** Takes a `node` object and transforms any contained `$ref` node variables with a prefix, recursively calling
@@ -358,61 +379,67 @@ class AJV8Validator {
358
379
  *
359
380
  * @param node - The object node to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it
360
381
  * @private
361
- */
362
-
363
-
364
- withIdRefPrefixObject(node) {
365
- for (const key in node) {
366
- const realObj = node;
367
- const value = realObj[key];
368
-
382
+ */;
383
+ _proto.withIdRefPrefixObject = function withIdRefPrefixObject(node) {
384
+ for (var key in node) {
385
+ var realObj = node;
386
+ var value = realObj[key];
369
387
  if (key === REF_KEY && typeof value === "string" && value.startsWith("#")) {
370
388
  realObj[key] = ROOT_SCHEMA_PREFIX + value;
371
389
  } else {
372
390
  realObj[key] = this.withIdRefPrefix(value);
373
391
  }
374
392
  }
375
-
376
393
  return node;
377
394
  }
378
395
  /** Takes a `node` object list and transforms any contained `$ref` node variables with a prefix, recursively calling
379
396
  * `withIdRefPrefix` for any other elements.
380
397
  *
381
- * @param nodeThe - list of object nodes to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it
398
+ * @param node - The list of object nodes to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it
382
399
  * @private
383
- */
384
-
385
-
386
- withIdRefPrefixArray(node) {
387
- for (let i = 0; i < node.length; i++) {
400
+ */;
401
+ _proto.withIdRefPrefixArray = function withIdRefPrefixArray(node) {
402
+ for (var i = 0; i < node.length; i++) {
388
403
  node[i] = this.withIdRefPrefix(node[i]);
389
404
  }
390
-
391
405
  return node;
392
406
  }
393
407
  /** Validates data against a schema, returning true if the data is valid, or
394
408
  * false otherwise. If the schema is invalid, then this function will return
395
409
  * false.
396
410
  *
397
- * @param schema - The schema against which to validate the form data * @param schema
398
- * @param formData- - The form data to validate
411
+ * @param schema - The schema against which to validate the form data
412
+ * @param formData - The form data to validate
399
413
  * @param rootSchema - The root schema used to provide $ref resolutions
400
- */
401
-
402
-
403
- isValid(schema, formData, rootSchema) {
414
+ */;
415
+ _proto.isValid = function isValid(schema, formData, rootSchema) {
416
+ var _rootSchema$$id;
417
+ var rootSchemaId = (_rootSchema$$id = rootSchema["$id"]) != null ? _rootSchema$$id : ROOT_SCHEMA_PREFIX;
404
418
  try {
405
419
  // add the rootSchema ROOT_SCHEMA_PREFIX as id.
406
420
  // then rewrite the schema ref's to point to the rootSchema
407
421
  // this accounts for the case where schema have references to models
408
422
  // that lives in the rootSchema but not in the schema in question.
409
- const result = this.ajv.addSchema(rootSchema, ROOT_SCHEMA_PREFIX).validate(this.withIdRefPrefix(schema), formData);
423
+ if (this.ajv.getSchema(rootSchemaId) === undefined) {
424
+ this.ajv.addSchema(rootSchema, rootSchemaId);
425
+ }
426
+ var schemaWithIdRefPrefix = this.withIdRefPrefix(schema);
427
+ var compiledValidator;
428
+ if (schemaWithIdRefPrefix["$id"]) {
429
+ compiledValidator = this.ajv.getSchema(schemaWithIdRefPrefix["$id"]);
430
+ }
431
+ if (compiledValidator === undefined) {
432
+ compiledValidator = this.ajv.compile(schemaWithIdRefPrefix);
433
+ }
434
+ var result = compiledValidator(formData);
410
435
  return result;
411
436
  } catch (e) {
437
+ console.warn("Error encountered compiling schema:", e);
412
438
  return false;
413
439
  } finally {
440
+ // TODO: A function should be called if the root schema changes so we don't have to remove and recompile the schema every run.
414
441
  // make sure we remove the rootSchema from the global ajv instance
415
- this.ajv.removeSchema(ROOT_SCHEMA_PREFIX);
442
+ this.ajv.removeSchema(rootSchemaId);
416
443
  }
417
444
  }
418
445
  /** Recursively prefixes all $ref's in a schema with `ROOT_SCHEMA_PREFIX`
@@ -420,23 +447,18 @@ class AJV8Validator {
420
447
  *
421
448
  * @param schemaNode - The object node to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it
422
449
  * @protected
423
- */
424
-
425
-
426
- withIdRefPrefix(schemaNode) {
427
- if (schemaNode.constructor === Object) {
428
- return this.withIdRefPrefixObject({ ...schemaNode
429
- });
430
- }
431
-
450
+ */;
451
+ _proto.withIdRefPrefix = function withIdRefPrefix(schemaNode) {
432
452
  if (Array.isArray(schemaNode)) {
433
- return this.withIdRefPrefixArray([...schemaNode]);
453
+ return this.withIdRefPrefixArray([].concat(schemaNode));
454
+ }
455
+ if (isObject(schemaNode)) {
456
+ return this.withIdRefPrefixObject(clone(schemaNode));
434
457
  }
435
-
436
458
  return schemaNode;
437
- }
438
-
439
- }
459
+ };
460
+ return AJV8Validator;
461
+ }();
440
462
 
441
463
  /** Creates and returns a customized implementation of the `ValidatorType` with the given customization `options` if
442
464
  * provided.
@@ -444,12 +466,10 @@ class AJV8Validator {
444
466
  * @param [options={}] - The `CustomValidatorOptionsType` options that are used to create the `ValidatorType` instance
445
467
  * @param [localizer] - If provided, is used to localize a list of Ajv `ErrorObject`s
446
468
  */
447
-
448
469
  function customizeValidator(options, localizer) {
449
470
  if (options === void 0) {
450
471
  options = {};
451
472
  }
452
-
453
473
  return new AJV8Validator(options, localizer);
454
474
  }
455
475