Socket
Socket
Sign inDemoInstall

@rjsf/validator-ajv8

Package Overview
Dependencies
24
Maintainers
2
Versions
64
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 5.11.2 to 5.12.0

dist/compileSchemaValidators.esm.js

101

dist/compileSchemaValidators.js

@@ -0,8 +1,99 @@

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
'use strict'
// src/compileSchemaValidators.ts
var compileSchemaValidators_exports = {};
__export(compileSchemaValidators_exports, {
compileSchemaValidatorsCode: () => compileSchemaValidatorsCode,
default: () => compileSchemaValidators
});
module.exports = __toCommonJS(compileSchemaValidators_exports);
var import_fs = __toESM(require("fs"));
if (process.env.NODE_ENV === 'production') {
module.exports = require('./compileSchemaValidators.cjs.production.min.js')
} else {
module.exports = require('./compileSchemaValidators.cjs.development.js')
// src/compileSchemaValidatorsCode.ts
var import_standalone = __toESM(require("ajv/dist/standalone"));
var import_utils2 = require("@rjsf/utils");
// src/createAjvInstance.ts
var import_ajv = __toESM(require("ajv"));
var import_ajv_formats = __toESM(require("ajv-formats"));
var import_isObject = __toESM(require("lodash/isObject"));
var import_utils = require("@rjsf/utils");
var AJV_CONFIG = {
allErrors: true,
multipleOfPrecision: 8,
strict: false,
verbose: true
};
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*\)))$/;
var DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
function createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides = {}, ajvFormatOptions, AjvClass = import_ajv.default) {
const ajv = new AjvClass({ ...AJV_CONFIG, ...ajvOptionsOverrides });
if (ajvFormatOptions) {
(0, import_ajv_formats.default)(ajv, ajvFormatOptions);
} else if (ajvFormatOptions !== false) {
(0, import_ajv_formats.default)(ajv);
}
ajv.addFormat("data-url", DATA_URL_FORMAT_REGEX);
ajv.addFormat("color", COLOR_FORMAT_REGEX);
ajv.addKeyword(import_utils.ADDITIONAL_PROPERTY_FLAG);
ajv.addKeyword(import_utils.RJSF_ADDITONAL_PROPERTIES_FLAG);
if (Array.isArray(additionalMetaSchemas)) {
ajv.addMetaSchema(additionalMetaSchemas);
}
if ((0, import_isObject.default)(customFormats)) {
Object.keys(customFormats).forEach((formatName) => {
ajv.addFormat(formatName, customFormats[formatName]);
});
}
return ajv;
}
// src/compileSchemaValidatorsCode.ts
function compileSchemaValidatorsCode(schema, options = {}) {
const schemaMaps = (0, import_utils2.schemaParser)(schema);
const schemas = Object.values(schemaMaps);
const { additionalMetaSchemas, customFormats, ajvOptionsOverrides = {}, ajvFormatOptions, AjvClass } = options;
const compileOptions = {
...ajvOptionsOverrides,
code: { lines: true, ...ajvOptionsOverrides.code, source: true },
schemas
};
const ajv = createAjvInstance(additionalMetaSchemas, customFormats, compileOptions, ajvFormatOptions, AjvClass);
return (0, import_standalone.default)(ajv);
}
// src/compileSchemaValidators.ts
function compileSchemaValidators(schema, output, options = {}) {
console.log("parsing the schema");
const moduleCode = compileSchemaValidatorsCode(schema, options);
console.log(`writing ${output}`);
import_fs.default.writeFileSync(output, moduleCode);
}
//# sourceMappingURL=compileSchemaValidators.js.map

@@ -0,8 +1,365 @@

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
'use strict'
// src/index.ts
var src_exports = {};
__export(src_exports, {
createPrecompiledValidator: () => createPrecompiledValidator,
customizeValidator: () => customizeValidator,
default: () => src_default
});
module.exports = __toCommonJS(src_exports);
if (process.env.NODE_ENV === 'production') {
module.exports = require('./index.cjs.production.min.js')
} else {
module.exports = require('./index.cjs.development.js')
// src/validator.ts
var import_utils3 = require("@rjsf/utils");
// src/createAjvInstance.ts
var import_ajv = __toESM(require("ajv"));
var import_ajv_formats = __toESM(require("ajv-formats"));
var import_isObject = __toESM(require("lodash/isObject"));
var import_utils = require("@rjsf/utils");
var AJV_CONFIG = {
allErrors: true,
multipleOfPrecision: 8,
strict: false,
verbose: true
};
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*\)))$/;
var DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
function createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides = {}, ajvFormatOptions, AjvClass = import_ajv.default) {
const ajv = new AjvClass({ ...AJV_CONFIG, ...ajvOptionsOverrides });
if (ajvFormatOptions) {
(0, import_ajv_formats.default)(ajv, ajvFormatOptions);
} else if (ajvFormatOptions !== false) {
(0, import_ajv_formats.default)(ajv);
}
ajv.addFormat("data-url", DATA_URL_FORMAT_REGEX);
ajv.addFormat("color", COLOR_FORMAT_REGEX);
ajv.addKeyword(import_utils.ADDITIONAL_PROPERTY_FLAG);
ajv.addKeyword(import_utils.RJSF_ADDITONAL_PROPERTIES_FLAG);
if (Array.isArray(additionalMetaSchemas)) {
ajv.addMetaSchema(additionalMetaSchemas);
}
if ((0, import_isObject.default)(customFormats)) {
Object.keys(customFormats).forEach((formatName) => {
ajv.addFormat(formatName, customFormats[formatName]);
});
}
return ajv;
}
// src/processRawValidationErrors.ts
var import_get = __toESM(require("lodash/get"));
var import_utils2 = require("@rjsf/utils");
function transformRJSFValidationErrors(errors = [], uiSchema) {
return errors.map((e) => {
const { instancePath, keyword, params, schemaPath, parentSchema, ...rest } = e;
let { message = "" } = rest;
let property = instancePath.replace(/\//g, ".");
let stack = `${property} ${message}`.trim();
if ("missingProperty" in params) {
property = property ? `${property}.${params.missingProperty}` : params.missingProperty;
const currentProperty = params.missingProperty;
const uiSchemaTitle = (0, import_utils2.getUiOptions)((0, import_get.default)(uiSchema, `${property.replace(/^\./, "")}`)).title;
if (uiSchemaTitle) {
message = message.replace(currentProperty, uiSchemaTitle);
} else {
const parentSchemaTitle = (0, import_get.default)(parentSchema, [import_utils2.PROPERTIES_KEY, currentProperty, "title"]);
if (parentSchemaTitle) {
message = message.replace(currentProperty, parentSchemaTitle);
}
}
stack = message;
} else {
const uiSchemaTitle = (0, import_utils2.getUiOptions)((0, import_get.default)(uiSchema, `${property.replace(/^\./, "")}`)).title;
if (uiSchemaTitle) {
stack = `'${uiSchemaTitle}' ${message}`.trim();
} else {
const parentSchemaTitle = parentSchema?.title;
if (parentSchemaTitle) {
stack = `'${parentSchemaTitle}' ${message}`.trim();
}
}
}
return {
name: keyword,
property,
message,
params,
// specific to ajv
stack,
schemaPath
};
});
}
function processRawValidationErrors(validator, rawErrors, formData, schema, customValidate, transformErrors, uiSchema) {
const { validationError: invalidSchemaError } = rawErrors;
let errors = transformRJSFValidationErrors(rawErrors.errors, uiSchema);
if (invalidSchemaError) {
errors = [...errors, { stack: invalidSchemaError.message }];
}
if (typeof transformErrors === "function") {
errors = transformErrors(errors, uiSchema);
}
let errorSchema = (0, import_utils2.toErrorSchema)(errors);
if (invalidSchemaError) {
errorSchema = {
...errorSchema,
$schema: {
__errors: [invalidSchemaError.message]
}
};
}
if (typeof customValidate !== "function") {
return { errors, errorSchema };
}
const newFormData = (0, import_utils2.getDefaultFormState)(validator, schema, formData, schema, true);
const errorHandler = customValidate(newFormData, (0, import_utils2.createErrorHandler)(newFormData), uiSchema);
const userErrorSchema = (0, import_utils2.unwrapErrorHandler)(errorHandler);
return (0, import_utils2.validationDataMerge)({ errors, errorSchema }, userErrorSchema);
}
// src/validator.ts
var AJV8Validator = class {
/** Constructs an `AJV8Validator` instance using the `options`
*
* @param options - The `CustomValidatorOptionsType` options that are used to create the AJV instance
* @param [localizer] - If provided, is used to localize a list of Ajv `ErrorObject`s
*/
constructor(options, localizer) {
const { additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions, AjvClass } = options;
this.ajv = createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions, AjvClass);
this.localizer = localizer;
}
/** Converts an `errorSchema` into a list of `RJSFValidationErrors`
*
* @param errorSchema - The `ErrorSchema` instance to convert
* @param [fieldPath=[]] - The current field path, defaults to [] if not specified
* @deprecated - Use the `toErrorList()` function provided by `@rjsf/utils` instead. This function will be removed in
* the next major release.
*/
toErrorList(errorSchema, fieldPath = []) {
return (0, import_utils3.toErrorList)(errorSchema, fieldPath);
}
/** Runs the pure validation of the `schema` and `formData` without any of the RJSF functionality. Provided for use
* by the playground. Returns the `errors` from the validation
*
* @param schema - The schema against which to validate the form data * @param schema
* @param formData - The form data to validate
*/
rawValidation(schema, formData) {
let compilationError = void 0;
let compiledValidator;
if (schema[import_utils3.ID_KEY]) {
compiledValidator = this.ajv.getSchema(schema[import_utils3.ID_KEY]);
}
try {
if (compiledValidator === void 0) {
compiledValidator = this.ajv.compile(schema);
}
compiledValidator(formData);
} catch (err) {
compilationError = err;
}
let errors;
if (compiledValidator) {
if (typeof this.localizer === "function") {
this.localizer(compiledValidator.errors);
}
errors = compiledValidator.errors || void 0;
compiledValidator.errors = null;
}
return {
errors,
validationError: compilationError
};
}
/** This function processes the `formData` with an optional user contributed `customValidate` function, which receives
* the form data and a `errorHandler` function that will be used to add custom validation errors for each field. Also
* supports a `transformErrors` function that will take the raw AJV validation errors, prior to custom validation and
* transform them in what ever way it chooses.
*
* @param formData - The form data to validate
* @param schema - The schema against which to validate the form data
* @param [customValidate] - An optional function that is used to perform custom validation
* @param [transformErrors] - An optional function that is used to transform errors after AJV validation
* @param [uiSchema] - An optional uiSchema that is passed to `transformErrors` and `customValidate`
*/
validateFormData(formData, schema, customValidate, transformErrors, uiSchema) {
const rawErrors = this.rawValidation(schema, formData);
return processRawValidationErrors(this, rawErrors, formData, schema, customValidate, transformErrors, uiSchema);
}
/** Validates data against a schema, returning true if the data is valid, or
* false otherwise. If the schema is invalid, then this function will return
* false.
*
* @param schema - The schema against which to validate the form data
* @param formData - The form data to validate
* @param rootSchema - The root schema used to provide $ref resolutions
*/
isValid(schema, formData, rootSchema) {
const rootSchemaId = rootSchema[import_utils3.ID_KEY] ?? import_utils3.ROOT_SCHEMA_PREFIX;
try {
if (this.ajv.getSchema(rootSchemaId) === void 0) {
this.ajv.addSchema(rootSchema, rootSchemaId);
}
const schemaWithIdRefPrefix = (0, import_utils3.withIdRefPrefix)(schema);
const schemaId = schemaWithIdRefPrefix[import_utils3.ID_KEY] ?? (0, import_utils3.hashForSchema)(schemaWithIdRefPrefix);
let compiledValidator;
compiledValidator = this.ajv.getSchema(schemaId);
if (compiledValidator === void 0) {
compiledValidator = this.ajv.addSchema(schemaWithIdRefPrefix, schemaId).getSchema(schemaId) || this.ajv.compile(schemaWithIdRefPrefix);
}
const result = compiledValidator(formData);
return result;
} catch (e) {
console.warn("Error encountered compiling schema:", e);
return false;
} finally {
this.ajv.removeSchema(rootSchemaId);
}
}
};
// src/customizeValidator.ts
function customizeValidator(options = {}, localizer) {
return new AJV8Validator(options, localizer);
}
// src/precompiledValidator.ts
var import_get2 = __toESM(require("lodash/get"));
var import_isEqual = __toESM(require("lodash/isEqual"));
var import_utils4 = require("@rjsf/utils");
var AJV8PrecompiledValidator = class {
/** Constructs an `AJV8PrecompiledValidator` instance using the `validateFns` and `rootSchema`
*
* @param validateFns - The map of the validation functions that are generated by the `schemaCompile()` function
* @param rootSchema - The root schema that was used with the `compileSchema()` function
* @param [localizer] - If provided, is used to localize a list of Ajv `ErrorObject`s
* @throws - Error when the base schema of the precompiled validator does not have a matching validator function
*/
constructor(validateFns, rootSchema, localizer) {
this.rootSchema = rootSchema;
this.validateFns = validateFns;
this.localizer = localizer;
this.mainValidator = this.getValidator(rootSchema);
this.resolvedRootSchema = (0, import_utils4.retrieveSchema)(this, rootSchema, rootSchema);
}
/** Returns the precompiled validator associated with the given `schema` from the map of precompiled validator
* functions.
*
* @param schema - The schema for which a precompiled validator function is desired
* @returns - The precompiled validator function associated with this schema
*/
getValidator(schema) {
const key = (0, import_get2.default)(schema, import_utils4.ID_KEY) || (0, import_utils4.hashForSchema)(schema);
const validator = this.validateFns[key];
if (!validator) {
throw new Error(`No precompiled validator function was found for the given schema for "${key}"`);
}
return validator;
}
/** Converts an `errorSchema` into a list of `RJSFValidationErrors`
*
* @param errorSchema - The `ErrorSchema` instance to convert
* @param [fieldPath=[]] - The current field path, defaults to [] if not specified
* @deprecated - Use the `toErrorList()` function provided by `@rjsf/utils` instead. This function will be removed in
* the next major release.
*/
toErrorList(errorSchema, fieldPath = []) {
return (0, import_utils4.toErrorList)(errorSchema, fieldPath);
}
/** Runs the pure validation of the `schema` and `formData` without any of the RJSF functionality. Provided for use
* by the playground. Returns the `errors` from the validation
*
* @param schema - The schema against which to validate the form data * @param schema
* @param formData - The form data to validate
* @throws - Error when the schema provided does not match the base schema of the precompiled validator
*/
rawValidation(schema, formData) {
if (!(0, import_isEqual.default)(schema, this.resolvedRootSchema)) {
throw new Error(
"The schema associated with the precompiled schema differs from the schema provided for validation"
);
}
this.mainValidator(formData);
if (typeof this.localizer === "function") {
this.localizer(this.mainValidator.errors);
}
const errors = this.mainValidator.errors || void 0;
this.mainValidator.errors = null;
return { errors };
}
/** This function processes the `formData` with an optional user contributed `customValidate` function, which receives
* the form data and a `errorHandler` function that will be used to add custom validation errors for each field. Also
* supports a `transformErrors` function that will take the raw AJV validation errors, prior to custom validation and
* transform them in what ever way it chooses.
*
* @param formData - The form data to validate
* @param schema - The schema against which to validate the form data
* @param [customValidate] - An optional function that is used to perform custom validation
* @param [transformErrors] - An optional function that is used to transform errors after AJV validation
* @param [uiSchema] - An optional uiSchema that is passed to `transformErrors` and `customValidate`
*/
validateFormData(formData, schema, customValidate, transformErrors, uiSchema) {
const rawErrors = this.rawValidation(schema, formData);
return processRawValidationErrors(this, rawErrors, formData, schema, customValidate, transformErrors, uiSchema);
}
/** Validates data against a schema, returning true if the data is valid, or false otherwise. If the schema is
* invalid, then this function will return false.
*
* @param schema - The schema against which to validate the form data
* @param formData - The form data to validate
* @param rootSchema - The root schema used to provide $ref resolutions
* @returns - true if the formData validates against the schema, false otherwise
* @throws - Error when the schema provided does not match the base schema of the precompiled validator OR if there
* isn't a precompiled validator function associated with the schema
*/
isValid(schema, formData, rootSchema) {
if (!(0, import_isEqual.default)(rootSchema, this.rootSchema)) {
throw new Error(
"The schema associated with the precompiled validator differs from the rootSchema provided for validation"
);
}
if ((0, import_get2.default)(schema, import_utils4.ID_KEY) === import_utils4.JUNK_OPTION_ID) {
return false;
}
const validator = this.getValidator(schema);
return validator(formData);
}
};
// src/createPrecompiledValidator.ts
function createPrecompiledValidator(validateFns, rootSchema, localizer) {
return new AJV8PrecompiledValidator(validateFns, rootSchema, localizer);
}
// src/index.ts
var src_default = customizeValidator();
//# sourceMappingURL=index.js.map

284

dist/validator-ajv8.esm.js

@@ -1,9 +0,16 @@

import { ADDITIONAL_PROPERTY_FLAG, RJSF_ADDITONAL_PROPERTIES_FLAG, toErrorSchema, getDefaultFormState, createErrorHandler, unwrapErrorHandler, validationDataMerge, getUiOptions, PROPERTIES_KEY, toErrorList, ID_KEY, withIdRefPrefix, hashForSchema, ROOT_SCHEMA_PREFIX, retrieveSchema, JUNK_OPTION_ID } from '@rjsf/utils';
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
import isObject from 'lodash-es/isObject';
import get from 'lodash-es/get';
import isEqual from 'lodash-es/isEqual';
// src/validator.ts
import {
ID_KEY,
ROOT_SCHEMA_PREFIX,
toErrorList,
withIdRefPrefix,
hashForSchema
} from "@rjsf/utils";
const AJV_CONFIG = {
// src/createAjvInstance.ts
import Ajv from "ajv";
import addFormats from "ajv-formats";
import isObject from "lodash/isObject";
import { ADDITIONAL_PROPERTY_FLAG, RJSF_ADDITONAL_PROPERTIES_FLAG } from "@rjsf/utils";
var AJV_CONFIG = {
allErrors: true,

@@ -14,24 +21,6 @@ multipleOfPrecision: 8,

};
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*\)))$/;
const DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
/** Creates an Ajv version 8 implementation object with standard support for the 'color` and `data-url` custom formats.
* If `additionalMetaSchemas` are provided then the Ajv instance is modified to add each of the meta schemas in the
* list. If `customFormats` are provided then those additional formats are added to the list of supported formats. If
* `ajvOptionsOverrides` are provided then they are spread on top of the default `AJV_CONFIG` options when constructing
* the `Ajv` instance. With Ajv v8, the JSON Schema formats are not provided by default, but can be plugged in. By
* default, all formats from the `ajv-formats` library are added. To disable this capability, set the `ajvFormatOptions`
* parameter to `false`. Additionally, you can configure the `ajv-formats` by providing a custom set of
* [format options](https://github.com/ajv-validator/ajv-formats) to the `ajvFormatOptions` parameter.
*
* @param [additionalMetaSchemas] - The list of additional meta schemas that the validator can access
* @param [customFormats] - The set of additional custom formats that the validator will support
* @param [ajvOptionsOverrides={}] - The set of validator config override options
* @param [ajvFormatOptions] - The `ajv-format` options to use when adding formats to `ajv`; pass `false` to disable it
* @param [AjvClass] - The `Ajv` class to use when creating the validator instance
*/
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*\)))$/;
var DATA_URL_FORMAT_REGEX = /^data:([a-z]+\/[a-z0-9-+.]+)?;(?:name=(.*);)?base64,(.*)$/;
function createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides = {}, ajvFormatOptions, AjvClass = Ajv) {
const ajv = new AjvClass({
...AJV_CONFIG,
...ajvOptionsOverrides
});
const ajv = new AjvClass({ ...AJV_CONFIG, ...ajvOptionsOverrides });
if (ajvFormatOptions) {

@@ -42,15 +31,11 @@ addFormats(ajv, ajvFormatOptions);

}
// add custom formats
ajv.addFormat('data-url', DATA_URL_FORMAT_REGEX);
ajv.addFormat('color', COLOR_FORMAT_REGEX);
// Add RJSF-specific additional properties keywords so Ajv doesn't report errors if strict is enabled.
ajv.addFormat("data-url", DATA_URL_FORMAT_REGEX);
ajv.addFormat("color", COLOR_FORMAT_REGEX);
ajv.addKeyword(ADDITIONAL_PROPERTY_FLAG);
ajv.addKeyword(RJSF_ADDITONAL_PROPERTIES_FLAG);
// add more schemas to validate against
if (Array.isArray(additionalMetaSchemas)) {
ajv.addMetaSchema(additionalMetaSchemas);
}
// add more custom formats to validate against
if (isObject(customFormats)) {
Object.keys(customFormats).forEach(formatName => {
Object.keys(customFormats).forEach((formatName) => {
ajv.addFormat(formatName, customFormats[formatName]);

@@ -62,31 +47,27 @@ });

/** Transforming the error output from ajv to format used by @rjsf/utils.
* At some point, components should be updated to support ajv.
*
* @param errors - The list of AJV errors to convert to `RJSFValidationErrors`
* @param [uiSchema] - An optional uiSchema that is passed to `transformErrors` and `customValidate`
*/
// src/processRawValidationErrors.ts
import get from "lodash/get";
import {
createErrorHandler,
getDefaultFormState,
getUiOptions,
PROPERTIES_KEY,
toErrorSchema,
unwrapErrorHandler,
validationDataMerge
} from "@rjsf/utils";
function transformRJSFValidationErrors(errors = [], uiSchema) {
return errors.map(e => {
const {
instancePath,
keyword,
params,
schemaPath,
parentSchema,
...rest
} = e;
let {
message = ''
} = rest;
let property = instancePath.replace(/\//g, '.');
return errors.map((e) => {
const { instancePath, keyword, params, schemaPath, parentSchema, ...rest } = e;
let { message = "" } = rest;
let property = instancePath.replace(/\//g, ".");
let stack = `${property} ${message}`.trim();
if ('missingProperty' in params) {
if ("missingProperty" in params) {
property = property ? `${property}.${params.missingProperty}` : params.missingProperty;
const currentProperty = params.missingProperty;
const uiSchemaTitle = getUiOptions(get(uiSchema, `${property.replace(/^\./, '')}`)).title;
const uiSchemaTitle = getUiOptions(get(uiSchema, `${property.replace(/^\./, "")}`)).title;
if (uiSchemaTitle) {
message = message.replace(currentProperty, uiSchemaTitle);
} else {
const parentSchemaTitle = get(parentSchema, [PROPERTIES_KEY, currentProperty, 'title']);
const parentSchemaTitle = get(parentSchema, [PROPERTIES_KEY, currentProperty, "title"]);
if (parentSchemaTitle) {

@@ -98,7 +79,7 @@ message = message.replace(currentProperty, parentSchemaTitle);

} else {
const uiSchemaTitle = getUiOptions(get(uiSchema, `${property.replace(/^\./, '')}`)).title;
const uiSchemaTitle = getUiOptions(get(uiSchema, `${property.replace(/^\./, "")}`)).title;
if (uiSchemaTitle) {
stack = `'${uiSchemaTitle}' ${message}`.trim();
} else {
const parentSchemaTitle = parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.title;
const parentSchemaTitle = parentSchema?.title;
if (parentSchemaTitle) {

@@ -109,3 +90,2 @@ stack = `'${parentSchemaTitle}' ${message}`.trim();

}
// put data in expected format
return {

@@ -116,2 +96,3 @@ name: keyword,

params,
// specific to ajv
stack,

@@ -122,26 +103,9 @@ schemaPath

}
/** This function processes the `formData` with an optional user contributed `customValidate` function, which receives
* the form data and a `errorHandler` function that will be used to add custom validation errors for each field. Also
* supports a `transformErrors` function that will take the raw AJV validation errors, prior to custom validation and
* transform them in what ever way it chooses.
*
* @param validator - The `ValidatorType` implementation used for the `getDefaultFormState()` call
* @param rawErrors - The list of raw `ErrorObject`s to process
* @param formData - The form data to validate
* @param schema - The schema against which to validate the form data
* @param [customValidate] - An optional function that is used to perform custom validation
* @param [transformErrors] - An optional function that is used to transform errors after AJV validation
* @param [uiSchema] - An optional uiSchema that is passed to `transformErrors` and `customValidate`
*/
function processRawValidationErrors(validator, rawErrors, formData, schema, customValidate, transformErrors, uiSchema) {
const {
validationError: invalidSchemaError
} = rawErrors;
const { validationError: invalidSchemaError } = rawErrors;
let errors = transformRJSFValidationErrors(rawErrors.errors, uiSchema);
if (invalidSchemaError) {
errors = [...errors, {
stack: invalidSchemaError.message
}];
errors = [...errors, { stack: invalidSchemaError.message }];
}
if (typeof transformErrors === 'function') {
if (typeof transformErrors === "function") {
errors = transformErrors(errors, uiSchema);

@@ -158,21 +122,13 @@ }

}
if (typeof customValidate !== 'function') {
return {
errors,
errorSchema
};
if (typeof customValidate !== "function") {
return { errors, errorSchema };
}
// Include form data with undefined values, which is required for custom validation.
const newFormData = getDefaultFormState(validator, schema, formData, schema, true);
const errorHandler = customValidate(newFormData, createErrorHandler(newFormData), uiSchema);
const userErrorSchema = unwrapErrorHandler(errorHandler);
return validationDataMerge({
errors,
errorSchema
}, userErrorSchema);
return validationDataMerge({ errors, errorSchema }, userErrorSchema);
}
/** `ValidatorType` implementation that uses the AJV 8 validation mechanism.
*/
class AJV8Validator {
// src/validator.ts
var AJV8Validator = class {
/** Constructs an `AJV8Validator` instance using the `options`

@@ -184,19 +140,3 @@ *

constructor(options, localizer) {
/** The AJV instance to use for all validations
*
* @private
*/
this.ajv = void 0;
/** The Localizer function to use for localizing Ajv errors
*
* @private
*/
this.localizer = void 0;
const {
additionalMetaSchemas,
customFormats,
ajvOptionsOverrides,
ajvFormatOptions,
AjvClass
} = options;
const { additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions, AjvClass } = options;
this.ajv = createAjvInstance(additionalMetaSchemas, customFormats, ajvOptionsOverrides, ajvFormatOptions, AjvClass);

@@ -222,3 +162,3 @@ this.localizer = localizer;

rawValidation(schema, formData) {
let compilationError = undefined;
let compilationError = void 0;
let compiledValidator;

@@ -229,3 +169,3 @@ if (schema[ID_KEY]) {

try {
if (compiledValidator === undefined) {
if (compiledValidator === void 0) {
compiledValidator = this.ajv.compile(schema);

@@ -239,11 +179,10 @@ }

if (compiledValidator) {
if (typeof this.localizer === 'function') {
if (typeof this.localizer === "function") {
this.localizer(compiledValidator.errors);
}
errors = compiledValidator.errors || undefined;
// Clear errors to prevent persistent errors, see #1104
errors = compiledValidator.errors || void 0;
compiledValidator.errors = null;
}
return {
errors: errors,
errors,
validationError: compilationError

@@ -278,7 +217,3 @@ };

try {
// add the rootSchema ROOT_SCHEMA_PREFIX as id.
// then rewrite the schema ref's to point to the rootSchema
// this accounts for the case where schema have references to models
// that lives in the rootSchema but not in the schema in question.
if (this.ajv.getSchema(rootSchemaId) === undefined) {
if (this.ajv.getSchema(rootSchemaId) === void 0) {
this.ajv.addSchema(rootSchema, rootSchemaId);

@@ -290,6 +225,3 @@ }

compiledValidator = this.ajv.getSchema(schemaId);
if (compiledValidator === undefined) {
// Add schema by an explicit ID so it can be fetched later
// Fall back to using compile if necessary
// https://ajv.js.org/guide/managing-schemas.html#pre-adding-all-schemas-vs-adding-on-demand
if (compiledValidator === void 0) {
compiledValidator = this.ajv.addSchema(schemaWithIdRefPrefix, schemaId).getSchema(schemaId) || this.ajv.compile(schemaWithIdRefPrefix);

@@ -300,20 +232,11 @@ }

} catch (e) {
console.warn('Error encountered compiling schema:', e);
console.warn("Error encountered compiling schema:", e);
return false;
} finally {
// TODO: A function should be called if the root schema changes so we don't have to remove and recompile the schema every run.
// make sure we remove the rootSchema from the global ajv instance
this.ajv.removeSchema(rootSchemaId);
}
}
}
};
/** Creates and returns a customized implementation of the `ValidatorType` with the given customization `options` if
* provided. If a `localizer` is provided, it is used to translate the messages generated by the underlying AJV
* validation.
*
* @param [options={}] - The `CustomValidatorOptionsType` options that are used to create the `ValidatorType` instance
* @param [localizer] - If provided, is used to localize a list of Ajv `ErrorObject`s
* @returns - The custom validator implementation resulting from the set of parameters provided
*/
// src/customizeValidator.ts
function customizeValidator(options = {}, localizer) {

@@ -323,6 +246,13 @@ return new AJV8Validator(options, localizer);

/** `ValidatorType` implementation that uses an AJV 8 precompiled validator as created by the
* `compileSchemaValidators()` function provided by the `@rjsf/validator-ajv8` library.
*/
class AJV8PrecompiledValidator {
// src/precompiledValidator.ts
import get2 from "lodash/get";
import isEqual from "lodash/isEqual";
import {
hashForSchema as hashForSchema2,
ID_KEY as ID_KEY2,
JUNK_OPTION_ID,
toErrorList as toErrorList2,
retrieveSchema
} from "@rjsf/utils";
var AJV8PrecompiledValidator = class {
/** Constructs an `AJV8PrecompiledValidator` instance using the `validateFns` and `rootSchema`

@@ -336,27 +266,2 @@ *

constructor(validateFns, rootSchema, localizer) {
/** The root schema object used to construct this validator
*
* @private
*/
this.rootSchema = void 0;
/** The root schema resolved top level refs
*
* @private
*/
this.resolvedRootSchema = void 0;
/** The `ValidatorFunctions` map used to construct this validator
*
* @private
*/
this.validateFns = void 0;
/** The main validator function associated with the base schema in the `precompiledValidator`
*
* @private
*/
this.mainValidator = void 0;
/** The Localizer function to use for localizing Ajv errors
*
* @private
*/
this.localizer = void 0;
this.rootSchema = rootSchema;

@@ -375,3 +280,3 @@ this.validateFns = validateFns;

getValidator(schema) {
const key = get(schema, ID_KEY) || hashForSchema(schema);
const key = get2(schema, ID_KEY2) || hashForSchema2(schema);
const validator = this.validateFns[key];

@@ -391,3 +296,3 @@ if (!validator) {

toErrorList(errorSchema, fieldPath = []) {
return toErrorList(errorSchema, fieldPath);
return toErrorList2(errorSchema, fieldPath);
}

@@ -403,14 +308,13 @@ /** Runs the pure validation of the `schema` and `formData` without any of the RJSF functionality. Provided for use

if (!isEqual(schema, this.resolvedRootSchema)) {
throw new Error('The schema associated with the precompiled schema differs from the schema provided for validation');
throw new Error(
"The schema associated with the precompiled schema differs from the schema provided for validation"
);
}
this.mainValidator(formData);
if (typeof this.localizer === 'function') {
if (typeof this.localizer === "function") {
this.localizer(this.mainValidator.errors);
}
const errors = this.mainValidator.errors || undefined;
// Clear errors to prevent persistent errors, see #1104
const errors = this.mainValidator.errors || void 0;
this.mainValidator.errors = null;
return {
errors: errors
};
return { errors };
}

@@ -444,5 +348,7 @@ /** This function processes the `formData` with an optional user contributed `customValidate` function, which receives

if (!isEqual(rootSchema, this.rootSchema)) {
throw new Error('The schema associated with the precompiled validator differs from the rootSchema provided for validation');
throw new Error(
"The schema associated with the precompiled validator differs from the rootSchema provided for validation"
);
}
if (get(schema, ID_KEY) === JUNK_OPTION_ID) {
if (get2(schema, ID_KEY2) === JUNK_OPTION_ID) {
return false;

@@ -453,15 +359,5 @@ }

}
}
};
/** Creates and returns a `ValidatorType` interface that is implemented with a precompiled validator. If a `localizer`
* is provided, it is used to translate the messages generated by the underlying AJV validation.
*
* NOTE: The `validateFns` parameter is an object obtained by importing from a precompiled validation file created via
* the `compileSchemaValidators()` function.
*
* @param validateFns - The map of the validation functions that are created by the `compileSchemaValidators()` function
* @param rootSchema - The root schema that was used with the `compileSchemaValidators()` function
* @param [localizer] - If provided, is used to localize a list of Ajv `ErrorObject`s
* @returns - The precompiled validator implementation resulting from the set of parameters provided
*/
// src/createPrecompiledValidator.ts
function createPrecompiledValidator(validateFns, rootSchema, localizer) {

@@ -471,5 +367,9 @@ return new AJV8PrecompiledValidator(validateFns, rootSchema, localizer);

var index = /*#__PURE__*/customizeValidator();
export { createPrecompiledValidator, customizeValidator, index as default };
// src/index.ts
var src_default = customizeValidator();
export {
createPrecompiledValidator,
customizeValidator,
src_default as default
};
//# sourceMappingURL=validator-ajv8.esm.js.map
{
"name": "@rjsf/validator-ajv8",
"version": "5.11.2",
"version": "5.12.0",
"main": "dist/index.js",
"module": "dist/validator-ajv8.esm.js",
"typings": "dist/index.d.ts",
"module": "lib/index.js",
"typings": "lib/index.d.ts",
"description": "The ajv-8 based validator for @rjsf/core",
"files": [
"dist"
"dist",
"lib",
"src"
],

@@ -16,4 +18,7 @@ "engineStrict": false,

"scripts": {
"build": "rimraf dist && dts build --rollupTypes --format esm,umd && npm run build:compiler",
"build:compiler": "dts build --noClean --rollupTypes --format cjs --entry ./src/index.ts --entry ./src/compileSchemaValidators.ts",
"build:ts": "rimraf lib && tsc",
"build:cjs": "esbuild ./src/index.ts --bundle --outfile=dist/index.js --sourcemap --packages=external --format=cjs && esbuild ./src/compileSchemaValidators.ts --bundle --outfile=dist/compileSchemaValidators.js --sourcemap --packages=external --format=cjs",
"build:esm": "esbuild ./src/index.ts --bundle --outfile=dist/validator-ajv8.esm.js --sourcemap --packages=external --format=esm && esbuild ./src/compileSchemaValidators.ts --bundle --outfile=dist/compileSchemaValidators.esm.js --sourcemap --packages=external --format=esm",
"build:umd": "rollup dist/validator-ajv8.esm.js --format=umd --file=dist/validator-ajv8.umd.js --name=@rjsf/validator-ajv8",
"build": "rimraf dist && npm run build:ts && npm run build:cjs && npm run build:esm && npm run build:umd",
"cs-check": "prettier -l \"{src,test}/**/*.ts?(x)\"",

@@ -48,13 +53,13 @@ "cs-format": "prettier \"{src,test}/**/*.ts?(x)\" --write",

"@babel/preset-typescript": "^7.22.5",
"@rjsf/utils": "^5.11.2",
"@types/jest-expect-message": "^1.1.0",
"@rjsf/utils": "^5.12.0",
"@types/json-schema": "^7.0.12",
"@types/lodash": "^4.14.195",
"babel-jest": "^29.6.1",
"dts-cli": "^1.6.3",
"eslint": "^8.44.0",
"jest": "^29.6.1",
"@types/lodash": "^4.14.196",
"babel-jest": "^29.6.2",
"esbuild": "^0.18.19",
"eslint": "^8.46.0",
"jest": "^29.6.2",
"jest-environment-jsdom": "^29.6.1",
"jest-expect-message": "^1.1.3",
"rimraf": "^5.0.1"
"rimraf": "^5.0.1",
"rollup": "^3.27.2",
"typescript": "^4.9.5"
},

@@ -82,3 +87,3 @@ "publishConfig": {

"license": "Apache-2.0",
"gitHead": "2fafced84e18aa2cd487715d11d2730cd23333f3"
"gitHead": "bab797c43a34e5ec68a84b2bdabb3c377e46b092"
}

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc