Socket
Socket
Sign inDemoInstall

@hookform/resolvers

Package Overview
Dependencies
Maintainers
2
Versions
118
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@hookform/resolvers - npm Package Compare versions

Comparing version 0.2.0-beta.2 to 0.2.0-beta.3

dist/jsonSchema.d.ts

561

dist/index.cjs.development.js

@@ -128,5 +128,566 @@ 'use strict';

var compileSchema = require('./compile')
, resolve = require('./compile/resolve')
, Cache = require('./cache')
, SchemaObject = require('./compile/schema_obj')
, stableStringify = require('fast-json-stable-stringify')
, formats = require('./compile/formats')
, rules = require('./compile/rules')
, $dataMetaSchema = require('./data')
, util = require('./compile/util');
module.exports = Ajv;
Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;
Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;
Ajv.prototype.compileAsync = require('./compile/async');
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;
var errorClasses = require('./compile/error_classes');
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
var META_SUPPORT_DATA = ['/properties'];
/**
* Creates validator instance.
* Usage: `Ajv(opts)`
* @param {Object} opts optional options
* @return {Object} ajv instance
*/
function Ajv(opts) {
if (!(this instanceof Ajv)) return new Ajv(opts);
opts = this._opts = util.copy(opts) || {};
setLogger(this);
this._schemas = {};
this._refs = {};
this._fragments = {};
this._formats = formats(opts.format);
this._cache = opts.cache || new Cache;
this._loadingSchemas = {};
this._compilations = [];
this.RULES = rules();
this._getId = chooseGetId(opts);
opts.loopRequired = opts.loopRequired || Infinity;
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
if (opts.serialize === undefined) opts.serialize = stableStringify;
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
if (opts.keywords) addInitialKeywords(this);
addDefaultMetaSchema(this);
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
addInitialSchemas(this);
}
/**
* Validate data using schema
* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
* @this Ajv
* @param {String|Object} schemaKeyRef key, ref or schema object
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
function validate(schemaKeyRef, data) {
var v;
if (typeof schemaKeyRef == 'string') {
v = this.getSchema(schemaKeyRef);
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
} else {
var schemaObj = this._addSchema(schemaKeyRef);
v = schemaObj.validate || this._compile(schemaObj);
}
var valid = v(data);
if (v.$async !== true) this.errors = v.errors;
return valid;
}
/**
* Create validating function for passed schema.
* @this Ajv
* @param {Object} schema schema object
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
* @return {Function} validating function
*/
function compile(schema, _meta) {
var schemaObj = this._addSchema(schema, undefined, _meta);
return schemaObj.validate || this._compile(schemaObj);
}
/**
* Adds schema to the instance.
* @this Ajv
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
* @return {Ajv} this for method chaining
*/
function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
return this;
}
var id = this._getId(schema);
if (id !== undefined && typeof id != 'string')
throw new Error('schema id must be string');
key = resolve.normalizeId(key || id);
checkUnique(this, key);
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
return this;
}
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @this Ajv
* @param {Object} schema schema object
* @param {String} key optional schema key
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
* @return {Ajv} this for method chaining
*/
function addMetaSchema(schema, key, skipValidation) {
this.addSchema(schema, key, skipValidation, true);
return this;
}
/**
* Validate schema
* @this Ajv
* @param {Object} schema schema to validate
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
* @return {Boolean} true if schema is valid
*/
function validateSchema(schema, throwOrLogError) {
var $schema = schema.$schema;
if ($schema !== undefined && typeof $schema != 'string')
throw new Error('$schema must be a string');
$schema = $schema || this._opts.defaultMeta || defaultMeta(this);
if (!$schema) {
this.logger.warn('meta-schema not available');
this.errors = null;
return true;
}
var valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
var message = 'schema is invalid: ' + this.errorsText();
if (this._opts.validateSchema == 'log') this.logger.error(message);
else throw new Error(message);
}
return valid;
}
function defaultMeta(self) {
var meta = self._opts.meta;
self._opts.defaultMeta = typeof meta == 'object'
? self._getId(meta) || meta
: self.getSchema(META_SCHEMA_ID)
? META_SCHEMA_ID
: undefined;
return self._opts.defaultMeta;
}
/**
* Get compiled schema from the instance by `key` or `ref`.
* @this Ajv
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
* @return {Function} schema validating function (with property `schema`).
*/
function getSchema(keyRef) {
var schemaObj = _getSchemaObj(this, keyRef);
switch (typeof schemaObj) {
case 'object': return schemaObj.validate || this._compile(schemaObj);
case 'string': return this.getSchema(schemaObj);
case 'undefined': return _getSchemaFragment(this, keyRef);
}
}
function _getSchemaFragment(self, ref) {
var res = resolve.schema.call(self, { schema: {} }, ref);
if (res) {
var schema = res.schema
, root = res.root
, baseId = res.baseId;
var v = compileSchema.call(self, schema, root, undefined, baseId);
self._fragments[ref] = new SchemaObject({
ref: ref,
fragment: true,
schema: schema,
root: root,
baseId: baseId,
validate: v
});
return v;
}
}
function _getSchemaObj(self, keyRef) {
keyRef = resolve.normalizeId(keyRef);
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}
/**
* Remove cached schema(s).
* If no parameter is passed all schemas but meta-schemas are removed.
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
* @this Ajv
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
* @return {Ajv} this for method chaining
*/
function removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
_removeAllSchemas(this, this._schemas, schemaKeyRef);
_removeAllSchemas(this, this._refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case 'undefined':
_removeAllSchemas(this, this._schemas);
_removeAllSchemas(this, this._refs);
this._cache.clear();
return this;
case 'string':
var schemaObj = _getSchemaObj(this, schemaKeyRef);
if (schemaObj) this._cache.del(schemaObj.cacheKey);
delete this._schemas[schemaKeyRef];
delete this._refs[schemaKeyRef];
return this;
case 'object':
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
this._cache.del(cacheKey);
var id = this._getId(schemaKeyRef);
if (id) {
id = resolve.normalizeId(id);
delete this._schemas[id];
delete this._refs[id];
}
}
return this;
}
function _removeAllSchemas(self, schemas, regex) {
for (var keyRef in schemas) {
var schemaObj = schemas[keyRef];
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
self._cache.del(schemaObj.cacheKey);
delete schemas[keyRef];
}
}
}
/* @this Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
if (typeof schema != 'object' && typeof schema != 'boolean')
throw new Error('schema should be object or boolean');
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schema) : schema;
var cached = this._cache.get(cacheKey);
if (cached) return cached;
shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
var id = resolve.normalizeId(this._getId(schema));
if (id && shouldAddSchema) checkUnique(this, id);
var willValidate = this._opts.validateSchema !== false && !skipValidation;
var recursiveMeta;
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
this.validateSchema(schema, true);
var localRefs = resolve.ids.call(this, schema);
var schemaObj = new SchemaObject({
id: id,
schema: schema,
localRefs: localRefs,
cacheKey: cacheKey,
meta: meta
});
if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
this._cache.put(cacheKey, schemaObj);
if (willValidate && recursiveMeta) this.validateSchema(schema, true);
return schemaObj;
}
/* @this Ajv */
function _compile(schemaObj, root) {
if (schemaObj.compiling) {
schemaObj.validate = callValidate;
callValidate.schema = schemaObj.schema;
callValidate.errors = null;
callValidate.root = root ? root : callValidate;
if (schemaObj.schema.$async === true)
callValidate.$async = true;
return callValidate;
}
schemaObj.compiling = true;
var currentOpts;
if (schemaObj.meta) {
currentOpts = this._opts;
this._opts = this._metaOpts;
}
var v;
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
catch(e) {
delete schemaObj.validate;
throw e;
}
finally {
schemaObj.compiling = false;
if (schemaObj.meta) this._opts = currentOpts;
}
schemaObj.validate = v;
schemaObj.refs = v.refs;
schemaObj.refVal = v.refVal;
schemaObj.root = v.root;
return v;
/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var _validate = schemaObj.validate;
var result = _validate.apply(this, arguments);
callValidate.errors = _validate.errors;
return result;
}
}
function chooseGetId(opts) {
switch (opts.schemaId) {
case 'auto': return _get$IdOrId;
case 'id': return _getId;
default: return _get$Id;
}
}
/* @this Ajv */
function _getId(schema) {
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
return schema.id;
}
/* @this Ajv */
function _get$Id(schema) {
if (schema.id) this.logger.warn('schema id ignored', schema.id);
return schema.$id;
}
function _get$IdOrId(schema) {
if (schema.$id && schema.id && schema.$id != schema.id)
throw new Error('schema $id is different from id');
return schema.$id || schema.id;
}
/**
* Convert array of error message objects to string
* @this Ajv
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {Object} options optional options with properties `separator` and `dataVar`.
* @return {String} human readable string with all errors descriptions
*/
function errorsText(errors, options) {
errors = errors || this.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = options.separator === undefined ? ', ' : options.separator;
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
var text = '';
for (var i=0; i<errors.length; i++) {
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
}
/**
* Add custom format
* @this Ajv
* @param {String} name format name
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
* @return {Ajv} this for method chaining
*/
function addFormat(name, format) {
if (typeof format == 'string') format = new RegExp(format);
this._formats[name] = format;
return this;
}
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = require('./refs/data.json');
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
}
if (self._opts.meta === false) return;
var metaSchema = require('./refs/json-schema-draft-07.json');
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}
function addInitialSchemas(self) {
var optsSchemas = self._opts.schemas;
if (!optsSchemas) return;
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}
function addInitialFormats(self) {
for (var name in self._opts.formats) {
var format = self._opts.formats[name];
self.addFormat(name, format);
}
}
function addInitialKeywords(self) {
for (var name in self._opts.keywords) {
var keyword = self._opts.keywords[name];
self.addKeyword(name, keyword);
}
}
function checkUnique(self, id) {
if (self._schemas[id] || self._refs[id])
throw new Error('schema with key or id "' + id + '" already exists');
}
function getMetaSchemaOptions(self) {
var metaOpts = util.copy(self._opts);
for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
delete metaOpts[META_IGNORE_OPTIONS[i]];
return metaOpts;
}
function setLogger(self) {
var logger = self._opts.logger;
if (logger === false) {
self.logger = {log: noop, warn: noop, error: noop};
} else {
if (logger === undefined) logger = console;
if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
throw new Error('logger must implement log, warn and error methods');
self.logger = logger;
}
}
function noop() {}
var Ajv$1 = /*#__PURE__*/Object.freeze({
__proto__: null
});
const parseErrorSchema$3 = (validationError, validateAllFieldCriteria) => Array.isArray(validationError)
? validationError.reduce((previous, { dataPath, keyword, message }) => {
const path = dataPath.replace(/^\./, '');
return Object.assign(Object.assign({}, previous), (path
? previous[path] && validateAllFieldCriteria
? {
[path]: reactHookForm.appendErrors(path, validateAllFieldCriteria, previous, keyword, message),
}
: {
[path]: previous[path] ||
Object.assign({ type: keyword, message }, (validateAllFieldCriteria
? {
types: { [keyword]: message || true },
}
: {})),
}
: {}));
}, {})
: {};
const jsonSchemaResolver = (validationSchema, options = {}) => {
if (!validationSchema || typeof validationSchema !== 'object') {
throw new Error('Invalid AJV schema or validation function');
}
let allErrors = false;
let validate;
const getValidator = (validateAllFieldCriteria) => {
// compile only if necessary. otherwise return the memoized validation function
if (!validate || allErrors !== validateAllFieldCriteria) {
allErrors = validateAllFieldCriteria;
validate = new Ajv$1(Object.assign(Object.assign({}, options.ajvOptions), { async: false, allErrors, validateSchema: true, transpile: undefined })).compile(validationSchema);
}
return validate;
};
// compile the validator right away so there is an exception if the schema is invalid
getValidator(allErrors);
return async (data, _, validateAllFieldCriteria = allErrors) => {
const validate = getValidator(validateAllFieldCriteria);
const valid = validate(data);
const errors = validate.errors;
return valid
? {
values: data,
errors: {},
}
: {
values: {},
errors: reactHookForm.transformToNestObject(parseErrorSchema$3(errors, validateAllFieldCriteria)),
};
};
};
exports.joiResolver = joiResolver;
exports.jsonSchemaResolver = jsonSchemaResolver;
exports.superstructResolver = superstructResolver;
exports.yupResolver = yupResolver;
//# sourceMappingURL=index.cjs.development.js.map

2

dist/index.cjs.production.min.js

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react-hook-form");var s=e=>e.reduce((e,s,r)=>`${e}${"string"==typeof s?`${r>0?".":""}${s}`:`[${s}]`}`,"").toString();const r=(r,t)=>Array.isArray(r.failures)?r.failures.reduce((r,{path:a,message:n="",type:c})=>{const o=s(a);return Object.assign(Object.assign({},r),a?r[o]&&t?{[o]:e.appendErrors(o,t,r,c||"",n)}:{[o]:r[o]||Object.assign({message:n,type:c},t?{types:{[c||""]:n||!0}}:{})}:{})},{}):[],t=(r,t)=>Array.isArray(r.details)?r.details.reduce((r,{path:a,message:n="",type:c})=>{const o=s(a);return Object.assign(Object.assign({},r),a?r[o]&&t?{[o]:e.appendErrors(o,t,r,c,n)}:{[o]:r[o]||Object.assign({message:n,type:c},t?{types:{[c]:n||!0}}:{})}:{})},{}):[];exports.joiResolver=(s,r={abortEarly:!1})=>async(a,n,c=!1)=>{try{return{values:await s.validateAsync(a,Object.assign({},r)),errors:{}}}catch(s){return{values:{},errors:e.transformToNestObject(t(s,c))}}},exports.superstructResolver=s=>async(t,a,n=!1)=>{try{return{values:s(t),errors:{}}}catch(s){return{values:{},errors:e.transformToNestObject(r(s,n))}}},exports.yupResolver=(s,r={abortEarly:!1})=>async(t,a,n=!1)=>{try{return r.context,{values:await s.validate(t,Object.assign(Object.assign({},r),{context:a})),errors:{}}}catch(s){const r=((e,s)=>Array.isArray(e.inner)&&e.inner.length?e.inner.reduce((e,{path:r,message:t,type:a})=>{const n=e[r]&&e[r].types||{},c=r||a;return Object.assign(Object.assign({},e),c?{[c]:Object.assign(Object.assign({},e[c]||{message:t,type:a}),s?{types:Object.assign(Object.assign({},n),{[a]:n[a]?[...[].concat(n[a]),t]:t})}:{})}:{})},{}):{[e.path]:{message:e.message,type:e.type}})(s,n);return{values:{},errors:e.transformToNestObject(r)}}};
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react-hook-form");var t=e=>e.reduce((e,t,r)=>`${e}${"string"==typeof t?`${r>0?".":""}${t}`:`[${t}]`}`,"").toString();const r=(r,s)=>Array.isArray(r.failures)?r.failures.reduce((r,{path:a,message:i="",type:o})=>{const n=t(a);return Object.assign(Object.assign({},r),a?r[n]&&s?{[n]:e.appendErrors(n,s,r,o||"",i)}:{[n]:r[n]||Object.assign({message:i,type:o},s?{types:{[o||""]:i||!0}}:{})}:{})},{}):[],s=(r,s)=>Array.isArray(r.details)?r.details.reduce((r,{path:a,message:i="",type:o})=>{const n=t(a);return Object.assign(Object.assign({},r),a?r[n]&&s?{[n]:e.appendErrors(n,s,r,o,i)}:{[n]:r[n]||Object.assign({message:i,type:o},s?{types:{[o]:i||!0}}:{})}:{})},{}):[];var a=require("./compile"),i=require("./compile/resolve"),o=require("./cache"),n=require("./compile/schema_obj"),c=require("fast-json-stable-stringify"),h=require("./compile/formats"),d=require("./compile/rules"),l=require("./data"),p=require("./compile/util");module.exports=g,g.prototype.validate=function(e,t){var r;if("string"==typeof e){if(!(r=this.getSchema(e)))throw new Error('no schema with key or ref "'+e+'"')}else{var s=this._addSchema(e);r=s.validate||this._compile(s)}var a=r(t);!0!==r.$async&&(this.errors=r.errors);return a},g.prototype.compile=function(e,t){var r=this._addSchema(e,void 0,t);return r.validate||this._compile(r)},g.prototype.addSchema=function(e,t,r,s){if(Array.isArray(e)){for(var a=0;a<e.length;a++)this.addSchema(e[a],void 0,r,s);return this}var o=this._getId(e);if(void 0!==o&&"string"!=typeof o)throw new Error("schema id must be string");return O(this,t=i.normalizeId(t||o)),this._schemas[t]=this._addSchema(e,r,s,!0),this},g.prototype.addMetaSchema=function(e,t,r){return this.addSchema(e,t,r,!0),this},g.prototype.validateSchema=function(e,t){var r=e.$schema;if(void 0!==r&&"string"!=typeof r)throw new Error("$schema must be a string");if(!(r=r||this._opts.defaultMeta||function(e){var t=e._opts.meta;return e._opts.defaultMeta="object"==typeof t?e._getId(t)||t:e.getSchema(f)?f:void 0,e._opts.defaultMeta}(this)))return this.logger.warn("meta-schema not available"),this.errors=null,!0;var s=this.validate(r,e);if(!s&&t){var a="schema is invalid: "+this.errorsText();if("log"!=this._opts.validateSchema)throw new Error(a);this.logger.error(a)}return s},g.prototype.getSchema=function(e){var t=_(this,e);switch(typeof t){case"object":return t.validate||this._compile(t);case"string":return this.getSchema(t);case"undefined":return function(e,t){var r=i.schema.call(e,{schema:{}},t);if(r){var s=r.schema,o=r.root,c=r.baseId,h=a.call(e,s,o,void 0,c);return e._fragments[t]=new n({ref:t,fragment:!0,schema:s,root:o,baseId:c,validate:h}),h}}(this,e)}},g.prototype.removeSchema=function(e){if(e instanceof RegExp)return b(this,this._schemas,e),b(this,this._refs,e),this;switch(typeof e){case"undefined":return b(this,this._schemas),b(this,this._refs),this._cache.clear(),this;case"string":var t=_(this,e);return t&&this._cache.del(t.cacheKey),delete this._schemas[e],delete this._refs[e],this;case"object":var r=this._opts.serialize,s=r?r(e):e;this._cache.del(s);var a=this._getId(e);a&&(a=i.normalizeId(a),delete this._schemas[a],delete this._refs[a])}return this},g.prototype.addFormat=function(e,t){"string"==typeof t&&(t=new RegExp(t));return this._formats[e]=t,this},g.prototype.errorsText=function(e,t){if(!(e=e||this.errors))return"No errors";for(var r=void 0===(t=t||{}).separator?", ":t.separator,s=void 0===t.dataVar?"data":t.dataVar,a="",i=0;i<e.length;i++){var o=e[i];o&&(a+=s+o.dataPath+" "+o.message+r)}return a.slice(0,-r.length)},g.prototype._addSchema=function(e,t,r,s){if("object"!=typeof e&&"boolean"!=typeof e)throw new Error("schema should be object or boolean");var a=this._opts.serialize,o=a?a(e):e,c=this._cache.get(o);if(c)return c;s=s||!1!==this._opts.addUsedSchema;var h=i.normalizeId(this._getId(e));h&&s&&O(this,h);var d,l=!1!==this._opts.validateSchema&&!t;l&&!(d=h&&h==i.normalizeId(e.$schema))&&this.validateSchema(e,!0);var p=i.ids.call(this,e),m=new n({id:h,schema:e,localRefs:p,cacheKey:o,meta:r});"#"!=h[0]&&s&&(this._refs[h]=m);this._cache.put(o,m),l&&d&&this.validateSchema(e,!0);return m},g.prototype._compile=function(e,t){if(e.compiling)return e.validate=i,i.schema=e.schema,i.errors=null,i.root=t||i,!0===e.schema.$async&&(i.$async=!0),i;var r,s;e.compiling=!0,e.meta&&(r=this._opts,this._opts=this._metaOpts);try{s=a.call(this,e.schema,t,e.localRefs)}catch(t){throw delete e.validate,t}finally{e.compiling=!1,e.meta&&(this._opts=r)}return e.validate=s,e.refs=s.refs,e.refVal=s.refVal,e.root=s.root,s;function i(){var t=e.validate,r=t.apply(this,arguments);return i.errors=t.errors,r}},g.prototype.compileAsync=require("./compile/async");var m=require("./keyword");g.prototype.addKeyword=m.add,g.prototype.getKeyword=m.get,g.prototype.removeKeyword=m.remove,g.prototype.validateKeyword=m.validate;var u=require("./compile/error_classes");g.ValidationError=u.Validation,g.MissingRefError=u.MissingRef,g.$dataMetaSchema=l;var f="http://json-schema.org/draft-07/schema",y=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],v=["/properties"];function g(e){if(!(this instanceof g))return new g(e);e=this._opts=p.copy(e)||{},function(e){var t=e._opts.logger;if(!1===t)e.logger={log:$,warn:$,error:$};else{if(void 0===t&&(t=console),!("object"==typeof t&&t.log&&t.warn&&t.error))throw new Error("logger must implement log, warn and error methods");e.logger=t}}(this),this._schemas={},this._refs={},this._fragments={},this._formats=h(e.format),this._cache=e.cache||new o,this._loadingSchemas={},this._compilations=[],this.RULES=d(),this._getId=function(e){switch(e.schemaId){case"auto":return S;case"id":return w;default:return j}}(e),e.loopRequired=e.loopRequired||1/0,"property"==e.errorDataPath&&(e._errorDataPathProperty=!0),void 0===e.serialize&&(e.serialize=c),this._metaOpts=function(e){for(var t=p.copy(e._opts),r=0;r<y.length;r++)delete t[y[r]];return t}(this),e.formats&&function(e){for(var t in e._opts.formats){var r=e._opts.formats[t];e.addFormat(t,r)}}(this),e.keywords&&function(e){for(var t in e._opts.keywords){var r=e._opts.keywords[t];e.addKeyword(t,r)}}(this),function(e){var t;e._opts.$data&&(t=require("./refs/data.json"),e.addMetaSchema(t,t.$id,!0));if(!1===e._opts.meta)return;var r=require("./refs/json-schema-draft-07.json");e._opts.$data&&(r=l(r,v));e.addMetaSchema(r,f,!0),e._refs["http://json-schema.org/schema"]=f}(this),"object"==typeof e.meta&&this.addMetaSchema(e.meta),e.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),function(e){var t=e._opts.schemas;if(!t)return;if(Array.isArray(t))e.addSchema(t);else for(var r in t)e.addSchema(t[r],r)}(this)}function _(e,t){return t=i.normalizeId(t),e._schemas[t]||e._refs[t]||e._fragments[t]}function b(e,t,r){for(var s in t){var a=t[s];a.meta||r&&!r.test(s)||(e._cache.del(a.cacheKey),delete t[s])}}function w(e){return e.$id&&this.logger.warn("schema $id ignored",e.$id),e.id}function j(e){return e.id&&this.logger.warn("schema id ignored",e.id),e.$id}function S(e){if(e.$id&&e.id&&e.$id!=e.id)throw new Error("schema $id is different from id");return e.$id||e.id}function O(e,t){if(e._schemas[t]||e._refs[t])throw new Error('schema with key or id "'+t+'" already exists')}function $(){}var E=Object.freeze({__proto__:null});const q=(t,r)=>Array.isArray(t)?t.reduce((t,{dataPath:s,keyword:a,message:i})=>{const o=s.replace(/^\./,"");return Object.assign(Object.assign({},t),o?t[o]&&r?{[o]:e.appendErrors(o,r,t,a,i)}:{[o]:t[o]||Object.assign({type:a,message:i},r?{types:{[a]:i||!0}}:{})}:{})},{}):{};exports.joiResolver=(t,r={abortEarly:!1})=>async(a,i,o=!1)=>{try{return{values:await t.validateAsync(a,Object.assign({},r)),errors:{}}}catch(t){return{values:{},errors:e.transformToNestObject(s(t,o))}}},exports.jsonSchemaResolver=(t,r={})=>{if(!t||"object"!=typeof t)throw new Error("Invalid AJV schema or validation function");let s,a=!1;const i=e=>(s&&a===e||(a=e,s=new E(Object.assign(Object.assign({},r.ajvOptions),{async:!1,allErrors:a,validateSchema:!0,transpile:void 0})).compile(t)),s);return i(a),async(t,r,s=a)=>{const o=i(s),n=o(t),c=o.errors;return n?{values:t,errors:{}}:{values:{},errors:e.transformToNestObject(q(c,s))}}},exports.superstructResolver=t=>async(s,a,i=!1)=>{try{return{values:t(s),errors:{}}}catch(t){return{values:{},errors:e.transformToNestObject(r(t,i))}}},exports.yupResolver=(t,r={abortEarly:!1})=>async(s,a,i=!1)=>{try{return r.context,{values:await t.validate(s,Object.assign(Object.assign({},r),{context:a})),errors:{}}}catch(t){const r=((e,t)=>Array.isArray(e.inner)&&e.inner.length?e.inner.reduce((e,{path:r,message:s,type:a})=>{const i=e[r]&&e[r].types||{},o=r||a;return Object.assign(Object.assign({},e),o?{[o]:Object.assign(Object.assign({},e[o]||{message:s,type:a}),t?{types:Object.assign(Object.assign({},i),{[a]:i[a]?[...[].concat(i[a]),s]:s})}:{})}:{})},{}):{[e.path]:{message:e.message,type:e.type}})(t,i);return{values:{},errors:e.transformToNestObject(r)}}};
//# sourceMappingURL=index.cjs.production.min.js.map
export * from './yup';
export * from './superstruct';
export * from './joi';
export * from './jsonSchema';

@@ -124,3 +124,563 @@ import { transformToNestObject, appendErrors } from 'react-hook-form';

export { joiResolver, superstructResolver, yupResolver };
var compileSchema = require('./compile')
, resolve = require('./compile/resolve')
, Cache = require('./cache')
, SchemaObject = require('./compile/schema_obj')
, stableStringify = require('fast-json-stable-stringify')
, formats = require('./compile/formats')
, rules = require('./compile/rules')
, $dataMetaSchema = require('./data')
, util = require('./compile/util');
module.exports = Ajv;
Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;
Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;
Ajv.prototype.compileAsync = require('./compile/async');
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;
var errorClasses = require('./compile/error_classes');
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
var META_SUPPORT_DATA = ['/properties'];
/**
* Creates validator instance.
* Usage: `Ajv(opts)`
* @param {Object} opts optional options
* @return {Object} ajv instance
*/
function Ajv(opts) {
if (!(this instanceof Ajv)) return new Ajv(opts);
opts = this._opts = util.copy(opts) || {};
setLogger(this);
this._schemas = {};
this._refs = {};
this._fragments = {};
this._formats = formats(opts.format);
this._cache = opts.cache || new Cache;
this._loadingSchemas = {};
this._compilations = [];
this.RULES = rules();
this._getId = chooseGetId(opts);
opts.loopRequired = opts.loopRequired || Infinity;
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
if (opts.serialize === undefined) opts.serialize = stableStringify;
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
if (opts.keywords) addInitialKeywords(this);
addDefaultMetaSchema(this);
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
addInitialSchemas(this);
}
/**
* Validate data using schema
* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
* @this Ajv
* @param {String|Object} schemaKeyRef key, ref or schema object
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
function validate(schemaKeyRef, data) {
var v;
if (typeof schemaKeyRef == 'string') {
v = this.getSchema(schemaKeyRef);
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
} else {
var schemaObj = this._addSchema(schemaKeyRef);
v = schemaObj.validate || this._compile(schemaObj);
}
var valid = v(data);
if (v.$async !== true) this.errors = v.errors;
return valid;
}
/**
* Create validating function for passed schema.
* @this Ajv
* @param {Object} schema schema object
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
* @return {Function} validating function
*/
function compile(schema, _meta) {
var schemaObj = this._addSchema(schema, undefined, _meta);
return schemaObj.validate || this._compile(schemaObj);
}
/**
* Adds schema to the instance.
* @this Ajv
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
* @return {Ajv} this for method chaining
*/
function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
return this;
}
var id = this._getId(schema);
if (id !== undefined && typeof id != 'string')
throw new Error('schema id must be string');
key = resolve.normalizeId(key || id);
checkUnique(this, key);
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
return this;
}
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @this Ajv
* @param {Object} schema schema object
* @param {String} key optional schema key
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
* @return {Ajv} this for method chaining
*/
function addMetaSchema(schema, key, skipValidation) {
this.addSchema(schema, key, skipValidation, true);
return this;
}
/**
* Validate schema
* @this Ajv
* @param {Object} schema schema to validate
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
* @return {Boolean} true if schema is valid
*/
function validateSchema(schema, throwOrLogError) {
var $schema = schema.$schema;
if ($schema !== undefined && typeof $schema != 'string')
throw new Error('$schema must be a string');
$schema = $schema || this._opts.defaultMeta || defaultMeta(this);
if (!$schema) {
this.logger.warn('meta-schema not available');
this.errors = null;
return true;
}
var valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
var message = 'schema is invalid: ' + this.errorsText();
if (this._opts.validateSchema == 'log') this.logger.error(message);
else throw new Error(message);
}
return valid;
}
function defaultMeta(self) {
var meta = self._opts.meta;
self._opts.defaultMeta = typeof meta == 'object'
? self._getId(meta) || meta
: self.getSchema(META_SCHEMA_ID)
? META_SCHEMA_ID
: undefined;
return self._opts.defaultMeta;
}
/**
* Get compiled schema from the instance by `key` or `ref`.
* @this Ajv
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
* @return {Function} schema validating function (with property `schema`).
*/
function getSchema(keyRef) {
var schemaObj = _getSchemaObj(this, keyRef);
switch (typeof schemaObj) {
case 'object': return schemaObj.validate || this._compile(schemaObj);
case 'string': return this.getSchema(schemaObj);
case 'undefined': return _getSchemaFragment(this, keyRef);
}
}
function _getSchemaFragment(self, ref) {
var res = resolve.schema.call(self, { schema: {} }, ref);
if (res) {
var schema = res.schema
, root = res.root
, baseId = res.baseId;
var v = compileSchema.call(self, schema, root, undefined, baseId);
self._fragments[ref] = new SchemaObject({
ref: ref,
fragment: true,
schema: schema,
root: root,
baseId: baseId,
validate: v
});
return v;
}
}
function _getSchemaObj(self, keyRef) {
keyRef = resolve.normalizeId(keyRef);
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}
/**
* Remove cached schema(s).
* If no parameter is passed all schemas but meta-schemas are removed.
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
* @this Ajv
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
* @return {Ajv} this for method chaining
*/
function removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
_removeAllSchemas(this, this._schemas, schemaKeyRef);
_removeAllSchemas(this, this._refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case 'undefined':
_removeAllSchemas(this, this._schemas);
_removeAllSchemas(this, this._refs);
this._cache.clear();
return this;
case 'string':
var schemaObj = _getSchemaObj(this, schemaKeyRef);
if (schemaObj) this._cache.del(schemaObj.cacheKey);
delete this._schemas[schemaKeyRef];
delete this._refs[schemaKeyRef];
return this;
case 'object':
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
this._cache.del(cacheKey);
var id = this._getId(schemaKeyRef);
if (id) {
id = resolve.normalizeId(id);
delete this._schemas[id];
delete this._refs[id];
}
}
return this;
}
function _removeAllSchemas(self, schemas, regex) {
for (var keyRef in schemas) {
var schemaObj = schemas[keyRef];
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
self._cache.del(schemaObj.cacheKey);
delete schemas[keyRef];
}
}
}
/* @this Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
if (typeof schema != 'object' && typeof schema != 'boolean')
throw new Error('schema should be object or boolean');
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schema) : schema;
var cached = this._cache.get(cacheKey);
if (cached) return cached;
shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
var id = resolve.normalizeId(this._getId(schema));
if (id && shouldAddSchema) checkUnique(this, id);
var willValidate = this._opts.validateSchema !== false && !skipValidation;
var recursiveMeta;
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
this.validateSchema(schema, true);
var localRefs = resolve.ids.call(this, schema);
var schemaObj = new SchemaObject({
id: id,
schema: schema,
localRefs: localRefs,
cacheKey: cacheKey,
meta: meta
});
if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
this._cache.put(cacheKey, schemaObj);
if (willValidate && recursiveMeta) this.validateSchema(schema, true);
return schemaObj;
}
/* @this Ajv */
function _compile(schemaObj, root) {
if (schemaObj.compiling) {
schemaObj.validate = callValidate;
callValidate.schema = schemaObj.schema;
callValidate.errors = null;
callValidate.root = root ? root : callValidate;
if (schemaObj.schema.$async === true)
callValidate.$async = true;
return callValidate;
}
schemaObj.compiling = true;
var currentOpts;
if (schemaObj.meta) {
currentOpts = this._opts;
this._opts = this._metaOpts;
}
var v;
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
catch(e) {
delete schemaObj.validate;
throw e;
}
finally {
schemaObj.compiling = false;
if (schemaObj.meta) this._opts = currentOpts;
}
schemaObj.validate = v;
schemaObj.refs = v.refs;
schemaObj.refVal = v.refVal;
schemaObj.root = v.root;
return v;
/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var _validate = schemaObj.validate;
var result = _validate.apply(this, arguments);
callValidate.errors = _validate.errors;
return result;
}
}
function chooseGetId(opts) {
switch (opts.schemaId) {
case 'auto': return _get$IdOrId;
case 'id': return _getId;
default: return _get$Id;
}
}
/* @this Ajv */
function _getId(schema) {
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
return schema.id;
}
/* @this Ajv */
function _get$Id(schema) {
if (schema.id) this.logger.warn('schema id ignored', schema.id);
return schema.$id;
}
function _get$IdOrId(schema) {
if (schema.$id && schema.id && schema.$id != schema.id)
throw new Error('schema $id is different from id');
return schema.$id || schema.id;
}
/**
* Convert array of error message objects to string
* @this Ajv
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {Object} options optional options with properties `separator` and `dataVar`.
* @return {String} human readable string with all errors descriptions
*/
function errorsText(errors, options) {
errors = errors || this.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = options.separator === undefined ? ', ' : options.separator;
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
var text = '';
for (var i=0; i<errors.length; i++) {
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
}
/**
* Add custom format
* @this Ajv
* @param {String} name format name
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
* @return {Ajv} this for method chaining
*/
function addFormat(name, format) {
if (typeof format == 'string') format = new RegExp(format);
this._formats[name] = format;
return this;
}
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = require('./refs/data.json');
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
}
if (self._opts.meta === false) return;
var metaSchema = require('./refs/json-schema-draft-07.json');
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}
function addInitialSchemas(self) {
var optsSchemas = self._opts.schemas;
if (!optsSchemas) return;
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}
function addInitialFormats(self) {
for (var name in self._opts.formats) {
var format = self._opts.formats[name];
self.addFormat(name, format);
}
}
function addInitialKeywords(self) {
for (var name in self._opts.keywords) {
var keyword = self._opts.keywords[name];
self.addKeyword(name, keyword);
}
}
function checkUnique(self, id) {
if (self._schemas[id] || self._refs[id])
throw new Error('schema with key or id "' + id + '" already exists');
}
function getMetaSchemaOptions(self) {
var metaOpts = util.copy(self._opts);
for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
delete metaOpts[META_IGNORE_OPTIONS[i]];
return metaOpts;
}
function setLogger(self) {
var logger = self._opts.logger;
if (logger === false) {
self.logger = {log: noop, warn: noop, error: noop};
} else {
if (logger === undefined) logger = console;
if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
throw new Error('logger must implement log, warn and error methods');
self.logger = logger;
}
}
function noop() {}
var Ajv$1 = /*#__PURE__*/Object.freeze({
__proto__: null
});
const parseErrorSchema$3 = (validationError, validateAllFieldCriteria) => Array.isArray(validationError)
? validationError.reduce((previous, { dataPath, keyword, message }) => {
const path = dataPath.replace(/^\./, '');
return Object.assign(Object.assign({}, previous), (path
? previous[path] && validateAllFieldCriteria
? {
[path]: appendErrors(path, validateAllFieldCriteria, previous, keyword, message),
}
: {
[path]: previous[path] ||
Object.assign({ type: keyword, message }, (validateAllFieldCriteria
? {
types: { [keyword]: message || true },
}
: {})),
}
: {}));
}, {})
: {};
const jsonSchemaResolver = (validationSchema, options = {}) => {
if (!validationSchema || typeof validationSchema !== 'object') {
throw new Error('Invalid AJV schema or validation function');
}
let allErrors = false;
let validate;
const getValidator = (validateAllFieldCriteria) => {
// compile only if necessary. otherwise return the memoized validation function
if (!validate || allErrors !== validateAllFieldCriteria) {
allErrors = validateAllFieldCriteria;
validate = new Ajv$1(Object.assign(Object.assign({}, options.ajvOptions), { async: false, allErrors, validateSchema: true, transpile: undefined })).compile(validationSchema);
}
return validate;
};
// compile the validator right away so there is an exception if the schema is invalid
getValidator(allErrors);
return async (data, _, validateAllFieldCriteria = allErrors) => {
const validate = getValidator(validateAllFieldCriteria);
const valid = validate(data);
const errors = validate.errors;
return valid
? {
values: data,
errors: {},
}
: {
values: {},
errors: transformToNestObject(parseErrorSchema$3(errors, validateAllFieldCriteria)),
};
};
};
export { joiResolver, jsonSchemaResolver, superstructResolver, yupResolver };
//# sourceMappingURL=index.esm.js.map

@@ -256,3 +256,573 @@ import { transformToNestObject, appendErrors } from 'react-hook-form';

export { joiResolver, superstructResolver, yupResolver };
var compileSchema = require('./compile')
, resolve = require('./compile/resolve')
, Cache = require('./cache')
, SchemaObject = require('./compile/schema_obj')
, stableStringify = require('fast-json-stable-stringify')
, formats = require('./compile/formats')
, rules = require('./compile/rules')
, $dataMetaSchema = require('./data')
, util = require('./compile/util');
module.exports = Ajv;
Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;
Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;
Ajv.prototype.compileAsync = require('./compile/async');
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;
var errorClasses = require('./compile/error_classes');
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
var META_SUPPORT_DATA = ['/properties'];
/**
* Creates validator instance.
* Usage: `Ajv(opts)`
* @param {Object} opts optional options
* @return {Object} ajv instance
*/
function Ajv(opts) {
if (!(this instanceof Ajv)) return new Ajv(opts);
opts = this._opts = util.copy(opts) || {};
setLogger(this);
this._schemas = {};
this._refs = {};
this._fragments = {};
this._formats = formats(opts.format);
this._cache = opts.cache || new Cache;
this._loadingSchemas = {};
this._compilations = [];
this.RULES = rules();
this._getId = chooseGetId(opts);
opts.loopRequired = opts.loopRequired || Infinity;
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
if (opts.serialize === undefined) opts.serialize = stableStringify;
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
if (opts.keywords) addInitialKeywords(this);
addDefaultMetaSchema(this);
if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
addInitialSchemas(this);
}
/**
* Validate data using schema
* Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
* @this Ajv
* @param {String|Object} schemaKeyRef key, ref or schema object
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
function validate(schemaKeyRef, data) {
var v;
if (typeof schemaKeyRef == 'string') {
v = this.getSchema(schemaKeyRef);
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
} else {
var schemaObj = this._addSchema(schemaKeyRef);
v = schemaObj.validate || this._compile(schemaObj);
}
var valid = v(data);
if (v.$async !== true) this.errors = v.errors;
return valid;
}
/**
* Create validating function for passed schema.
* @this Ajv
* @param {Object} schema schema object
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
* @return {Function} validating function
*/
function compile(schema, _meta) {
var schemaObj = this._addSchema(schema, undefined, _meta);
return schemaObj.validate || this._compile(schemaObj);
}
/**
* Adds schema to the instance.
* @this Ajv
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
* @return {Ajv} this for method chaining
*/
function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
return this;
}
var id = this._getId(schema);
if (id !== undefined && typeof id != 'string')
throw new Error('schema id must be string');
key = resolve.normalizeId(key || id);
checkUnique(this, key);
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
return this;
}
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @this Ajv
* @param {Object} schema schema object
* @param {String} key optional schema key
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
* @return {Ajv} this for method chaining
*/
function addMetaSchema(schema, key, skipValidation) {
this.addSchema(schema, key, skipValidation, true);
return this;
}
/**
* Validate schema
* @this Ajv
* @param {Object} schema schema to validate
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
* @return {Boolean} true if schema is valid
*/
function validateSchema(schema, throwOrLogError) {
var $schema = schema.$schema;
if ($schema !== undefined && typeof $schema != 'string')
throw new Error('$schema must be a string');
$schema = $schema || this._opts.defaultMeta || defaultMeta(this);
if (!$schema) {
this.logger.warn('meta-schema not available');
this.errors = null;
return true;
}
var valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
var message = 'schema is invalid: ' + this.errorsText();
if (this._opts.validateSchema == 'log') this.logger.error(message);
else throw new Error(message);
}
return valid;
}
function defaultMeta(self) {
var meta = self._opts.meta;
self._opts.defaultMeta = typeof meta == 'object'
? self._getId(meta) || meta
: self.getSchema(META_SCHEMA_ID)
? META_SCHEMA_ID
: undefined;
return self._opts.defaultMeta;
}
/**
* Get compiled schema from the instance by `key` or `ref`.
* @this Ajv
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
* @return {Function} schema validating function (with property `schema`).
*/
function getSchema(keyRef) {
var schemaObj = _getSchemaObj(this, keyRef);
switch (typeof schemaObj) {
case 'object': return schemaObj.validate || this._compile(schemaObj);
case 'string': return this.getSchema(schemaObj);
case 'undefined': return _getSchemaFragment(this, keyRef);
}
}
function _getSchemaFragment(self, ref) {
var res = resolve.schema.call(self, { schema: {} }, ref);
if (res) {
var schema = res.schema
, root = res.root
, baseId = res.baseId;
var v = compileSchema.call(self, schema, root, undefined, baseId);
self._fragments[ref] = new SchemaObject({
ref: ref,
fragment: true,
schema: schema,
root: root,
baseId: baseId,
validate: v
});
return v;
}
}
function _getSchemaObj(self, keyRef) {
keyRef = resolve.normalizeId(keyRef);
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}
/**
* Remove cached schema(s).
* If no parameter is passed all schemas but meta-schemas are removed.
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
* @this Ajv
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
* @return {Ajv} this for method chaining
*/
function removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
_removeAllSchemas(this, this._schemas, schemaKeyRef);
_removeAllSchemas(this, this._refs, schemaKeyRef);
return this;
}
switch (typeof schemaKeyRef) {
case 'undefined':
_removeAllSchemas(this, this._schemas);
_removeAllSchemas(this, this._refs);
this._cache.clear();
return this;
case 'string':
var schemaObj = _getSchemaObj(this, schemaKeyRef);
if (schemaObj) this._cache.del(schemaObj.cacheKey);
delete this._schemas[schemaKeyRef];
delete this._refs[schemaKeyRef];
return this;
case 'object':
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
this._cache.del(cacheKey);
var id = this._getId(schemaKeyRef);
if (id) {
id = resolve.normalizeId(id);
delete this._schemas[id];
delete this._refs[id];
}
}
return this;
}
function _removeAllSchemas(self, schemas, regex) {
for (var keyRef in schemas) {
var schemaObj = schemas[keyRef];
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
self._cache.del(schemaObj.cacheKey);
delete schemas[keyRef];
}
}
}
/* @this Ajv */
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
if (typeof schema != 'object' && typeof schema != 'boolean')
throw new Error('schema should be object or boolean');
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schema) : schema;
var cached = this._cache.get(cacheKey);
if (cached) return cached;
shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
var id = resolve.normalizeId(this._getId(schema));
if (id && shouldAddSchema) checkUnique(this, id);
var willValidate = this._opts.validateSchema !== false && !skipValidation;
var recursiveMeta;
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
this.validateSchema(schema, true);
var localRefs = resolve.ids.call(this, schema);
var schemaObj = new SchemaObject({
id: id,
schema: schema,
localRefs: localRefs,
cacheKey: cacheKey,
meta: meta
});
if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
this._cache.put(cacheKey, schemaObj);
if (willValidate && recursiveMeta) this.validateSchema(schema, true);
return schemaObj;
}
/* @this Ajv */
function _compile(schemaObj, root) {
if (schemaObj.compiling) {
schemaObj.validate = callValidate;
callValidate.schema = schemaObj.schema;
callValidate.errors = null;
callValidate.root = root ? root : callValidate;
if (schemaObj.schema.$async === true)
callValidate.$async = true;
return callValidate;
}
schemaObj.compiling = true;
var currentOpts;
if (schemaObj.meta) {
currentOpts = this._opts;
this._opts = this._metaOpts;
}
var v;
try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
catch(e) {
delete schemaObj.validate;
throw e;
}
finally {
schemaObj.compiling = false;
if (schemaObj.meta) this._opts = currentOpts;
}
schemaObj.validate = v;
schemaObj.refs = v.refs;
schemaObj.refVal = v.refVal;
schemaObj.root = v.root;
return v;
/* @this {*} - custom context, see passContext option */
function callValidate() {
/* jshint validthis: true */
var _validate = schemaObj.validate;
var result = _validate.apply(this, arguments);
callValidate.errors = _validate.errors;
return result;
}
}
function chooseGetId(opts) {
switch (opts.schemaId) {
case 'auto': return _get$IdOrId;
case 'id': return _getId;
default: return _get$Id;
}
}
/* @this Ajv */
function _getId(schema) {
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
return schema.id;
}
/* @this Ajv */
function _get$Id(schema) {
if (schema.id) this.logger.warn('schema id ignored', schema.id);
return schema.$id;
}
function _get$IdOrId(schema) {
if (schema.$id && schema.id && schema.$id != schema.id)
throw new Error('schema $id is different from id');
return schema.$id || schema.id;
}
/**
* Convert array of error message objects to string
* @this Ajv
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {Object} options optional options with properties `separator` and `dataVar`.
* @return {String} human readable string with all errors descriptions
*/
function errorsText(errors, options) {
errors = errors || this.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = options.separator === undefined ? ', ' : options.separator;
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
var text = '';
for (var i=0; i<errors.length; i++) {
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
}
/**
* Add custom format
* @this Ajv
* @param {String} name format name
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
* @return {Ajv} this for method chaining
*/
function addFormat(name, format) {
if (typeof format == 'string') format = new RegExp(format);
this._formats[name] = format;
return this;
}
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = require('./refs/data.json');
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
}
if (self._opts.meta === false) return;
var metaSchema = require('./refs/json-schema-draft-07.json');
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}
function addInitialSchemas(self) {
var optsSchemas = self._opts.schemas;
if (!optsSchemas) return;
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
}
function addInitialFormats(self) {
for (var name in self._opts.formats) {
var format = self._opts.formats[name];
self.addFormat(name, format);
}
}
function addInitialKeywords(self) {
for (var name in self._opts.keywords) {
var keyword = self._opts.keywords[name];
self.addKeyword(name, keyword);
}
}
function checkUnique(self, id) {
if (self._schemas[id] || self._refs[id])
throw new Error('schema with key or id "' + id + '" already exists');
}
function getMetaSchemaOptions(self) {
var metaOpts = util.copy(self._opts);
for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
delete metaOpts[META_IGNORE_OPTIONS[i]];
return metaOpts;
}
function setLogger(self) {
var logger = self._opts.logger;
if (logger === false) {
self.logger = {log: noop, warn: noop, error: noop};
} else {
if (logger === undefined) logger = console;
if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
throw new Error('logger must implement log, warn and error methods');
self.logger = logger;
}
}
function noop() {}
var Ajv$1 = /*#__PURE__*/Object.freeze({
__proto__: null
});
var parseErrorSchema$3 = function (validationError, validateAllFieldCriteria) {
return Array.isArray(validationError)
? validationError.reduce(function (previous, _a) {
var _b, _c, _d;
var dataPath = _a.dataPath, keyword = _a.keyword, message = _a.message;
var path = dataPath.replace(/^\./, '');
return __assign(__assign({}, previous), (path
? previous[path] && validateAllFieldCriteria
? (_b = {},
_b[path] = appendErrors(path, validateAllFieldCriteria, previous, keyword, message),
_b) : (_c = {},
_c[path] = previous[path] ||
__assign({ type: keyword, message: message }, (validateAllFieldCriteria
? {
types: (_d = {}, _d[keyword] = message || true, _d),
}
: {})),
_c)
: {}));
}, {})
: {};
};
var jsonSchemaResolver = function (validationSchema, options) {
if (options === void 0) { options = {}; }
if (!validationSchema || typeof validationSchema !== 'object') {
throw new Error('Invalid AJV schema or validation function');
}
var allErrors = false;
var validate;
var getValidator = function (validateAllFieldCriteria) {
// compile only if necessary. otherwise return the memoized validation function
if (!validate || allErrors !== validateAllFieldCriteria) {
allErrors = validateAllFieldCriteria;
validate = new Ajv$1(__assign(__assign({}, options.ajvOptions), { async: false, allErrors: allErrors, validateSchema: true, transpile: undefined })).compile(validationSchema);
}
return validate;
};
// compile the validator right away so there is an exception if the schema is invalid
getValidator(allErrors);
return function (data, _, validateAllFieldCriteria) {
if (validateAllFieldCriteria === void 0) { validateAllFieldCriteria = allErrors; }
return __awaiter(void 0, void 0, void 0, function () {
var validate, valid, errors;
return __generator(this, function (_a) {
validate = getValidator(validateAllFieldCriteria);
valid = validate(data);
errors = validate.errors;
return [2 /*return*/, valid
? {
values: data,
errors: {},
}
: {
values: {},
errors: transformToNestObject(parseErrorSchema$3(errors, validateAllFieldCriteria)),
}];
});
});
};
};
export { joiResolver, jsonSchemaResolver, superstructResolver, yupResolver };
//# sourceMappingURL=index.ie11.js.map
{
"name": "@hookform/resolvers",
"version": "0.2.0-beta.2",
"version": "0.2.0-beta.3",
"description": "React Hook Form validation resolvers: Yup, Joi, Superstruct and etc.",

@@ -39,2 +39,4 @@ "main": "dist/index.js",

"yup",
"json-schema",
"ajv",
"joi",

@@ -62,5 +64,7 @@ "sperstruct",

"@types/jest": "^26.0.0",
"@types/json-schema": "^7.0.6",
"@types/yup": "^0.29.3",
"@typescript-eslint/eslint-plugin": "^3.2.0",
"@typescript-eslint/parser": "^3.2.0",
"ajv": "^6.12.4",
"eslint": "^7.2.0",

@@ -67,0 +71,0 @@ "eslint-config-prettier": "^6.11.0",

@@ -61,3 +61,3 @@ <div align="center">

return (
<form onSubmit={handleSubmit(d => console.log(d))}>
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input name="name" ref={register} />

@@ -79,10 +79,10 @@ <input name="age" type="number" ref={register} />

```typescript jsx
import React from "react";
import { useForm } from "react-hook-form";
import { superstructResolver } from "@hookform/resolvers";
import { struct } from "superstruct";
import React from 'react';
import { useForm } from 'react-hook-form';
import { superstructResolver } from '@hookform/resolvers';
import { struct } from 'superstruct';
const schema = struct({
name: "string",
age: "number",
name: 'string',
age: 'number',
});

@@ -113,6 +113,6 @@

```typescript jsx
import React from "react";
import { useForm } from "react-hook-form";
import { joiResolver } from "@hookform/resolvers";
import Joi from "@hapi/joi";
import React from 'react';
import { useForm } from 'react-hook-form';
import { joiResolver } from '@hookform/resolvers';
import Joi from '@hapi/joi';

@@ -139,2 +139,52 @@ const schema = Joi.object({

### [Json Schema](http://json-schema.org/)
The most standard way to validate JSON (implemented by [ajv](https://github.com/ajv-validator/ajv))
[![npm](https://img.shields.io/bundlephobia/minzip/ajv@6.12.4?style=for-the-badge)](https://bundlephobia.com/result?p=ajv@6.12.4)
```typescript jsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { JSONSchema4, JSONSchema6, JSONSchema7 } from 'json-schema';
import { jsonSchemaResolver } from '@hookform/resolvers';
type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7;
const schema: JSONSchema = {
type: 'object',
properties: {
name: {
type: 'string',
pattern: '[a-zA-Z]',
minLength: 3,
},
age: {
type: 'integer',
minimum: 0,
},
email: {
type: 'string',
format: 'email',
},
},
};
const App = () => {
const { register, handleSubmit } = useForm({
resolver: jsonSchemaResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input name="name" ref={register} />
<input name="age" type="number" ref={register} />
<input name="email" type="email" ref={register} />
<input type="submit" />
</form>
);
};
```
## Backers

@@ -145,3 +195,3 @@

<a href="https://opencollective.com/react-hook-form#backers">
<img src="https://opencollective.com/react-hook-form/backers.svg?width=950" />
<img src="https://opencollective.com/react-hook-form/backers.svg?width=950" alt="Backers" />
</a>

@@ -154,3 +204,3 @@

<a href="https://github.com/react-hook-form/react-hook-form/graphs/contributors">
<img src="https://opencollective.com/react-hook-form/organizations.svg?width=950" />
<img src="https://opencollective.com/react-hook-form/organizations.svg?width=950" alt="Contributor Organizations" />
</a>

@@ -163,3 +213,3 @@

<a href="https://github.com/react-hook-form/react-hook-form/graphs/contributors">
<img src="https://opencollective.com/react-hook-form/contributors.svg?width=950" />
<img src="https://opencollective.com/react-hook-form/contributors.svg?width=950" alt="Contributors" />
</a>

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc