@rjsf/validator-ajv8 5.0.0-beta.5

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.
@@ -0,0 +1,458 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('lodash-es/toPath'), require('@rjsf/utils'), require('ajv'), require('ajv-formats'), require('lodash-es/isObject')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'lodash-es/toPath', '@rjsf/utils', 'ajv', 'ajv-formats', 'lodash-es/isObject'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@rjsf/validator-ajv8"] = {}, global.toPath, global.utils, global.Ajv, global.addFormats, global.isObject));
5
+ })(this, (function (exports, toPath, utils, Ajv, addFormats, isObject) { 'use strict';
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
+
9
+ var toPath__default = /*#__PURE__*/_interopDefaultLegacy(toPath);
10
+ var Ajv__default = /*#__PURE__*/_interopDefaultLegacy(Ajv);
11
+ var addFormats__default = /*#__PURE__*/_interopDefaultLegacy(addFormats);
12
+ var isObject__default = /*#__PURE__*/_interopDefaultLegacy(isObject);
13
+
14
+ const AJV_CONFIG = {
15
+ allErrors: true,
16
+ multipleOfPrecision: 8
17
+ };
18
+ 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*\)))$/;
19
+ const DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
20
+ /** Creates an Ajv version 8 implementation object with standard support for the 'color` and `data-url` custom formats.
21
+ * If `additionalMetaSchemas` are provided then the Ajv instance is modified to add each of the meta schemas in the
22
+ * list. If `customFormats` are provided then those additional formats are added to the list of supported formats. If
23
+ * `ajvOptionsOverrides` are provided then they are spread on top of the default `AJV_CONFIG` options when constructing
24
+ * the `Ajv` instance. With Ajv v8, the JSON Schema formats are not provided by default, but can be plugged in. By
25
+ * default, all formats from the `ajv-formats` library are added. To disable this capability, set the `ajvFormatOptions`
26
+ * parameter to `false`. Additionally, you can configure the `ajv-formats` by providing a custom set of
27
+ * [format options](https://github.com/ajv-validator/ajv-formats) to the `ajvFormatOptions` parameter.
28
+ *
29
+ * @param [additionalMetaSchemas] - The list of additional meta schemas that the validator can access
30
+ * @param [customFormats] - The set of additional custom formats that the validator will support
31
+ * @param [ajvOptionsOverrides={}] - The set of validator config override options
32
+ * @param [ajvFormatOptions] - The `ajv-format` options to use when adding formats to `ajv`; pass `false` to disable it
33
+ */
34
+
35
+ function createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions) {
36
+ if (ajvOptionsOverrides === void 0) {
37
+ ajvOptionsOverrides = {};
38
+ }
39
+
40
+ const ajv = new Ajv__default["default"]({ ...AJV_CONFIG,
41
+ ...ajvOptionsOverrides
42
+ });
43
+
44
+ if (typeof ajvFormatOptions !== "boolean") {
45
+ addFormats__default["default"](ajv, ajvFormatOptions);
46
+ } // add custom formats
47
+
48
+
49
+ ajv.addFormat("data-url", DATA_URL_FORMAT_REGEX);
50
+ ajv.addFormat("color", COLOR_FORMAT_REGEX); // add more schemas to validate against
51
+
52
+ if (Array.isArray(additionalMetaSchemas)) {
53
+ ajv.addMetaSchema(additionalMetaSchemas);
54
+ } // add more custom formats to validate against
55
+
56
+
57
+ if (isObject__default["default"](customFormats)) {
58
+ Object.keys(customFormats).forEach(formatName => {
59
+ ajv.addFormat(formatName, customFormats[formatName]);
60
+ });
61
+ }
62
+
63
+ return ajv;
64
+ }
65
+
66
+ const ROOT_SCHEMA_PREFIX = "__rjsf_rootSchema";
67
+ /** `ValidatorType` implementation that uses the AJV 8 validation mechanism.
68
+ */
69
+
70
+ class AJV8Validator {
71
+ /** The AJV instance to use for all validations
72
+ *
73
+ * @private
74
+ */
75
+
76
+ /** Constructs an `AJV8Validator` instance using the `options`
77
+ *
78
+ * @param options - The `CustomValidatorOptionsType` options that are used to create the AJV instance
79
+ */
80
+ constructor(options) {
81
+ this.ajv = void 0;
82
+ const {
83
+ additionalMetaSchemas,
84
+ customFormats,
85
+ ajvOptionsOverrides,
86
+ ajvFormatOptions
87
+ } = options;
88
+ this.ajv = createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions);
89
+ }
90
+ /** Transforms a ajv validation errors list:
91
+ * [
92
+ * {property: '.level1.level2[2].level3', message: 'err a'},
93
+ * {property: '.level1.level2[2].level3', message: 'err b'},
94
+ * {property: '.level1.level2[4].level3', message: 'err b'},
95
+ * ]
96
+ * Into an error tree:
97
+ * {
98
+ * level1: {
99
+ * level2: {
100
+ * 2: {level3: {errors: ['err a', 'err b']}},
101
+ * 4: {level3: {errors: ['err b']}},
102
+ * }
103
+ * }
104
+ * };
105
+ *
106
+ * @param errors - The list of RJSFValidationError objects
107
+ * @private
108
+ */
109
+
110
+
111
+ toErrorSchema(errors) {
112
+ if (!errors.length) {
113
+ return {};
114
+ }
115
+
116
+ return errors.reduce((errorSchema, error) => {
117
+ const {
118
+ property,
119
+ message
120
+ } = error;
121
+ const path = toPath__default["default"](property);
122
+ let parent = errorSchema; // If the property is at the root (.level1) then toPath creates
123
+ // an empty array element at the first index. Remove it.
124
+
125
+ if (path.length > 0 && path[0] === "") {
126
+ path.splice(0, 1);
127
+ }
128
+
129
+ for (const segment of path.slice(0)) {
130
+ if (!(segment in parent)) {
131
+ parent[segment] = {};
132
+ }
133
+
134
+ parent = parent[segment];
135
+ }
136
+
137
+ if (Array.isArray(parent.__errors)) {
138
+ // We store the list of errors for this node in a property named __errors
139
+ // to avoid name collision with a possible sub schema field named
140
+ // 'errors' (see `validate.createErrorHandler`).
141
+ parent.__errors = parent.__errors.concat(message);
142
+ } else {
143
+ if (message) {
144
+ parent.__errors = [message];
145
+ }
146
+ }
147
+
148
+ return errorSchema;
149
+ }, {});
150
+ }
151
+ /** Converts an `errorSchema` into a list of `RJSFValidationErrors`
152
+ *
153
+ * @param errorSchema - The `ErrorSchema` instance to convert
154
+ * @param [fieldPath=[]] - The current field path, defaults to [] if not specified
155
+ */
156
+
157
+
158
+ toErrorList(errorSchema, fieldPath) {
159
+ if (fieldPath === void 0) {
160
+ fieldPath = [];
161
+ }
162
+
163
+ if (!errorSchema) {
164
+ return [];
165
+ }
166
+
167
+ let errorList = [];
168
+
169
+ if (utils.ERRORS_KEY in errorSchema) {
170
+ errorList = errorList.concat(errorSchema.__errors.map(message => {
171
+ const property = "." + fieldPath.join(".");
172
+ return {
173
+ property,
174
+ message,
175
+ stack: property + " " + message
176
+ };
177
+ }));
178
+ }
179
+
180
+ return Object.keys(errorSchema).reduce((acc, key) => {
181
+ if (key !== utils.ERRORS_KEY) {
182
+ acc = acc.concat(this.toErrorList(errorSchema[key], [...fieldPath, key]));
183
+ }
184
+
185
+ return acc;
186
+ }, errorList);
187
+ }
188
+ /** Given a `formData` object, recursively creates a `FormValidation` error handling structure around it
189
+ *
190
+ * @param formData - The form data around which the error handler is created
191
+ * @private
192
+ */
193
+
194
+
195
+ createErrorHandler(formData) {
196
+ const handler = {
197
+ // We store the list of errors for this node in a property named __errors
198
+ // to avoid name collision with a possible sub schema field named
199
+ // 'errors' (see `utils.toErrorSchema`).
200
+ __errors: [],
201
+
202
+ addError(message) {
203
+ this.__errors.push(message);
204
+ }
205
+
206
+ };
207
+
208
+ if (utils.isObject(formData)) {
209
+ const formObject = formData;
210
+ return Object.keys(formObject).reduce((acc, key) => {
211
+ return { ...acc,
212
+ [key]: this.createErrorHandler(formObject[key])
213
+ };
214
+ }, handler);
215
+ }
216
+
217
+ if (Array.isArray(formData)) {
218
+ return formData.reduce((acc, value, key) => {
219
+ return { ...acc,
220
+ [key]: this.createErrorHandler(value)
221
+ };
222
+ }, handler);
223
+ }
224
+
225
+ return handler;
226
+ }
227
+ /** Unwraps the `errorHandler` structure into the associated `ErrorSchema`, stripping the `addError` functions from it
228
+ *
229
+ * @param errorHandler - The `FormValidation` error handling structure
230
+ * @private
231
+ */
232
+
233
+
234
+ unwrapErrorHandler(errorHandler) {
235
+ return Object.keys(errorHandler).reduce((acc, key) => {
236
+ if (key === "addError") {
237
+ return acc;
238
+ } else if (key === utils.ERRORS_KEY) {
239
+ return { ...acc,
240
+ [key]: errorHandler[key]
241
+ };
242
+ }
243
+
244
+ return { ...acc,
245
+ [key]: this.unwrapErrorHandler(errorHandler[key])
246
+ };
247
+ }, {});
248
+ }
249
+ /** Transforming the error output from ajv to format used by @rjsf/utils.
250
+ * At some point, components should be updated to support ajv.
251
+ *
252
+ * @param errors - The list of AJV errors to convert to `RJSFValidationErrors`
253
+ * @private
254
+ */
255
+
256
+
257
+ transformRJSFValidationErrors(errors) {
258
+ if (errors === void 0) {
259
+ errors = [];
260
+ }
261
+
262
+ if (errors === null) {
263
+ return [];
264
+ }
265
+
266
+ return errors.map(e => {
267
+ const {
268
+ instancePath,
269
+ keyword,
270
+ message,
271
+ params,
272
+ schemaPath
273
+ } = e;
274
+ const property = instancePath.replace(/\//g, "."); // put data in expected format
275
+
276
+ return {
277
+ name: keyword,
278
+ property,
279
+ message,
280
+ params,
281
+ stack: (property + " " + message).trim(),
282
+ schemaPath
283
+ };
284
+ });
285
+ }
286
+ /** This function processes the `formData` with an optional user contributed `customValidate` function, which receives
287
+ * the form data and a `errorHandler` function that will be used to add custom validation errors for each field. Also
288
+ * supports a `transformErrors` function that will take the raw AJV validation errors, prior to custom validation and
289
+ * transform them in what ever way it chooses.
290
+ *
291
+ * @param formData - The form data to validate
292
+ * @param schema - The schema against which to validate the form data
293
+ * @param [customValidate] - An optional function that is used to perform custom validation
294
+ * @param [transformErrors] - An optional function that is used to transform errors after AJV validation
295
+ */
296
+
297
+
298
+ validateFormData(formData, schema, customValidate, transformErrors) {
299
+ // Include form data with undefined values, which is required for validation.
300
+ const rootSchema = schema;
301
+ const newFormData = utils.getDefaultFormState(this, schema, formData, rootSchema, true);
302
+ let validationError = null;
303
+
304
+ try {
305
+ this.ajv.validate(schema, newFormData);
306
+ } catch (err) {
307
+ validationError = err;
308
+ }
309
+
310
+ let errors = this.transformRJSFValidationErrors(this.ajv.errors); // Clear errors to prevent persistent errors, see #1104
311
+
312
+ this.ajv.errors = null;
313
+ const noProperMetaSchema = validationError && validationError.message && typeof validationError.message === "string" && validationError.message.includes("no schema with key or ref ");
314
+
315
+ if (noProperMetaSchema) {
316
+ errors = [...errors, {
317
+ stack: validationError.message
318
+ }];
319
+ }
320
+
321
+ if (typeof transformErrors === "function") {
322
+ errors = transformErrors(errors);
323
+ }
324
+
325
+ let errorSchema = this.toErrorSchema(errors);
326
+
327
+ if (noProperMetaSchema) {
328
+ errorSchema = { ...errorSchema,
329
+ ...{
330
+ $schema: {
331
+ __errors: [validationError.message]
332
+ }
333
+ }
334
+ };
335
+ }
336
+
337
+ if (typeof customValidate !== "function") {
338
+ return {
339
+ errors,
340
+ errorSchema
341
+ };
342
+ }
343
+
344
+ const errorHandler = customValidate(newFormData, this.createErrorHandler(newFormData));
345
+ const userErrorSchema = this.unwrapErrorHandler(errorHandler);
346
+ return utils.mergeValidationData(this, {
347
+ errors,
348
+ errorSchema
349
+ }, userErrorSchema);
350
+ }
351
+ /** Takes a `node` object and transforms any contained `$ref` node variables with a prefix, recursively calling
352
+ * `withIdRefPrefix` for any other elements.
353
+ *
354
+ * @param node - The object node to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it
355
+ * @private
356
+ */
357
+
358
+
359
+ withIdRefPrefixObject(node) {
360
+ for (const key in node) {
361
+ const realObj = node;
362
+ const value = realObj[key];
363
+
364
+ if (key === utils.REF_KEY && typeof value === "string" && value.startsWith("#")) {
365
+ realObj[key] = ROOT_SCHEMA_PREFIX + value;
366
+ } else {
367
+ realObj[key] = this.withIdRefPrefix(value);
368
+ }
369
+ }
370
+
371
+ return node;
372
+ }
373
+ /** Takes a `node` object list and transforms any contained `$ref` node variables with a prefix, recursively calling
374
+ * `withIdRefPrefix` for any other elements.
375
+ *
376
+ * @param nodeThe - list of object nodes to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it
377
+ * @private
378
+ */
379
+
380
+
381
+ withIdRefPrefixArray(node) {
382
+ for (let i = 0; i < node.length; i++) {
383
+ node[i] = this.withIdRefPrefix(node[i]);
384
+ }
385
+
386
+ return node;
387
+ }
388
+ /** Validates data against a schema, returning true if the data is valid, or
389
+ * false otherwise. If the schema is invalid, then this function will return
390
+ * false.
391
+ *
392
+ * @param schema - The schema against which to validate the form data * @param schema
393
+ * @param formData- - The form data to validate
394
+ * @param rootSchema - The root schema used to provide $ref resolutions
395
+ */
396
+
397
+
398
+ isValid(schema, formData, rootSchema) {
399
+ try {
400
+ // add the rootSchema ROOT_SCHEMA_PREFIX as id.
401
+ // then rewrite the schema ref's to point to the rootSchema
402
+ // this accounts for the case where schema have references to models
403
+ // that lives in the rootSchema but not in the schema in question.
404
+ const result = this.ajv.addSchema(rootSchema, ROOT_SCHEMA_PREFIX).validate(this.withIdRefPrefix(schema), formData);
405
+ return result;
406
+ } catch (e) {
407
+ return false;
408
+ } finally {
409
+ // make sure we remove the rootSchema from the global ajv instance
410
+ this.ajv.removeSchema(ROOT_SCHEMA_PREFIX);
411
+ }
412
+ }
413
+ /** Recursively prefixes all $ref's in a schema with `ROOT_SCHEMA_PREFIX`
414
+ * This is used in isValid to make references to the rootSchema
415
+ *
416
+ * @param schemaNode - The object node to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it
417
+ * @protected
418
+ */
419
+
420
+
421
+ withIdRefPrefix(schemaNode) {
422
+ if (schemaNode.constructor === Object) {
423
+ return this.withIdRefPrefixObject({ ...schemaNode
424
+ });
425
+ }
426
+
427
+ if (Array.isArray(schemaNode)) {
428
+ return this.withIdRefPrefixArray([...schemaNode]);
429
+ }
430
+
431
+ return schemaNode;
432
+ }
433
+
434
+ }
435
+
436
+ /** Creates and returns a customized implementation of the `ValidatorType` with the given customization `options` if
437
+ * provided.
438
+ *
439
+ * @param [options={}] - The `CustomValidatorOptionsType` options that are used to create the `ValidatorType` instance
440
+ */
441
+
442
+ function customizeValidator(options) {
443
+ if (options === void 0) {
444
+ options = {};
445
+ }
446
+
447
+ return new AJV8Validator(options);
448
+ }
449
+
450
+ var index = /*#__PURE__*/customizeValidator();
451
+
452
+ exports.customizeValidator = customizeValidator;
453
+ exports["default"] = index;
454
+
455
+ Object.defineProperty(exports, '__esModule', { value: true });
456
+
457
+ }));
458
+ //# sourceMappingURL=validator-ajv8.umd.development.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validator-ajv8.umd.development.js","sources":["../src/createAjvInstance.ts","../src/validator.ts","../src/customizeValidator.ts","../src/index.ts"],"sourcesContent":["import Ajv, { Options } from \"ajv\";\nimport addFormats, { FormatsPluginOptions } from \"ajv-formats\";\nimport isObject from \"lodash/isObject\";\n\nimport { CustomValidatorOptionsType } from \"./types\";\n\nexport const AJV_CONFIG: Options = {\n allErrors: true,\n multipleOfPrecision: 8,\n} as const;\nexport const COLOR_FORMAT_REGEX =\n /^(#?([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*\\)))$/;\nexport const DATA_URL_FORMAT_REGEX =\n /^data:([a-z]+\\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;\n\n/** Creates an Ajv version 8 implementation object with standard support for the 'color` and `data-url` custom formats.\n * If `additionalMetaSchemas` are provided then the Ajv instance is modified to add each of the meta schemas in the\n * list. If `customFormats` are provided then those additional formats are added to the list of supported formats. If\n * `ajvOptionsOverrides` are provided then they are spread on top of the default `AJV_CONFIG` options when constructing\n * the `Ajv` instance. With Ajv v8, the JSON Schema formats are not provided by default, but can be plugged in. By\n * default, all formats from the `ajv-formats` library are added. To disable this capability, set the `ajvFormatOptions`\n * parameter to `false`. Additionally, you can configure the `ajv-formats` by providing a custom set of\n * [format options](https://github.com/ajv-validator/ajv-formats) to the `ajvFormatOptions` parameter.\n *\n * @param [additionalMetaSchemas] - The list of additional meta schemas that the validator can access\n * @param [customFormats] - The set of additional custom formats that the validator will support\n * @param [ajvOptionsOverrides={}] - The set of validator config override options\n * @param [ajvFormatOptions] - The `ajv-format` options to use when adding formats to `ajv`; pass `false` to disable it\n */\nexport default function createAjvInstance(\n additionalMetaSchemas?: CustomValidatorOptionsType[\"additionalMetaSchemas\"],\n customFormats?: CustomValidatorOptionsType[\"customFormats\"],\n ajvOptionsOverrides: CustomValidatorOptionsType[\"ajvOptionsOverrides\"] = {},\n ajvFormatOptions?: FormatsPluginOptions | false\n) {\n const ajv = new Ajv({ ...AJV_CONFIG, ...ajvOptionsOverrides });\n if (typeof ajvFormatOptions !== \"boolean\") {\n addFormats(ajv, ajvFormatOptions);\n }\n\n // add custom formats\n ajv.addFormat(\"data-url\", DATA_URL_FORMAT_REGEX);\n ajv.addFormat(\"color\", COLOR_FORMAT_REGEX);\n\n // add more schemas to validate against\n if (Array.isArray(additionalMetaSchemas)) {\n ajv.addMetaSchema(additionalMetaSchemas);\n }\n\n // add more custom formats to validate against\n if (isObject(customFormats)) {\n Object.keys(customFormats).forEach((formatName) => {\n ajv.addFormat(formatName, customFormats[formatName]);\n });\n }\n\n return ajv;\n}\n","import Ajv, { ErrorObject } from \"ajv\";\nimport toPath from \"lodash/toPath\";\nimport {\n CustomValidator,\n ErrorSchema,\n ErrorTransformer,\n FieldValidation,\n FormValidation,\n GenericObjectType,\n RJSFSchema,\n RJSFValidationError,\n ValidationData,\n ValidatorType,\n getDefaultFormState,\n isObject,\n mergeValidationData,\n ERRORS_KEY,\n REF_KEY,\n} from \"@rjsf/utils\";\n\nimport { CustomValidatorOptionsType } from \"./types\";\nimport createAjvInstance from \"./createAjvInstance\";\n\nconst ROOT_SCHEMA_PREFIX = \"__rjsf_rootSchema\";\n\n/** `ValidatorType` implementation that uses the AJV 8 validation mechanism.\n */\nexport default class AJV8Validator<T = any> implements ValidatorType<T> {\n /** The AJV instance to use for all validations\n *\n * @private\n */\n private ajv: Ajv;\n\n /** Constructs an `AJV8Validator` instance using the `options`\n *\n * @param options - The `CustomValidatorOptionsType` options that are used to create the AJV instance\n */\n constructor(options: CustomValidatorOptionsType) {\n const {\n additionalMetaSchemas,\n customFormats,\n ajvOptionsOverrides,\n ajvFormatOptions,\n } = options;\n this.ajv = createAjvInstance(\n additionalMetaSchemas,\n customFormats,\n ajvOptionsOverrides,\n ajvFormatOptions\n );\n }\n\n /** Transforms a ajv validation errors list:\n * [\n * {property: '.level1.level2[2].level3', message: 'err a'},\n * {property: '.level1.level2[2].level3', message: 'err b'},\n * {property: '.level1.level2[4].level3', message: 'err b'},\n * ]\n * Into an error tree:\n * {\n * level1: {\n * level2: {\n * 2: {level3: {errors: ['err a', 'err b']}},\n * 4: {level3: {errors: ['err b']}},\n * }\n * }\n * };\n *\n * @param errors - The list of RJSFValidationError objects\n * @private\n */\n private toErrorSchema(errors: RJSFValidationError[]): ErrorSchema<T> {\n if (!errors.length) {\n return {} as ErrorSchema<T>;\n }\n return errors.reduce(\n (errorSchema: ErrorSchema<T>, error): ErrorSchema<T> => {\n const { property, message } = error;\n const path = toPath(property);\n let parent: GenericObjectType = errorSchema;\n\n // If the property is at the root (.level1) then toPath creates\n // an empty array element at the first index. Remove it.\n if (path.length > 0 && path[0] === \"\") {\n path.splice(0, 1);\n }\n\n for (const segment of path.slice(0)) {\n if (!(segment in parent)) {\n parent[segment] = {};\n }\n parent = parent[segment];\n }\n\n if (Array.isArray(parent.__errors)) {\n // We store the list of errors for this node in a property named __errors\n // to avoid name collision with a possible sub schema field named\n // 'errors' (see `validate.createErrorHandler`).\n parent.__errors = parent.__errors.concat(message!);\n } else {\n if (message) {\n parent.__errors = [message];\n }\n }\n return errorSchema;\n },\n {} as ErrorSchema<T>\n );\n }\n\n /** Converts an `errorSchema` into a list of `RJSFValidationErrors`\n *\n * @param errorSchema - The `ErrorSchema` instance to convert\n * @param [fieldPath=[]] - The current field path, defaults to [] if not specified\n */\n toErrorList(errorSchema?: ErrorSchema<T>, fieldPath: string[] = []) {\n if (!errorSchema) {\n return [];\n }\n let errorList: RJSFValidationError[] = [];\n if (ERRORS_KEY in errorSchema) {\n errorList = errorList.concat(\n errorSchema.__errors!.map((message: string) => {\n const property = `.${fieldPath.join(\".\")}`;\n return {\n property,\n message,\n stack: `${property} ${message}`,\n };\n })\n );\n }\n return Object.keys(errorSchema).reduce((acc, key) => {\n if (key !== ERRORS_KEY) {\n acc = acc.concat(\n this.toErrorList((errorSchema as GenericObjectType)[key], [\n ...fieldPath,\n key,\n ])\n );\n }\n return acc;\n }, errorList);\n }\n\n /** Given a `formData` object, recursively creates a `FormValidation` error handling structure around it\n *\n * @param formData - The form data around which the error handler is created\n * @private\n */\n private createErrorHandler(formData: T): FormValidation<T> {\n const handler: FieldValidation = {\n // We store the list of errors for this node in a property named __errors\n // to avoid name collision with a possible sub schema field named\n // 'errors' (see `utils.toErrorSchema`).\n __errors: [],\n addError(message: string) {\n this.__errors!.push(message);\n },\n };\n if (isObject(formData)) {\n const formObject: GenericObjectType = formData as GenericObjectType;\n return Object.keys(formObject).reduce((acc, key) => {\n return { ...acc, [key]: this.createErrorHandler(formObject[key]) };\n }, handler as FormValidation<T>);\n }\n if (Array.isArray(formData)) {\n return formData.reduce((acc, value, key) => {\n return { ...acc, [key]: this.createErrorHandler(value) };\n }, handler);\n }\n return handler as FormValidation<T>;\n }\n\n /** Unwraps the `errorHandler` structure into the associated `ErrorSchema`, stripping the `addError` functions from it\n *\n * @param errorHandler - The `FormValidation` error handling structure\n * @private\n */\n private unwrapErrorHandler(errorHandler: FormValidation<T>): ErrorSchema<T> {\n return Object.keys(errorHandler).reduce((acc, key) => {\n if (key === \"addError\") {\n return acc;\n } else if (key === ERRORS_KEY) {\n return { ...acc, [key]: (errorHandler as GenericObjectType)[key] };\n }\n return {\n ...acc,\n [key]: this.unwrapErrorHandler(\n (errorHandler as GenericObjectType)[key]\n ),\n };\n }, {} as ErrorSchema<T>);\n }\n\n /** Transforming the error output from ajv to format used by @rjsf/utils.\n * At some point, components should be updated to support ajv.\n *\n * @param errors - The list of AJV errors to convert to `RJSFValidationErrors`\n * @private\n */\n private transformRJSFValidationErrors(\n errors: Ajv[\"errors\"] = []\n ): RJSFValidationError[] {\n if (errors === null) {\n return [];\n }\n\n return errors.map((e: ErrorObject) => {\n const { instancePath, keyword, message, params, schemaPath } = e;\n const property = instancePath.replace(/\\//g, \".\");\n\n // put data in expected format\n return {\n name: keyword,\n property,\n message,\n params, // specific to ajv\n stack: `${property} ${message}`.trim(),\n schemaPath,\n };\n });\n }\n\n /** This function processes the `formData` with an optional user contributed `customValidate` function, which receives\n * the form data and a `errorHandler` function that will be used to add custom validation errors for each field. Also\n * supports a `transformErrors` function that will take the raw AJV validation errors, prior to custom validation and\n * transform them in what ever way it chooses.\n *\n * @param formData - The form data to validate\n * @param schema - The schema against which to validate the form data\n * @param [customValidate] - An optional function that is used to perform custom validation\n * @param [transformErrors] - An optional function that is used to transform errors after AJV validation\n */\n validateFormData(\n formData: T,\n schema: RJSFSchema,\n customValidate?: CustomValidator<T>,\n transformErrors?: ErrorTransformer\n ): ValidationData<T> {\n // Include form data with undefined values, which is required for validation.\n const rootSchema = schema;\n const newFormData = getDefaultFormState<T>(\n this,\n schema,\n formData,\n rootSchema,\n true\n ) as T;\n\n let validationError: Error | null = null;\n try {\n this.ajv.validate(schema, newFormData);\n } catch (err) {\n validationError = err as Error;\n }\n\n let errors = this.transformRJSFValidationErrors(this.ajv.errors);\n // Clear errors to prevent persistent errors, see #1104\n\n this.ajv.errors = null;\n\n const noProperMetaSchema =\n validationError &&\n validationError.message &&\n typeof validationError.message === \"string\" &&\n validationError.message.includes(\"no schema with key or ref \");\n\n if (noProperMetaSchema) {\n errors = [...errors, { stack: validationError!.message }];\n }\n if (typeof transformErrors === \"function\") {\n errors = transformErrors(errors);\n }\n\n let errorSchema = this.toErrorSchema(errors);\n\n if (noProperMetaSchema) {\n errorSchema = {\n ...errorSchema,\n ...{\n $schema: {\n __errors: [validationError!.message],\n },\n },\n };\n }\n\n if (typeof customValidate !== \"function\") {\n return { errors, errorSchema };\n }\n\n const errorHandler = customValidate(\n newFormData,\n this.createErrorHandler(newFormData)\n );\n const userErrorSchema = this.unwrapErrorHandler(errorHandler);\n return mergeValidationData<T>(\n this,\n { errors, errorSchema },\n userErrorSchema\n );\n }\n\n /** Takes a `node` object and transforms any contained `$ref` node variables with a prefix, recursively calling\n * `withIdRefPrefix` for any other elements.\n *\n * @param node - The object node to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it\n * @private\n */\n private withIdRefPrefixObject(node: object) {\n for (const key in node) {\n const realObj: { [k: string]: any } = node;\n const value = realObj[key];\n if (\n key === REF_KEY &&\n typeof value === \"string\" &&\n value.startsWith(\"#\")\n ) {\n realObj[key] = ROOT_SCHEMA_PREFIX + value;\n } else {\n realObj[key] = this.withIdRefPrefix(value);\n }\n }\n return node;\n }\n\n /** Takes a `node` object list and transforms any contained `$ref` node variables with a prefix, recursively calling\n * `withIdRefPrefix` for any other elements.\n *\n * @param nodeThe - list of object nodes to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it\n * @private\n */\n private withIdRefPrefixArray(node: object[]): RJSFSchema {\n for (let i = 0; i < node.length; i++) {\n node[i] = this.withIdRefPrefix(node[i]);\n }\n return node as RJSFSchema;\n }\n\n /** Validates data against a schema, returning true if the data is valid, or\n * false otherwise. If the schema is invalid, then this function will return\n * false.\n *\n * @param schema - The schema against which to validate the form data * @param schema\n * @param formData- - The form data to validate\n * @param rootSchema - The root schema used to provide $ref resolutions\n */\n isValid(schema: RJSFSchema, formData: T, rootSchema: RJSFSchema) {\n try {\n // add the rootSchema ROOT_SCHEMA_PREFIX as id.\n // then rewrite the schema ref's to point to the rootSchema\n // this accounts for the case where schema have references to models\n // that lives in the rootSchema but not in the schema in question.\n const result = this.ajv\n .addSchema(rootSchema, ROOT_SCHEMA_PREFIX)\n .validate(this.withIdRefPrefix(schema), formData);\n return result as boolean;\n } catch (e) {\n return false;\n } finally {\n // make sure we remove the rootSchema from the global ajv instance\n this.ajv.removeSchema(ROOT_SCHEMA_PREFIX);\n }\n }\n\n /** Recursively prefixes all $ref's in a schema with `ROOT_SCHEMA_PREFIX`\n * This is used in isValid to make references to the rootSchema\n *\n * @param schemaNode - The object node to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it\n * @protected\n */\n protected withIdRefPrefix(schemaNode: RJSFSchema): RJSFSchema {\n if (schemaNode.constructor === Object) {\n return this.withIdRefPrefixObject({ ...schemaNode });\n }\n if (Array.isArray(schemaNode)) {\n return this.withIdRefPrefixArray([...schemaNode]);\n }\n return schemaNode;\n }\n}\n","import { ValidatorType } from \"@rjsf/utils\";\n\nimport { CustomValidatorOptionsType } from \"./types\";\nimport AJV8Validator from \"./validator\";\n\n/** Creates and returns a customized implementation of the `ValidatorType` with the given customization `options` if\n * provided.\n *\n * @param [options={}] - The `CustomValidatorOptionsType` options that are used to create the `ValidatorType` instance\n */\nexport default function customizeValidator<T = any>(\n options: CustomValidatorOptionsType = {}\n): ValidatorType<T> {\n return new AJV8Validator<T>(options);\n}\n","import customizeValidator from \"./customizeValidator\";\n\nexport { customizeValidator };\nexport * from \"./types\";\n\nexport default customizeValidator();\n"],"names":["AJV_CONFIG","allErrors","multipleOfPrecision","COLOR_FORMAT_REGEX","DATA_URL_FORMAT_REGEX","createAjvInstance","additionalMetaSchemas","customFormats","ajvOptionsOverrides","ajvFormatOptions","ajv","Ajv","addFormats","addFormat","Array","isArray","addMetaSchema","isObject","Object","keys","forEach","formatName","ROOT_SCHEMA_PREFIX","AJV8Validator","constructor","options","toErrorSchema","errors","length","reduce","errorSchema","error","property","message","path","toPath","parent","splice","segment","slice","__errors","concat","toErrorList","fieldPath","errorList","ERRORS_KEY","map","join","stack","acc","key","createErrorHandler","formData","handler","addError","push","formObject","value","unwrapErrorHandler","errorHandler","transformRJSFValidationErrors","e","instancePath","keyword","params","schemaPath","replace","name","trim","validateFormData","schema","customValidate","transformErrors","rootSchema","newFormData","getDefaultFormState","validationError","validate","err","noProperMetaSchema","includes","$schema","userErrorSchema","mergeValidationData","withIdRefPrefixObject","node","realObj","REF_KEY","startsWith","withIdRefPrefix","withIdRefPrefixArray","i","isValid","result","addSchema","removeSchema","schemaNode","customizeValidator"],"mappings":";;;;;;;;;;;;;EAMO,MAAMA,UAAU,GAAY;EACjCC,EAAAA,SAAS,EAAE,IADsB;EAEjCC,EAAAA,mBAAmB,EAAE,CAAA;EAFY,CAA5B,CAAA;EAIA,MAAMC,kBAAkB,GAC7B,4YADK,CAAA;EAEA,MAAMC,qBAAqB,GAChC,2DADK,CAAA;EAGP;;;;;;;;;;;;;EAaG;;EACqB,SAAAC,iBAAA,CACtBC,qBADsB,EAEtBC,aAFsB,EAGtBC,mBAHsB,EAItBC,gBAJsB,EAIyB;EAAA,EAAA,IAD/CD,mBAC+C,KAAA,KAAA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xCA,OAAwC,KAAA,KAAA,CAAA,EAAA;EAAxCA,IAAAA,OAAwC,GAAF,EAAE,CAAA;EAAA,GAAA;;EAExC,EAAA,OAAO,IAAIF,aAAJ,CAAqBE,OAArB,CAAP,CAAA;EACD;;ACTD,cAAA,aAAewE,kBAAkB,EAAjC;;;;;;;;;;;"}
@@ -0,0 +1,2 @@
1
+ !function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("lodash-es/toPath"),require("@rjsf/utils"),require("ajv"),require("ajv-formats"),require("lodash-es/isObject")):"function"==typeof define&&define.amd?define(["exports","lodash-es/toPath","@rjsf/utils","ajv","ajv-formats","lodash-es/isObject"],e):e((r="undefined"!=typeof globalThis?globalThis:r||self)["@rjsf/validator-ajv8"]={},r.toPath,r.utils,r.Ajv,r.addFormats,r.isObject)}(this,(function(r,e,t,a,s,o){"use strict";function i(r){return r&&"object"==typeof r&&"default"in r?r:{default:r}}var n=i(e),c=i(a),d=i(s),l=i(o);const u={allErrors:!0,multipleOfPrecision:8},f=/^(#?([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*\)))$/,h=/^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/,m="__rjsf_rootSchema";class y{constructor(r){this.ajv=void 0;const{additionalMetaSchemas:e,customFormats:t,ajvOptionsOverrides:a,ajvFormatOptions:s}=r;this.ajv=function(r,e,t,a){void 0===t&&(t={});const s=new c.default({...u,...t});return"boolean"!=typeof a&&d.default(s,a),s.addFormat("data-url",h),s.addFormat("color",f),Array.isArray(r)&&s.addMetaSchema(r),l.default(e)&&Object.keys(e).forEach((r=>{s.addFormat(r,e[r])})),s}(e,t,a,s)}toErrorSchema(r){return r.length?r.reduce(((r,e)=>{const{property:t,message:a}=e,s=n.default(t);let o=r;s.length>0&&""===s[0]&&s.splice(0,1);for(const r of s.slice(0))r in o||(o[r]={}),o=o[r];return Array.isArray(o.__errors)?o.__errors=o.__errors.concat(a):a&&(o.__errors=[a]),r}),{}):{}}toErrorList(r,e){if(void 0===e&&(e=[]),!r)return[];let a=[];return t.ERRORS_KEY in r&&(a=a.concat(r.__errors.map((r=>{const t="."+e.join(".");return{property:t,message:r,stack:t+" "+r}})))),Object.keys(r).reduce(((a,s)=>(s!==t.ERRORS_KEY&&(a=a.concat(this.toErrorList(r[s],[...e,s]))),a)),a)}createErrorHandler(r){const e={__errors:[],addError(r){this.__errors.push(r)}};if(t.isObject(r)){const t=r;return Object.keys(t).reduce(((r,e)=>({...r,[e]:this.createErrorHandler(t[e])})),e)}return Array.isArray(r)?r.reduce(((r,e,t)=>({...r,[t]:this.createErrorHandler(e)})),e):e}unwrapErrorHandler(r){return Object.keys(r).reduce(((e,a)=>"addError"===a?e:a===t.ERRORS_KEY?{...e,[a]:r[a]}:{...e,[a]:this.unwrapErrorHandler(r[a])}),{})}transformRJSFValidationErrors(r){return void 0===r&&(r=[]),null===r?[]:r.map((r=>{const{instancePath:e,keyword:t,message:a,params:s,schemaPath:o}=r,i=e.replace(/\//g,".");return{name:t,property:i,message:a,params:s,stack:(i+" "+a).trim(),schemaPath:o}}))}validateFormData(r,e,a,s){const o=t.getDefaultFormState(this,e,r,e,!0);let i=null;try{this.ajv.validate(e,o)}catch(r){i=r}let n=this.transformRJSFValidationErrors(this.ajv.errors);this.ajv.errors=null;const c=i&&i.message&&"string"==typeof i.message&&i.message.includes("no schema with key or ref ");c&&(n=[...n,{stack:i.message}]),"function"==typeof s&&(n=s(n));let d=this.toErrorSchema(n);if(c&&(d={...d,$schema:{__errors:[i.message]}}),"function"!=typeof a)return{errors:n,errorSchema:d};const l=a(o,this.createErrorHandler(o)),u=this.unwrapErrorHandler(l);return t.mergeValidationData(this,{errors:n,errorSchema:d},u)}withIdRefPrefixObject(r){for(const e in r){const a=r[e];r[e]=e===t.REF_KEY&&"string"==typeof a&&a.startsWith("#")?m+a:this.withIdRefPrefix(a)}return r}withIdRefPrefixArray(r){for(let e=0;e<r.length;e++)r[e]=this.withIdRefPrefix(r[e]);return r}isValid(r,e,t){try{return this.ajv.addSchema(t,m).validate(this.withIdRefPrefix(r),e)}catch(r){return!1}finally{this.ajv.removeSchema(m)}}withIdRefPrefix(r){return r.constructor===Object?this.withIdRefPrefixObject({...r}):Array.isArray(r)?this.withIdRefPrefixArray([...r]):r}}function p(r){return void 0===r&&(r={}),new y(r)}var j=p();r.customizeValidator=p,r.default=j,Object.defineProperty(r,"__esModule",{value:!0})}));
2
+ //# sourceMappingURL=validator-ajv8.umd.production.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validator-ajv8.umd.production.min.js","sources":["../src/createAjvInstance.ts","../src/validator.ts","../src/customizeValidator.ts","../src/index.ts"],"sourcesContent":["import Ajv, { Options } from \"ajv\";\nimport addFormats, { FormatsPluginOptions } from \"ajv-formats\";\nimport isObject from \"lodash/isObject\";\n\nimport { CustomValidatorOptionsType } from \"./types\";\n\nexport const AJV_CONFIG: Options = {\n allErrors: true,\n multipleOfPrecision: 8,\n} as const;\nexport const COLOR_FORMAT_REGEX =\n /^(#?([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*\\)))$/;\nexport const DATA_URL_FORMAT_REGEX =\n /^data:([a-z]+\\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;\n\n/** Creates an Ajv version 8 implementation object with standard support for the 'color` and `data-url` custom formats.\n * If `additionalMetaSchemas` are provided then the Ajv instance is modified to add each of the meta schemas in the\n * list. If `customFormats` are provided then those additional formats are added to the list of supported formats. If\n * `ajvOptionsOverrides` are provided then they are spread on top of the default `AJV_CONFIG` options when constructing\n * the `Ajv` instance. With Ajv v8, the JSON Schema formats are not provided by default, but can be plugged in. By\n * default, all formats from the `ajv-formats` library are added. To disable this capability, set the `ajvFormatOptions`\n * parameter to `false`. Additionally, you can configure the `ajv-formats` by providing a custom set of\n * [format options](https://github.com/ajv-validator/ajv-formats) to the `ajvFormatOptions` parameter.\n *\n * @param [additionalMetaSchemas] - The list of additional meta schemas that the validator can access\n * @param [customFormats] - The set of additional custom formats that the validator will support\n * @param [ajvOptionsOverrides={}] - The set of validator config override options\n * @param [ajvFormatOptions] - The `ajv-format` options to use when adding formats to `ajv`; pass `false` to disable it\n */\nexport default function createAjvInstance(\n additionalMetaSchemas?: CustomValidatorOptionsType[\"additionalMetaSchemas\"],\n customFormats?: CustomValidatorOptionsType[\"customFormats\"],\n ajvOptionsOverrides: CustomValidatorOptionsType[\"ajvOptionsOverrides\"] = {},\n ajvFormatOptions?: FormatsPluginOptions | false\n) {\n const ajv = new Ajv({ ...AJV_CONFIG, ...ajvOptionsOverrides });\n if (typeof ajvFormatOptions !== \"boolean\") {\n addFormats(ajv, ajvFormatOptions);\n }\n\n // add custom formats\n ajv.addFormat(\"data-url\", DATA_URL_FORMAT_REGEX);\n ajv.addFormat(\"color\", COLOR_FORMAT_REGEX);\n\n // add more schemas to validate against\n if (Array.isArray(additionalMetaSchemas)) {\n ajv.addMetaSchema(additionalMetaSchemas);\n }\n\n // add more custom formats to validate against\n if (isObject(customFormats)) {\n Object.keys(customFormats).forEach((formatName) => {\n ajv.addFormat(formatName, customFormats[formatName]);\n });\n }\n\n return ajv;\n}\n","import Ajv, { ErrorObject } from \"ajv\";\nimport toPath from \"lodash/toPath\";\nimport {\n CustomValidator,\n ErrorSchema,\n ErrorTransformer,\n FieldValidation,\n FormValidation,\n GenericObjectType,\n RJSFSchema,\n RJSFValidationError,\n ValidationData,\n ValidatorType,\n getDefaultFormState,\n isObject,\n mergeValidationData,\n ERRORS_KEY,\n REF_KEY,\n} from \"@rjsf/utils\";\n\nimport { CustomValidatorOptionsType } from \"./types\";\nimport createAjvInstance from \"./createAjvInstance\";\n\nconst ROOT_SCHEMA_PREFIX = \"__rjsf_rootSchema\";\n\n/** `ValidatorType` implementation that uses the AJV 8 validation mechanism.\n */\nexport default class AJV8Validator<T = any> implements ValidatorType<T> {\n /** The AJV instance to use for all validations\n *\n * @private\n */\n private ajv: Ajv;\n\n /** Constructs an `AJV8Validator` instance using the `options`\n *\n * @param options - The `CustomValidatorOptionsType` options that are used to create the AJV instance\n */\n constructor(options: CustomValidatorOptionsType) {\n const {\n additionalMetaSchemas,\n customFormats,\n ajvOptionsOverrides,\n ajvFormatOptions,\n } = options;\n this.ajv = createAjvInstance(\n additionalMetaSchemas,\n customFormats,\n ajvOptionsOverrides,\n ajvFormatOptions\n );\n }\n\n /** Transforms a ajv validation errors list:\n * [\n * {property: '.level1.level2[2].level3', message: 'err a'},\n * {property: '.level1.level2[2].level3', message: 'err b'},\n * {property: '.level1.level2[4].level3', message: 'err b'},\n * ]\n * Into an error tree:\n * {\n * level1: {\n * level2: {\n * 2: {level3: {errors: ['err a', 'err b']}},\n * 4: {level3: {errors: ['err b']}},\n * }\n * }\n * };\n *\n * @param errors - The list of RJSFValidationError objects\n * @private\n */\n private toErrorSchema(errors: RJSFValidationError[]): ErrorSchema<T> {\n if (!errors.length) {\n return {} as ErrorSchema<T>;\n }\n return errors.reduce(\n (errorSchema: ErrorSchema<T>, error): ErrorSchema<T> => {\n const { property, message } = error;\n const path = toPath(property);\n let parent: GenericObjectType = errorSchema;\n\n // If the property is at the root (.level1) then toPath creates\n // an empty array element at the first index. Remove it.\n if (path.length > 0 && path[0] === \"\") {\n path.splice(0, 1);\n }\n\n for (const segment of path.slice(0)) {\n if (!(segment in parent)) {\n parent[segment] = {};\n }\n parent = parent[segment];\n }\n\n if (Array.isArray(parent.__errors)) {\n // We store the list of errors for this node in a property named __errors\n // to avoid name collision with a possible sub schema field named\n // 'errors' (see `validate.createErrorHandler`).\n parent.__errors = parent.__errors.concat(message!);\n } else {\n if (message) {\n parent.__errors = [message];\n }\n }\n return errorSchema;\n },\n {} as ErrorSchema<T>\n );\n }\n\n /** Converts an `errorSchema` into a list of `RJSFValidationErrors`\n *\n * @param errorSchema - The `ErrorSchema` instance to convert\n * @param [fieldPath=[]] - The current field path, defaults to [] if not specified\n */\n toErrorList(errorSchema?: ErrorSchema<T>, fieldPath: string[] = []) {\n if (!errorSchema) {\n return [];\n }\n let errorList: RJSFValidationError[] = [];\n if (ERRORS_KEY in errorSchema) {\n errorList = errorList.concat(\n errorSchema.__errors!.map((message: string) => {\n const property = `.${fieldPath.join(\".\")}`;\n return {\n property,\n message,\n stack: `${property} ${message}`,\n };\n })\n );\n }\n return Object.keys(errorSchema).reduce((acc, key) => {\n if (key !== ERRORS_KEY) {\n acc = acc.concat(\n this.toErrorList((errorSchema as GenericObjectType)[key], [\n ...fieldPath,\n key,\n ])\n );\n }\n return acc;\n }, errorList);\n }\n\n /** Given a `formData` object, recursively creates a `FormValidation` error handling structure around it\n *\n * @param formData - The form data around which the error handler is created\n * @private\n */\n private createErrorHandler(formData: T): FormValidation<T> {\n const handler: FieldValidation = {\n // We store the list of errors for this node in a property named __errors\n // to avoid name collision with a possible sub schema field named\n // 'errors' (see `utils.toErrorSchema`).\n __errors: [],\n addError(message: string) {\n this.__errors!.push(message);\n },\n };\n if (isObject(formData)) {\n const formObject: GenericObjectType = formData as GenericObjectType;\n return Object.keys(formObject).reduce((acc, key) => {\n return { ...acc, [key]: this.createErrorHandler(formObject[key]) };\n }, handler as FormValidation<T>);\n }\n if (Array.isArray(formData)) {\n return formData.reduce((acc, value, key) => {\n return { ...acc, [key]: this.createErrorHandler(value) };\n }, handler);\n }\n return handler as FormValidation<T>;\n }\n\n /** Unwraps the `errorHandler` structure into the associated `ErrorSchema`, stripping the `addError` functions from it\n *\n * @param errorHandler - The `FormValidation` error handling structure\n * @private\n */\n private unwrapErrorHandler(errorHandler: FormValidation<T>): ErrorSchema<T> {\n return Object.keys(errorHandler).reduce((acc, key) => {\n if (key === \"addError\") {\n return acc;\n } else if (key === ERRORS_KEY) {\n return { ...acc, [key]: (errorHandler as GenericObjectType)[key] };\n }\n return {\n ...acc,\n [key]: this.unwrapErrorHandler(\n (errorHandler as GenericObjectType)[key]\n ),\n };\n }, {} as ErrorSchema<T>);\n }\n\n /** Transforming the error output from ajv to format used by @rjsf/utils.\n * At some point, components should be updated to support ajv.\n *\n * @param errors - The list of AJV errors to convert to `RJSFValidationErrors`\n * @private\n */\n private transformRJSFValidationErrors(\n errors: Ajv[\"errors\"] = []\n ): RJSFValidationError[] {\n if (errors === null) {\n return [];\n }\n\n return errors.map((e: ErrorObject) => {\n const { instancePath, keyword, message, params, schemaPath } = e;\n const property = instancePath.replace(/\\//g, \".\");\n\n // put data in expected format\n return {\n name: keyword,\n property,\n message,\n params, // specific to ajv\n stack: `${property} ${message}`.trim(),\n schemaPath,\n };\n });\n }\n\n /** This function processes the `formData` with an optional user contributed `customValidate` function, which receives\n * the form data and a `errorHandler` function that will be used to add custom validation errors for each field. Also\n * supports a `transformErrors` function that will take the raw AJV validation errors, prior to custom validation and\n * transform them in what ever way it chooses.\n *\n * @param formData - The form data to validate\n * @param schema - The schema against which to validate the form data\n * @param [customValidate] - An optional function that is used to perform custom validation\n * @param [transformErrors] - An optional function that is used to transform errors after AJV validation\n */\n validateFormData(\n formData: T,\n schema: RJSFSchema,\n customValidate?: CustomValidator<T>,\n transformErrors?: ErrorTransformer\n ): ValidationData<T> {\n // Include form data with undefined values, which is required for validation.\n const rootSchema = schema;\n const newFormData = getDefaultFormState<T>(\n this,\n schema,\n formData,\n rootSchema,\n true\n ) as T;\n\n let validationError: Error | null = null;\n try {\n this.ajv.validate(schema, newFormData);\n } catch (err) {\n validationError = err as Error;\n }\n\n let errors = this.transformRJSFValidationErrors(this.ajv.errors);\n // Clear errors to prevent persistent errors, see #1104\n\n this.ajv.errors = null;\n\n const noProperMetaSchema =\n validationError &&\n validationError.message &&\n typeof validationError.message === \"string\" &&\n validationError.message.includes(\"no schema with key or ref \");\n\n if (noProperMetaSchema) {\n errors = [...errors, { stack: validationError!.message }];\n }\n if (typeof transformErrors === \"function\") {\n errors = transformErrors(errors);\n }\n\n let errorSchema = this.toErrorSchema(errors);\n\n if (noProperMetaSchema) {\n errorSchema = {\n ...errorSchema,\n ...{\n $schema: {\n __errors: [validationError!.message],\n },\n },\n };\n }\n\n if (typeof customValidate !== \"function\") {\n return { errors, errorSchema };\n }\n\n const errorHandler = customValidate(\n newFormData,\n this.createErrorHandler(newFormData)\n );\n const userErrorSchema = this.unwrapErrorHandler(errorHandler);\n return mergeValidationData<T>(\n this,\n { errors, errorSchema },\n userErrorSchema\n );\n }\n\n /** Takes a `node` object and transforms any contained `$ref` node variables with a prefix, recursively calling\n * `withIdRefPrefix` for any other elements.\n *\n * @param node - The object node to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it\n * @private\n */\n private withIdRefPrefixObject(node: object) {\n for (const key in node) {\n const realObj: { [k: string]: any } = node;\n const value = realObj[key];\n if (\n key === REF_KEY &&\n typeof value === \"string\" &&\n value.startsWith(\"#\")\n ) {\n realObj[key] = ROOT_SCHEMA_PREFIX + value;\n } else {\n realObj[key] = this.withIdRefPrefix(value);\n }\n }\n return node;\n }\n\n /** Takes a `node` object list and transforms any contained `$ref` node variables with a prefix, recursively calling\n * `withIdRefPrefix` for any other elements.\n *\n * @param nodeThe - list of object nodes to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it\n * @private\n */\n private withIdRefPrefixArray(node: object[]): RJSFSchema {\n for (let i = 0; i < node.length; i++) {\n node[i] = this.withIdRefPrefix(node[i]);\n }\n return node as RJSFSchema;\n }\n\n /** Validates data against a schema, returning true if the data is valid, or\n * false otherwise. If the schema is invalid, then this function will return\n * false.\n *\n * @param schema - The schema against which to validate the form data * @param schema\n * @param formData- - The form data to validate\n * @param rootSchema - The root schema used to provide $ref resolutions\n */\n isValid(schema: RJSFSchema, formData: T, rootSchema: RJSFSchema) {\n try {\n // add the rootSchema ROOT_SCHEMA_PREFIX as id.\n // then rewrite the schema ref's to point to the rootSchema\n // this accounts for the case where schema have references to models\n // that lives in the rootSchema but not in the schema in question.\n const result = this.ajv\n .addSchema(rootSchema, ROOT_SCHEMA_PREFIX)\n .validate(this.withIdRefPrefix(schema), formData);\n return result as boolean;\n } catch (e) {\n return false;\n } finally {\n // make sure we remove the rootSchema from the global ajv instance\n this.ajv.removeSchema(ROOT_SCHEMA_PREFIX);\n }\n }\n\n /** Recursively prefixes all $ref's in a schema with `ROOT_SCHEMA_PREFIX`\n * This is used in isValid to make references to the rootSchema\n *\n * @param schemaNode - The object node to which a ROOT_SCHEMA_PREFIX is added when a REF_KEY is part of it\n * @protected\n */\n protected withIdRefPrefix(schemaNode: RJSFSchema): RJSFSchema {\n if (schemaNode.constructor === Object) {\n return this.withIdRefPrefixObject({ ...schemaNode });\n }\n if (Array.isArray(schemaNode)) {\n return this.withIdRefPrefixArray([...schemaNode]);\n }\n return schemaNode;\n }\n}\n","import { ValidatorType } from \"@rjsf/utils\";\n\nimport { CustomValidatorOptionsType } from \"./types\";\nimport AJV8Validator from \"./validator\";\n\n/** Creates and returns a customized implementation of the `ValidatorType` with the given customization `options` if\n * provided.\n *\n * @param [options={}] - The `CustomValidatorOptionsType` options that are used to create the `ValidatorType` instance\n */\nexport default function customizeValidator<T = any>(\n options: CustomValidatorOptionsType = {}\n): ValidatorType<T> {\n return new AJV8Validator<T>(options);\n}\n","import customizeValidator from \"./customizeValidator\";\n\nexport { customizeValidator };\nexport * from \"./types\";\n\nexport default customizeValidator();\n"],"names":["AJV_CONFIG","allErrors","multipleOfPrecision","COLOR_FORMAT_REGEX","DATA_URL_FORMAT_REGEX","ROOT_SCHEMA_PREFIX","AJV8Validator","constructor","options","this","ajv","additionalMetaSchemas","customFormats","ajvOptionsOverrides","ajvFormatOptions","Ajv","addFormats","addFormat","Array","isArray","addMetaSchema","isObject","Object","keys","forEach","formatName","createAjvInstance","toErrorSchema","errors","length","reduce","errorSchema","error","property","message","path","toPath","parent","splice","segment","slice","__errors","concat","toErrorList","fieldPath","errorList","ERRORS_KEY","map","join","stack","acc","key","createErrorHandler","formData","handler","addError","push","formObject","value","unwrapErrorHandler","errorHandler","transformRJSFValidationErrors","e","instancePath","keyword","params","schemaPath","replace","name","trim","validateFormData","schema","customValidate","transformErrors","newFormData","getDefaultFormState","validationError","validate","err","noProperMetaSchema","includes","$schema","userErrorSchema","mergeValidationData","withIdRefPrefixObject","node","REF_KEY","startsWith","withIdRefPrefix","withIdRefPrefixArray","i","isValid","rootSchema","addSchema","removeSchema","schemaNode","customizeValidator","index"],"mappings":"imBAMO,MAAMA,EAAsB,CACjCC,WAAW,EACXC,oBAAqB,GAEVC,EACX,6YACWC,EACX,4DCUIC,EAAqB,oBAIb,MAAOC,EAWnBC,YAAYC,GAAmCC,KANvCC,SAMuC,EAC7C,MAAMC,sBACJA,EADIC,cAEJA,EAFIC,oBAGJA,EAHIC,iBAIJA,GACEN,EACJC,KAAKC,IDhBe,SACtBC,EACAC,EACAC,EACAC,QAA+C,IAD/CD,IAAAA,EAAyE,CAAA,GAGzE,MAAMH,EAAM,IAAIK,UAAI,IAAKf,KAAea,IAqBxC,MApBgC,kBAArBC,GACTE,UAAW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EhCA,CACR,ECnXW,SAAUC,EACtBxF,GAEA,YAFwC,IAAxCA,IAAAA,EAAsC,CAAA,GAE/B,IAAIF,EAAiBE,EAC7B,CCTD,IAAAyF,EAAeD"}
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@rjsf/validator-ajv8",
3
+ "version": "5.0.0-beta.5",
4
+ "main": "dist/index.js",
5
+ "module": "dist/validator-ajv8.esm.js",
6
+ "typings": "dist/index.d.ts",
7
+ "description": "The ajv-8 based validator for @rjsf/core",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "engineStrict": false,
12
+ "engines": {
13
+ "node": ">=14"
14
+ },
15
+ "scripts": {
16
+ "build": "rimraf dist && dts build --rollupTypes --format cjs,esm,umd",
17
+ "cs-check": "prettier -l \"{src,test}/**/*.ts?(x)\"",
18
+ "cs-format": "prettier \"{src,test}/**/*.ts?(x)\" --write",
19
+ "lint": "eslint src test",
20
+ "precommit": "lint-staged",
21
+ "test": "dts test"
22
+ },
23
+ "lint-staged": {
24
+ "{src,test}/**/*.ts?(x)": [
25
+ "eslint --fix",
26
+ "prettier --write"
27
+ ]
28
+ },
29
+ "dependencies": {
30
+ "ajv": "^8.11.0",
31
+ "ajv-formats": "^2.1.1",
32
+ "lodash": "^4.17.15",
33
+ "lodash-es": "^4.17.15"
34
+ },
35
+ "peerDependencies": {
36
+ "@rjsf/utils": "^5.0.0-beta.1"
37
+ },
38
+ "devDependencies": {
39
+ "@babel/core": "^7.18.13",
40
+ "@babel/plugin-proposal-class-properties": "^7.18.6",
41
+ "@babel/plugin-transform-modules-commonjs": "^7.18.6",
42
+ "@babel/plugin-transform-react-jsx": "^7.18.10",
43
+ "@babel/preset-env": "^7.18.10",
44
+ "@babel/preset-react": "^7.18.6",
45
+ "@rjsf/utils": "^5.0.0-beta.5",
46
+ "@types/jest-expect-message": "^1.0.3",
47
+ "@types/json-schema": "^7.0.9",
48
+ "@types/lodash": "^4.14.184",
49
+ "dts-cli": "^1.6.0",
50
+ "eslint": "^8.23.0",
51
+ "jest-expect-message": "^1.0.2",
52
+ "rimraf": "^3.0.2"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "author": "Heath Chiavettone <heath.chiavettone@freenome.com",
58
+ "contributors": [],
59
+ "keywords": [
60
+ "react-jsonschema-form",
61
+ "jsonschema",
62
+ "json-schema",
63
+ "json",
64
+ "schema",
65
+ "form",
66
+ "react",
67
+ "ajv-8",
68
+ "rjsf-validator"
69
+ ],
70
+ "repository": {
71
+ "type": "git",
72
+ "url": "git+https://github.com/rjsf-team/react-jsonschema-form.git"
73
+ },
74
+ "license": "Apache-2.0",
75
+ "gitHead": "e4c61ea6867d6089dced3227d5aa8ac40516376d"
76
+ }