@hookform/resolvers 2.0.0-beta.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +19 -10
  2. package/dist/index.d.ts +1 -1
  3. package/dist/resolvers.js +1 -1
  4. package/dist/resolvers.js.map +1 -1
  5. package/dist/resolvers.mjs +1 -1
  6. package/dist/resolvers.modern.js +1 -1
  7. package/dist/resolvers.modern.js.map +1 -1
  8. package/dist/resolvers.module.js +1 -1
  9. package/dist/resolvers.module.js.map +1 -1
  10. package/dist/resolvers.umd.js +1 -1
  11. package/dist/resolvers.umd.js.map +1 -1
  12. package/dist/toNestError.d.ts +2 -0
  13. package/joi/dist/joi.js +1 -1
  14. package/joi/dist/joi.js.map +1 -1
  15. package/joi/dist/joi.mjs +1 -1
  16. package/joi/dist/joi.modern.js +1 -1
  17. package/joi/dist/joi.modern.js.map +1 -1
  18. package/joi/dist/joi.module.js +1 -1
  19. package/joi/dist/joi.module.js.map +1 -1
  20. package/joi/dist/joi.umd.js +1 -1
  21. package/joi/dist/joi.umd.js.map +1 -1
  22. package/joi/dist/types.d.ts +1 -1
  23. package/joi/src/__tests__/__fixtures__/data.ts +76 -0
  24. package/joi/src/__tests__/__snapshots__/joi.ts.snap +118 -0
  25. package/joi/src/__tests__/joi.ts +35 -88
  26. package/joi/src/joi.ts +47 -64
  27. package/joi/src/types.ts +1 -1
  28. package/package.json +14 -15
  29. package/superstruct/dist/superstruct.js +1 -1
  30. package/superstruct/dist/superstruct.js.map +1 -1
  31. package/superstruct/dist/superstruct.mjs +1 -1
  32. package/superstruct/dist/superstruct.modern.js +1 -1
  33. package/superstruct/dist/superstruct.modern.js.map +1 -1
  34. package/superstruct/dist/superstruct.module.js +1 -1
  35. package/superstruct/dist/superstruct.module.js.map +1 -1
  36. package/superstruct/dist/superstruct.umd.js +1 -1
  37. package/superstruct/dist/superstruct.umd.js.map +1 -1
  38. package/superstruct/dist/types.d.ts +1 -1
  39. package/superstruct/package.json +2 -1
  40. package/superstruct/src/__tests__/__fixtures__/data.ts +73 -0
  41. package/superstruct/src/__tests__/__snapshots__/superstruct.ts.snap +26 -56
  42. package/superstruct/src/__tests__/superstruct.ts +6 -65
  43. package/superstruct/src/superstruct.ts +20 -53
  44. package/superstruct/src/types.ts +1 -1
  45. package/vest/dist/vest.js +1 -1
  46. package/vest/dist/vest.js.map +1 -1
  47. package/vest/dist/vest.mjs +1 -1
  48. package/vest/dist/vest.modern.js +1 -1
  49. package/vest/dist/vest.modern.js.map +1 -1
  50. package/vest/dist/vest.module.js +1 -1
  51. package/vest/dist/vest.module.js.map +1 -1
  52. package/vest/dist/vest.umd.js +1 -1
  53. package/vest/dist/vest.umd.js.map +1 -1
  54. package/vest/package.json +3 -1
  55. package/vest/src/__tests__/__fixtures__/data.ts +67 -0
  56. package/vest/src/__tests__/__snapshots__/vest.ts.snap +28 -0
  57. package/vest/src/__tests__/vest.ts +22 -95
  58. package/vest/src/types.ts +1 -1
  59. package/vest/src/vest.ts +31 -42
  60. package/yup/dist/types.d.ts +4 -3
  61. package/yup/dist/yup.js +1 -1
  62. package/yup/dist/yup.js.map +1 -1
  63. package/yup/dist/yup.mjs +1 -1
  64. package/yup/dist/yup.modern.js +1 -1
  65. package/yup/dist/yup.modern.js.map +1 -1
  66. package/yup/dist/yup.module.js +1 -1
  67. package/yup/dist/yup.module.js.map +1 -1
  68. package/yup/dist/yup.umd.js +1 -1
  69. package/yup/dist/yup.umd.js.map +1 -1
  70. package/yup/package.json +2 -1
  71. package/yup/src/__tests__/__fixtures__/data.ts +65 -0
  72. package/yup/src/__tests__/__snapshots__/yup.ts.snap +99 -13
  73. package/yup/src/__tests__/yup.ts +23 -97
  74. package/yup/src/types.ts +6 -3
  75. package/yup/src/yup.ts +30 -60
  76. package/zod/dist/types.d.ts +1 -1
  77. package/zod/dist/zod.js +1 -1
  78. package/zod/dist/zod.js.map +1 -1
  79. package/zod/dist/zod.mjs +1 -1
  80. package/zod/dist/zod.modern.js +1 -1
  81. package/zod/dist/zod.modern.js.map +1 -1
  82. package/zod/dist/zod.module.js +1 -1
  83. package/zod/dist/zod.module.js.map +1 -1
  84. package/zod/dist/zod.umd.js +1 -1
  85. package/zod/dist/zod.umd.js.map +1 -1
  86. package/zod/src/__tests__/__fixtures__/data.ts +68 -0
  87. package/zod/src/__tests__/__snapshots__/zod.ts.snap +146 -0
  88. package/zod/src/__tests__/zod.ts +19 -79
  89. package/zod/src/types.ts +1 -1
  90. package/zod/src/zod.ts +45 -50
  91. package/dist/convertArrayToPathName.d.ts +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"superstruct.js","sources":["../../node_modules/superstruct/lib/index.es.js","../src/superstruct.ts"],"sourcesContent":["/**\n * A `StructFailure` represents a single specific failure in validation.\n */\n\n/**\n * `StructError` objects are thrown (or returned) when validation fails.\n *\n * Validation logic is design to exit early for maximum performance. The error\n * represents the first error encountered during validation. For more detail,\n * the `error.failures` property is a generator function that can be run to\n * continue validation and receive all the failures in the data.\n */\nclass StructError extends TypeError {\n constructor(failure, failures) {\n let cached;\n const {\n message,\n ...rest\n } = failure;\n const {\n path\n } = failure;\n const msg = path.length === 0 ? message : \"At path: \" + path.join('.') + \" -- \" + message;\n super(msg);\n Object.assign(this, rest);\n this.name = this.constructor.name;\n\n this.failures = () => {\n var _cached;\n\n return (_cached = cached) != null ? _cached : cached = [failure, ...failures()];\n };\n }\n\n}\n\n/**\n * Check if a value is an iterator.\n */\nfunction isIterable(x) {\n return isObject(x) && typeof x[Symbol.iterator] === 'function';\n}\n/**\n * Check if a value is a plain object.\n */\n\n\nfunction isObject(x) {\n return typeof x === 'object' && x != null;\n}\n/**\n * Check if a value is a plain object.\n */\n\nfunction isPlainObject(x) {\n if (Object.prototype.toString.call(x) !== '[object Object]') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(x);\n return prototype === null || prototype === Object.prototype;\n}\n/**\n * Return a value as a printable string.\n */\n\nfunction print(value) {\n return typeof value === 'string' ? JSON.stringify(value) : \"\" + value;\n}\n/**\n * Shifts (removes and returns) the first value from the `input` iterator.\n * Like `Array.prototype.shift()` but for an `Iterator`.\n */\n\nfunction shiftIterator(input) {\n const {\n done,\n value\n } = input.next();\n return done ? undefined : value;\n}\n/**\n * Convert a single validation result to a failure.\n */\n\nfunction toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n } else if (result === false) {\n result = {};\n } else if (typeof result === 'string') {\n result = {\n message: result\n };\n }\n\n const {\n path,\n branch\n } = context;\n const {\n type\n } = struct;\n const {\n refinement,\n message = \"Expected a value of type `\" + type + \"`\" + (refinement ? \" with refinement `\" + refinement + \"`\" : '') + \", but received: `\" + print(value) + \"`\"\n } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message\n };\n}\n/**\n * Convert a validation result to an iterable of failures.\n */\n\nfunction* toFailures(result, context, struct, value) {\n if (!isIterable(result)) {\n result = [result];\n }\n\n for (const r of result) {\n const failure = toFailure(r, context, struct, value);\n\n if (failure) {\n yield failure;\n }\n }\n}\n/**\n * Check a value against a struct, traversing deeply into nested values, and\n * returning an iterator of failures or success.\n */\n\nfunction* run(value, struct, options = {}) {\n const {\n path = [],\n branch = [value],\n coerce = false\n } = options;\n const ctx = {\n path,\n branch\n };\n\n if (coerce) {\n value = struct.coercer(value, ctx);\n }\n\n let valid = true;\n\n for (const failure of struct.validator(value, ctx)) {\n valid = false;\n yield [failure, undefined];\n }\n\n for (let [k, v, s] of struct.entries(value, ctx)) {\n const ts = run(v, s, {\n path: k === undefined ? path : [...path, k],\n branch: k === undefined ? branch : [...branch, v],\n coerce\n });\n\n for (const t of ts) {\n if (t[0]) {\n valid = false;\n yield [t[0], undefined];\n } else if (coerce) {\n v = t[1];\n\n if (k === undefined) {\n value = v;\n } else if (value instanceof Map) {\n value.set(k, v);\n } else if (value instanceof Set) {\n value.add(v);\n } else if (isObject(value)) {\n value[k] = v;\n }\n }\n }\n }\n\n if (valid) {\n for (const failure of struct.refiner(value, ctx)) {\n valid = false;\n yield [failure, undefined];\n }\n }\n\n if (valid) {\n yield [undefined, value];\n }\n}\n\nfunction assign(...Structs) {\n const schemas = Structs.map(s => s.schema);\n const schema = Object.assign({}, ...schemas);\n return object(schema);\n}\n/**\n * Define a new struct type with a custom validation function.\n */\n\nfunction define(name, validator) {\n return new Struct({\n type: name,\n schema: null,\n validator\n });\n}\n/**\n * Create a struct with dynamic validation logic.\n *\n * The callback will receive the value currently being validated, and must\n * return a struct object to validate it with. This can be useful to model\n * validation logic that changes based on its input.\n */\n\nfunction dynamic(fn) {\n return new Struct({\n type: 'dynamic',\n schema: null,\n\n *entries(value, ctx) {\n const struct = fn(value, ctx);\n yield* struct.entries(value, ctx);\n },\n\n validator(value, ctx) {\n const struct = fn(value, ctx);\n return struct.validator(value, ctx);\n },\n\n coercer(value, ctx) {\n const struct = fn(value, ctx);\n return struct.coercer(value, ctx);\n }\n\n });\n}\n/**\n * Create a struct with lazily evaluated validation logic.\n *\n * The first time validation is run with the struct, the callback will be called\n * and must return a struct object to use. This is useful for cases where you\n * want to have self-referential structs for nested data structures to avoid a\n * circular definition problem.\n */\n\nfunction lazy(fn) {\n let struct;\n return new Struct({\n type: 'lazy',\n schema: null,\n\n *entries(value, ctx) {\n var _struct;\n\n (_struct = struct) != null ? _struct : struct = fn();\n yield* struct.entries(value, ctx);\n },\n\n validator(value, ctx) {\n var _struct2;\n\n (_struct2 = struct) != null ? _struct2 : struct = fn();\n return struct.validator(value, ctx);\n },\n\n coercer(value, ctx) {\n var _struct3;\n\n (_struct3 = struct) != null ? _struct3 : struct = fn();\n return struct.coercer(value, ctx);\n }\n\n });\n}\n/**\n * Create a new struct based on an existing object struct, but excluding\n * specific properties.\n *\n * Like TypeScript's `Omit` utility.\n */\n\nfunction omit(struct, keys) {\n const {\n schema\n } = struct;\n const subschema = { ...schema\n };\n\n for (const key of keys) {\n delete subschema[key];\n }\n\n return object(subschema);\n}\n/**\n * Create a new struct based on an existing object struct, but with all of its\n * properties allowed to be `undefined`.\n *\n * Like TypeScript's `Partial` utility.\n */\n\nfunction partial(struct) {\n const schema = struct instanceof Struct ? { ...struct.schema\n } : { ...struct\n };\n\n for (const key in schema) {\n schema[key] = optional(schema[key]);\n }\n\n return object(schema);\n}\n/**\n * Create a new struct based on an existing object struct, but only including\n * specific properties.\n *\n * Like TypeScript's `Pick` utility.\n */\n\nfunction pick(struct, keys) {\n const {\n schema\n } = struct;\n const subschema = {};\n\n for (const key of keys) {\n subschema[key] = schema[key];\n }\n\n return object(subschema);\n}\n/**\n * Define a new struct type with a custom validation function.\n *\n * @deprecated This function has been renamed to `define`.\n */\n\nfunction struct(name, validator) {\n console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.');\n return define(name, validator);\n}\n\n/**\n * Ensure that any value passes validation.\n */\n\nfunction any() {\n return define('any', () => true);\n}\nfunction array(Element) {\n return new Struct({\n type: 'array',\n schema: Element,\n\n *entries(value) {\n if (Element && Array.isArray(value)) {\n for (const [i, v] of value.entries()) {\n yield [i, v, Element];\n }\n }\n },\n\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n\n validator(value) {\n return Array.isArray(value) || \"Expected an array value, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a boolean.\n */\n\nfunction boolean() {\n return define('boolean', value => {\n return typeof value === 'boolean';\n });\n}\n/**\n * Ensure that a value is a valid `Date`.\n *\n * Note: this also ensures that the value is *not* an invalid `Date` object,\n * which can occur when parsing a date fails but still returns a `Date`.\n */\n\nfunction date() {\n return define('date', value => {\n return value instanceof Date && !isNaN(value.getTime()) || \"Expected a valid `Date` object, but received: \" + print(value);\n });\n}\nfunction enums(values) {\n const schema = {};\n const description = values.map(v => print(v)).join();\n\n for (const key of values) {\n schema[key] = key;\n }\n\n return new Struct({\n type: 'enums',\n schema,\n\n validator(value) {\n return values.includes(value) || \"Expected one of `\" + description + \"`, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a function.\n */\n\nfunction func() {\n return define('func', value => {\n return typeof value === 'function' || \"Expected a function, but received: \" + print(value);\n });\n}\n/**\n * Ensure that a value is an instance of a specific class.\n */\n\nfunction instance(Class) {\n return define('instance', value => {\n return value instanceof Class || \"Expected a `\" + Class.name + \"` instance, but received: \" + print(value);\n });\n}\n/**\n * Ensure that a value is an integer.\n */\n\nfunction integer() {\n return define('integer', value => {\n return typeof value === 'number' && !isNaN(value) && Number.isInteger(value) || \"Expected an integer, but received: \" + print(value);\n });\n}\nfunction intersection(Structs) {\n return new Struct({\n type: 'intersection',\n schema: null,\n\n *entries(value, ctx) {\n for (const S of Structs) {\n yield* S.entries(value, ctx);\n }\n },\n\n *validator(value, ctx) {\n for (const S of Structs) {\n yield* S.validator(value, ctx);\n }\n },\n\n *refiner(value, ctx) {\n for (const S of Structs) {\n yield* S.refiner(value, ctx);\n }\n }\n\n });\n}\nfunction literal(constant) {\n const description = print(constant);\n return define('literal', value => {\n return value === constant || \"Expected the literal `\" + description + \"`, but received: \" + print(value);\n });\n}\nfunction map(Key, Value) {\n return new Struct({\n type: 'map',\n schema: null,\n\n *entries(value) {\n if (Key && Value && value instanceof Map) {\n for (const [k, v] of value.entries()) {\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n\n coercer(value) {\n return value instanceof Map ? new Map(value) : value;\n },\n\n validator(value) {\n return value instanceof Map || \"Expected a `Map` object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that no value ever passes validation.\n */\n\nfunction never() {\n return define('never', () => false);\n}\n/**\n * Augment an existing struct to allow `null` values.\n */\n\nfunction nullable(struct) {\n return new Struct({ ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx)\n });\n}\n/**\n * Ensure that a value is a number.\n */\n\nfunction number() {\n return define('number', value => {\n return typeof value === 'number' && !isNaN(value) || \"Expected a number, but received: \" + print(value);\n });\n}\nfunction object(schema) {\n const knowns = schema ? Object.keys(schema) : [];\n const Never = never();\n return new Struct({\n type: 'object',\n schema: schema ? schema : null,\n\n *entries(value) {\n if (schema && isObject(value)) {\n const unknowns = new Set(Object.keys(value));\n\n for (const key of knowns) {\n unknowns.delete(key);\n yield [key, value[key], schema[key]];\n }\n\n for (const key of unknowns) {\n yield [key, value[key], Never];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n },\n\n coercer(value) {\n return isObject(value) ? { ...value\n } : value;\n }\n\n });\n}\n/**\n * Augment a struct to allow `undefined` values.\n */\n\nfunction optional(struct) {\n return new Struct({ ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx)\n });\n}\n/**\n * Ensure that a value is an object with keys and values of specific types, but\n * without ensuring any specific shape of properties.\n *\n * Like TypeScript's `Record` utility.\n */\n\nfunction record(Key, Value) {\n return new Struct({\n type: 'record',\n schema: null,\n\n *entries(value) {\n if (isObject(value)) {\n for (const k in value) {\n const v = value[k];\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a `RegExp`.\n *\n * Note: this does not test the value against the regular expression! For that\n * you need to use the `pattern()` refinement.\n */\n\nfunction regexp() {\n return define('regexp', value => {\n return value instanceof RegExp;\n });\n}\nfunction set(Element) {\n return new Struct({\n type: 'set',\n schema: null,\n\n *entries(value) {\n if (Element && value instanceof Set) {\n for (const v of value) {\n yield [v, v, Element];\n }\n }\n },\n\n coercer(value) {\n return value instanceof Set ? new Set(value) : value;\n },\n\n validator(value) {\n return value instanceof Set || \"Expected a `Set` object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a string.\n */\n\nfunction string() {\n return define('string', value => {\n return typeof value === 'string' || \"Expected a string, but received: \" + print(value);\n });\n}\nfunction tuple(Elements) {\n const Never = never();\n return new Struct({\n type: 'tuple',\n schema: null,\n\n *entries(value) {\n if (Array.isArray(value)) {\n const length = Math.max(Elements.length, value.length);\n\n for (let i = 0; i < length; i++) {\n yield [i, value[i], Elements[i] || Never];\n }\n }\n },\n\n validator(value) {\n return Array.isArray(value) || \"Expected an array, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value has a set of known properties of specific types.\n *\n * Note: Unrecognized properties are allowed and untouched. This is similar to\n * how TypeScript's structural typing works.\n */\n\nfunction type(schema) {\n const keys = Object.keys(schema);\n return new Struct({\n type: 'type',\n schema,\n\n *entries(value) {\n if (isObject(value)) {\n for (const k of keys) {\n yield [k, value[k], schema[k]];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n }\n\n });\n}\nfunction union(Structs) {\n const description = Structs.map(s => s.type).join(' | ');\n return new Struct({\n type: 'union',\n schema: null,\n\n validator(value, ctx) {\n const failures = [];\n\n for (const S of Structs) {\n const [...tuples] = run(value, S, ctx);\n const [first] = tuples;\n\n if (!first[0]) {\n return [];\n } else {\n for (const [failure] of tuples) {\n if (failure) {\n failures.push(failure);\n }\n }\n }\n }\n\n return [\"Expected the value to satisfy a union of `\" + description + \"`, but received: \" + print(value), ...failures];\n }\n\n });\n}\n/**\n * Ensure that any value passes validation, without widening its type to `any`.\n */\n\nfunction unknown() {\n return define('unknown', () => true);\n}\n\n/**\n * Augment a `Struct` to add an additional coercion step to its input.\n *\n * This allows you to transform input data before validating it, to increase the\n * likelihood that it passes validation—for example for default values, parsing\n * different formats, etc.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction coerce(struct, condition, coercer) {\n return new Struct({ ...struct,\n coercer: (value, ctx) => {\n return is(value, condition) ? struct.coercer(coercer(value, ctx), ctx) : struct.coercer(value, ctx);\n }\n });\n}\n/**\n * Augment a struct to replace `undefined` values with a default.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction defaulted(struct, fallback, options = {}) {\n return coerce(struct, unknown(), x => {\n const f = typeof fallback === 'function' ? fallback() : fallback;\n\n if (x === undefined) {\n return f;\n }\n\n if (!options.strict && isPlainObject(x) && isPlainObject(f)) {\n const ret = { ...x\n };\n let changed = false;\n\n for (const key in f) {\n if (ret[key] === undefined) {\n ret[key] = f[key];\n changed = true;\n }\n }\n\n if (changed) {\n return ret;\n }\n }\n\n return x;\n });\n}\n/**\n * Augment a struct to mask its input to only properties defined in the struct.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction masked(struct) {\n return coerce(struct, unknown(), x => {\n if (typeof struct.schema !== 'object' || struct.schema == null || typeof x !== 'object' || x == null) {\n return x;\n } else {\n const ret = {};\n\n for (const key in struct.schema) {\n if (key in x) {\n ret[key] = x[key];\n }\n }\n\n return ret;\n }\n });\n}\n/**\n * Augment a struct to trim string inputs.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction trimmed(struct) {\n return coerce(struct, string(), x => x.trim());\n}\n\n/**\n * `Struct` objects encapsulate the validation logic for a specific type of\n * values. Once constructed, you use the `assert`, `is` or `validate` helpers to\n * validate unknown input data against the struct.\n */\n\nclass Struct {\n constructor(props) {\n const {\n type,\n schema,\n validator,\n refiner,\n coercer = value => value,\n entries = function* () {}\n } = props;\n this.type = type;\n this.schema = schema;\n this.entries = entries;\n this.coercer = coercer;\n\n if (validator) {\n this.validator = (value, context) => {\n const result = validator(value, context);\n return toFailures(result, context, this, value);\n };\n } else {\n this.validator = () => [];\n }\n\n if (refiner) {\n this.refiner = (value, context) => {\n const result = refiner(value, context);\n return toFailures(result, context, this, value);\n };\n } else {\n this.refiner = () => [];\n }\n }\n /**\n * Assert that a value passes the struct's validation, throwing if it doesn't.\n */\n\n\n assert(value) {\n return assert(value, this);\n }\n /**\n * Create a value with the struct's coercion logic, then validate it.\n */\n\n\n create(value) {\n return create(value, this);\n }\n /**\n * Check if a value passes the struct's validation.\n */\n\n\n is(value) {\n return is(value, this);\n }\n /**\n * Mask a value, coercing and validating it, but returning only the subset of\n * properties defined by the struct's schema.\n */\n\n\n mask(value) {\n return mask(value, this);\n }\n /**\n * Validate a value with the struct's validation logic, returning a tuple\n * representing the result.\n *\n * You may optionally pass `true` for the `withCoercion` argument to coerce\n * the value before attempting to validate it. If you do, the result will\n * contain the coerced result when successful.\n */\n\n\n validate(value, options = {}) {\n return validate(value, this, options);\n }\n\n}\n/**\n * Assert that a value passes a struct, throwing if it doesn't.\n */\n\nfunction assert(value, struct) {\n const result = validate(value, struct);\n\n if (result[0]) {\n throw result[0];\n }\n}\n/**\n * Create a value with the coercion logic of struct and validate it.\n */\n\nfunction create(value, struct) {\n const result = validate(value, struct, {\n coerce: true\n });\n\n if (result[0]) {\n throw result[0];\n } else {\n return result[1];\n }\n}\n/**\n * Mask a value, returning only the subset of properties defined by a struct.\n */\n\nfunction mask(value, struct) {\n const M = masked(struct);\n const ret = create(value, M);\n return ret;\n}\n/**\n * Check if a value passes a struct.\n */\n\nfunction is(value, struct) {\n const result = validate(value, struct);\n return !result[0];\n}\n/**\n * Validate a value against a struct, returning an error if invalid, or the\n * value (with potential coercion) if valid.\n */\n\nfunction validate(value, struct, options = {}) {\n const tuples = run(value, struct, options);\n const tuple = shiftIterator(tuples);\n\n if (tuple[0]) {\n const error = new StructError(tuple[0], function* () {\n for (const t of tuples) {\n if (t[0]) {\n yield t[0];\n }\n }\n });\n return [error, undefined];\n } else {\n const v = tuple[1];\n return [undefined, v];\n }\n}\n\n/**\n * Ensure that a string, array, map, or set is empty.\n */\n\nfunction empty(struct) {\n const expected = \"Expected an empty \" + struct.type;\n return refine(struct, 'empty', value => {\n if (value instanceof Map || value instanceof Set) {\n const {\n size\n } = value;\n return size === 0 || expected + \" but received one with a size of `\" + size + \"`\";\n } else {\n const {\n length\n } = value;\n return length === 0 || expected + \" but received one with a length of `\" + length + \"`\";\n }\n });\n}\n/**\n * Ensure that a number or date is below a threshold.\n */\n\nfunction max(struct, threshold, options = {}) {\n const {\n exclusive\n } = options;\n return refine(struct, 'max', value => {\n return exclusive ? value < threshold : value <= threshold || \"Expected a \" + struct.type + \" greater than \" + (exclusive ? '' : 'or equal to ') + threshold + \" but received `\" + value + \"`\";\n });\n}\n/**\n * Ensure that a number or date is above a threshold.\n */\n\nfunction min(struct, threshold, options = {}) {\n const {\n exclusive\n } = options;\n return refine(struct, 'min', value => {\n return exclusive ? value > threshold : value >= threshold || \"Expected a \" + struct.type + \" greater than \" + (exclusive ? '' : 'or equal to ') + threshold + \" but received `\" + value + \"`\";\n });\n}\n/**\n * Ensure that a string matches a regular expression.\n */\n\nfunction pattern(struct, regexp) {\n return refine(struct, 'pattern', value => {\n return regexp.test(value) || \"Expected a \" + struct.type + \" matching `/\" + regexp.source + \"/` but received \\\"\" + value + \"\\\"\";\n });\n}\n/**\n * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`.\n */\n\nfunction size(struct, min, max = min) {\n const expected = \"Expected a \" + struct.type;\n const of = min === max ? \"of `\" + min + \"`\" : \"between `\" + min + \"` and `\" + max + \"`\";\n return refine(struct, 'size', value => {\n if (typeof value === 'number' || value instanceof Date) {\n return min <= value && value <= max || expected + \" \" + of + \" but received `\" + value + \"`\";\n } else if (value instanceof Map || value instanceof Set) {\n const {\n size\n } = value;\n return min <= size && size <= max || expected + \" with a size \" + of + \" but received one with a size of `\" + size + \"`\";\n } else {\n const {\n length\n } = value;\n return min <= length && length <= max || expected + \" with a length \" + of + \" but received one with a length of `\" + length + \"`\";\n }\n });\n}\n/**\n * Augment a `Struct` to add an additional refinement to the validation.\n *\n * The refiner function is guaranteed to receive a value of the struct's type,\n * because the struct's existing validation will already have passed. This\n * allows you to layer additional validation on top of existing structs.\n */\n\nfunction refine(struct, name, refiner) {\n return new Struct({ ...struct,\n\n *refiner(value, ctx) {\n yield* struct.refiner(value, ctx);\n const result = refiner(value, ctx);\n const failures = toFailures(result, ctx, struct, value);\n\n for (const failure of failures) {\n yield { ...failure,\n refinement: name\n };\n }\n }\n\n });\n}\n\nexport { Struct, StructError, any, array, assert, assign, boolean, coerce, create, date, defaulted, define, dynamic, empty, enums, func, instance, integer, intersection, is, lazy, literal, map, mask, masked, max, min, never, nullable, number, object, omit, optional, partial, pattern, pick, record, refine, regexp, set, size, string, struct, trimmed, tuple, type, union, unknown, validate };\n//# sourceMappingURL=index.es.js.map\n","import { appendErrors, transformToNestObject } from 'react-hook-form';\nimport { StructError, validate } from 'superstruct';\n// @ts-expect-error maybe fixed after the first publish ?\nimport { convertArrayToPathName } from '@hookform/resolvers';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n error: StructError,\n validateAllFieldCriteria: boolean,\n) =>\n error\n .failures()\n .reduce((previous: Record<string, any>, { path, message = '', type }) => {\n const currentPath = convertArrayToPathName(path);\n return {\n ...previous,\n ...(path\n ? previous[currentPath] && validateAllFieldCriteria\n ? {\n [currentPath]: appendErrors(\n currentPath,\n validateAllFieldCriteria,\n previous,\n type || '',\n message,\n ),\n }\n : {\n [currentPath]: previous[currentPath] || {\n message,\n type,\n ...(validateAllFieldCriteria\n ? {\n types: { [type || '']: message || true },\n }\n : {}),\n },\n }\n : {}),\n };\n }, {});\n\nexport const superstructResolver: Resolver = (schema, options) => async (\n values,\n _context,\n { criteriaMode },\n) => {\n const [errors, result] = validate(values, schema, options);\n\n if (errors != null) {\n return {\n values: {},\n errors: transformToNestObject(\n parseErrorSchema(errors, criteriaMode === 'all'),\n ),\n };\n }\n\n return {\n values: result,\n errors: {},\n };\n};\n"],"names":["StructError","TypeError","[object Object]","failure","failures","cached","message","rest","path","super","length","join","Object","assign","this","name","constructor","_cached","run","value","struct","options","branch","coerce","ctx","coercer","valid","validator","undefined","k","v","s","entries","ts","t","Map","set","Set","add","x","refiner","validate","tuples","tuple","input","done","next","shiftIterator","schema","values","_context","error","validateAllFieldCriteria","criteriaMode","errors","result","transformToNestObject","reduce","previous","type","currentPath","convertArrayToPathName","appendErrors","types"],"mappings":"iRAYA,MAAMA,UAAoBC,UACxBC,YAAYC,EAASC,GACnB,IAAIC,EACJ,MAAMC,QACJA,KACGC,GACDJ,GACEK,KACJA,GACEL,EAEJM,MAD4B,IAAhBD,EAAKE,OAAeJ,EAAU,YAAcE,EAAKG,KAAK,KAAO,OAASL,GAElFM,OAAOC,OAAOC,KAAMP,GACpBO,KAAKC,KAAOD,KAAKE,YAAYD,KAE7BD,KAAKV,SAAW,KACd,IAAIa,EAEJ,OAA6B,OAArBA,EAAUZ,GAAkBY,EAAUZ,EAAS,CAACF,KAAYC,OA8G1E,SAAUc,EAAIC,EAAOC,EAAQC,EAAU,IACrC,MAAMb,KACJA,EAAO,GAAEc,OACTA,EAAS,CAACH,GAAMI,OAChBA,GAAS,GACPF,EACEG,EAAM,CACVhB,KAAAA,EACAc,OAAAA,GAGEC,IACFJ,EAAQC,EAAOK,QAAQN,EAAOK,IAGhC,IAAIE,GAAQ,EAEZ,IAAK,MAAMvB,KAAWiB,EAAOO,UAAUR,EAAOK,GAC5CE,GAAQ,OACF,CAACvB,OAASyB,GAGlB,IAAK,IAAKC,EAAGC,EAAGC,KAAMX,EAAOY,QAAQb,EAAOK,GAAM,CAChD,MAAMS,EAAKf,EAAIY,EAAGC,EAAG,CACnBvB,UAAYoB,IAANC,EAAkBrB,EAAO,IAAIA,EAAMqB,GACzCP,YAAcM,IAANC,EAAkBP,EAAS,IAAIA,EAAQQ,GAC/CP,OAAAA,IAGF,IAAK,MAAMW,KAAKD,EACVC,EAAE,IACJR,GAAQ,OACF,CAACQ,EAAE,QAAIN,IACJL,IACTO,EAAII,EAAE,QAEIN,IAANC,EACFV,EAAQW,EACCX,aAAiBgB,IAC1BhB,EAAMiB,IAAIP,EAAGC,GACJX,aAAiBkB,IAC1BlB,EAAMmB,IAAIR,GArIE,iBADJS,EAuIUpB,IAtIW,MAALoB,IAuIxBpB,EAAMU,GAAKC,IAxIrB,IAAkBS,EA8IhB,GAAIb,EACF,IAAK,MAAMvB,KAAWiB,EAAOoB,QAAQrB,EAAOK,GAC1CE,GAAQ,OACF,CAACvB,OAASyB,GAIhBF,SACI,MAACE,EAAWT,IAqvBtB,SAASsB,EAAStB,EAAOC,EAAQC,EAAU,IACzC,MAAMqB,EAASxB,EAAIC,EAAOC,EAAQC,GAC5BsB,EAl3BR,SAAuBC,GACrB,MAAMC,KACJA,EAAI1B,MACJA,GACEyB,EAAME,OACV,OAAOD,OAAOjB,EAAYT,EA62BZ4B,CAAcL,GAE5B,OAAIC,EAAM,GAQD,CAPO,IAAI3C,EAAY2C,EAAM,GAAI,YACtC,IAAK,MAAMT,KAAKQ,EACVR,EAAE,WACEA,EAAE,WAICN,GAGR,MAACA,EADEe,EAAM,gCC95ByB,SAACK,EAAQ3B,mBACpD4B,EACAC,SArCAC,EACAC,EAqCEC,IAAAA,uBAEuBZ,EAASQ,EAAQD,EAAQ3B,GAA3CiC,OAAQC,OAEf,uBAAc,MAAVD,EACK,CACLL,OAAQ,GACRK,OAAQE,yBA7CZL,EA8CuBG,EA7CvBF,EA6CgD,QAAjBC,EA3C/BF,EACG/C,WACAqD,OAAO,SAACC,eAAiClD,IAAAA,SAAMF,QAAAA,aAAU,KAAIqD,IAAAA,KACtDC,EAAcC,yBAAuBrD,GAC3C,YACKkD,EACClD,EACAkD,EAASE,IAAgBR,UAEpBQ,GAAcE,eACbF,EACAR,EACAM,EACAC,GAAQ,GACRrD,cAIDsD,GAAcF,EAASE,OACtBtD,QAAAA,EACAqD,KAAAA,GACIP,EACA,CACEW,cAAUJ,GAAQ,IAAKrD,IAAW,MAEpC,OAGV,KAEL,OAkBE,CACL2C,OAAQM,EACRD,OAAQ,KAlBiC"}
1
+ {"version":3,"file":"superstruct.js","sources":["../src/superstruct.ts"],"sourcesContent":["import { FieldError } from 'react-hook-form';\nimport { toNestError } from '@hookform/resolvers';\n\nimport { StructError, validate } from 'superstruct';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (error: StructError) =>\n error.failures().reduce<Record<string, FieldError>>(\n (previous, error) =>\n (previous[error.path.join('.')] = {\n message: error.message,\n type: error.type,\n }) && previous,\n {},\n );\n\nexport const superstructResolver: Resolver = (schema, resolverOptions) => (\n values,\n _,\n options,\n) => {\n const result = validate(values, schema, resolverOptions);\n\n return {\n values: result[1] || {},\n errors: result[0]\n ? toNestError(parseErrorSchema(result[0]), options.fields)\n : {},\n };\n};\n"],"names":["schema","resolverOptions","values","_","options","error","result","validate","errors","toNestError","failures","reduce","previous","path","join","message","type","fields"],"mappings":"0FAgB6C,SAACA,EAAQC,mBACpDC,EACAC,EACAC,GAEA,IAfwBC,EAelBC,EAASC,WAASL,EAAQF,EAAQC,GAExC,MAAO,CACLC,OAAQI,EAAO,IAAM,GACrBE,OAAQF,EAAO,GACXG,eApBkBJ,EAoBWC,EAAO,GAnB1CD,EAAMK,WAAWC,OACf,SAACC,EAAUP,UACRO,EAASP,EAAMQ,KAAKC,KAAK,MAAQ,CAChCC,QAASV,EAAMU,QACfC,KAAMX,EAAMW,QACRJ,GACR,KAa6CR,EAAQa,QACjD"}
@@ -1,2 +1,2 @@
1
- import{transformToNestObject as r,appendErrors as e}from"react-hook-form";import{convertArrayToPathName as o}from"@hookform/resolvers";function t(){return(t=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var o=arguments[e];for(var t in o)Object.prototype.hasOwnProperty.call(o,t)&&(r[t]=o[t])}return r}).apply(this,arguments)}class n extends TypeError{constructor(r,e){let o;const{message:t,...n}=r,{path:i}=r;super(0===i.length?t:"At path: "+i.join(".")+" -- "+t),Object.assign(this,n),this.name=this.constructor.name,this.failures=()=>{var t;return null!=(t=o)?t:o=[r,...e()]}}}function*i(r,e,o={}){const{path:t=[],branch:n=[r],coerce:s=!1}=o,c={path:t,branch:n};s&&(r=e.coercer(r,c));let a=!0;for(const o of e.validator(r,c))a=!1,yield[o,void 0];for(let[o,l,u]of e.entries(r,c)){const e=i(l,u,{path:void 0===o?t:[...t,o],branch:void 0===o?n:[...n,l],coerce:s});for(const t of e)t[0]?(a=!1,yield[t[0],void 0]):s&&(l=t[1],void 0===o?r=l:r instanceof Map?r.set(o,l):r instanceof Set?r.add(l):"object"==typeof(f=r)&&null!=f&&(r[o]=l))}var f;if(a)for(const o of e.refiner(r,c))a=!1,yield[o,void 0];a&&(yield[void 0,r])}function s(r,e,o={}){const t=i(r,e,o),s=function(r){const{done:e,value:o}=r.next();return e?void 0:o}(t);return s[0]?[new n(s[0],function*(){for(const r of t)r[0]&&(yield r[0])}),void 0]:[void 0,s[1]]}var c=function(n,i){return function(c,a,f){var l,u,v=f.criteriaMode;try{var d=s(c,n,i),p=d[0],h=d[1];return Promise.resolve(null!=p?{values:{},errors:r((l=p,u="all"===v,l.failures().reduce(function(r,n){var i,s,c,a=n.path,f=n.message,l=void 0===f?"":f,v=n.type,d=o(a);return t({},r,a?r[d]&&u?((i={})[d]=e(d,u,r,v||"",l),i):((c={})[d]=r[d]||t({message:l,type:v},u?{types:(s={},s[v||""]=l||!0,s)}:{}),c):{})},{})))}:{values:h,errors:{}})}catch(r){return Promise.reject(r)}}};export{c as superstructResolver};
1
+ import{toNestError as r}from"@hookform/resolvers";import{validate as e}from"superstruct";var o=function(o,t){return function(s,u,n){var f,i=e(s,o,t);return{values:i[1]||{},errors:i[0]?r((f=i[0],f.failures().reduce(function(r,e){return(r[e.path.join(".")]={message:e.message,type:e.type})&&r},{})),n.fields):{}}}};export{o as superstructResolver};
2
2
  //# sourceMappingURL=superstruct.module.js.map
@@ -1,2 +1,2 @@
1
- import{transformToNestObject as o,appendErrors as e}from"react-hook-form";import{convertArrayToPathName as r}from"@hookform/resolvers";function t(){return(t=Object.assign||function(o){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var t in r)Object.prototype.hasOwnProperty.call(r,t)&&(o[t]=r[t])}return o}).apply(this,arguments)}class n extends TypeError{constructor(o,e){let r;const{message:t,...n}=o,{path:s}=o;super(0===s.length?t:"At path: "+s.join(".")+" -- "+t),Object.assign(this,n),this.name=this.constructor.name,this.failures=()=>{var t;return null!=(t=r)?t:r=[o,...e()]}}}function*s(o,e,r={}){const{path:t=[],branch:n=[o],coerce:c=!1}=r,i={path:t,branch:n};c&&(o=e.coercer(o,i));let a=!0;for(const r of e.validator(o,i))a=!1,yield[r,void 0];for(let[r,l,u]of e.entries(o,i)){const e=s(l,u,{path:void 0===r?t:[...t,r],branch:void 0===r?n:[...n,l],coerce:c});for(const t of e)t[0]?(a=!1,yield[t[0],void 0]):c&&(l=t[1],void 0===r?o=l:o instanceof Map?o.set(r,l):o instanceof Set?o.add(l):"object"==typeof(f=o)&&null!=f&&(o[r]=l))}var f;if(a)for(const r of e.refiner(o,i))a=!1,yield[r,void 0];a&&(yield[void 0,o])}function c(o,e,r={}){const t=s(o,e,r),c=function(o){const{done:e,value:r}=o.next();return e?void 0:r}(t);return c[0]?[new n(c[0],function*(){for(const o of t)o[0]&&(yield o[0])}),void 0]:[void 0,c[1]]}const i=(n,s)=>async(i,a,{criteriaMode:f})=>{const[l,u]=c(i,n,s);return null!=l?{values:{},errors:o((d=l,p="all"===f,d.failures().reduce((o,{path:n,message:s="",type:c})=>{const i=r(n);return t({},o,n?o[i]&&p?{[i]:e(i,p,o,c||"",s)}:{[i]:o[i]||t({message:s,type:c},p?{types:{[c||""]:s||!0}}:{})}:{})},{})))}:{values:u,errors:{}};var d,p};export{i as superstructResolver};
1
+ import{toNestError as r}from"@hookform/resolvers";import{validate as e}from"superstruct";const s=(s,o)=>(t,m,p)=>{const a=e(t,s,o);return{values:a[1]||{},errors:a[0]?r((u=a[0],u.failures().reduce((r,e)=>(r[e.path.join(".")]={message:e.message,type:e.type})&&r,{})),p.fields):{}};var u};export{s as superstructResolver};
2
2
  //# sourceMappingURL=superstruct.modern.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"superstruct.modern.js","sources":["../../node_modules/superstruct/lib/index.es.js","../src/superstruct.ts"],"sourcesContent":["/**\n * A `StructFailure` represents a single specific failure in validation.\n */\n\n/**\n * `StructError` objects are thrown (or returned) when validation fails.\n *\n * Validation logic is design to exit early for maximum performance. The error\n * represents the first error encountered during validation. For more detail,\n * the `error.failures` property is a generator function that can be run to\n * continue validation and receive all the failures in the data.\n */\nclass StructError extends TypeError {\n constructor(failure, failures) {\n let cached;\n const {\n message,\n ...rest\n } = failure;\n const {\n path\n } = failure;\n const msg = path.length === 0 ? message : \"At path: \" + path.join('.') + \" -- \" + message;\n super(msg);\n Object.assign(this, rest);\n this.name = this.constructor.name;\n\n this.failures = () => {\n var _cached;\n\n return (_cached = cached) != null ? _cached : cached = [failure, ...failures()];\n };\n }\n\n}\n\n/**\n * Check if a value is an iterator.\n */\nfunction isIterable(x) {\n return isObject(x) && typeof x[Symbol.iterator] === 'function';\n}\n/**\n * Check if a value is a plain object.\n */\n\n\nfunction isObject(x) {\n return typeof x === 'object' && x != null;\n}\n/**\n * Check if a value is a plain object.\n */\n\nfunction isPlainObject(x) {\n if (Object.prototype.toString.call(x) !== '[object Object]') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(x);\n return prototype === null || prototype === Object.prototype;\n}\n/**\n * Return a value as a printable string.\n */\n\nfunction print(value) {\n return typeof value === 'string' ? JSON.stringify(value) : \"\" + value;\n}\n/**\n * Shifts (removes and returns) the first value from the `input` iterator.\n * Like `Array.prototype.shift()` but for an `Iterator`.\n */\n\nfunction shiftIterator(input) {\n const {\n done,\n value\n } = input.next();\n return done ? undefined : value;\n}\n/**\n * Convert a single validation result to a failure.\n */\n\nfunction toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n } else if (result === false) {\n result = {};\n } else if (typeof result === 'string') {\n result = {\n message: result\n };\n }\n\n const {\n path,\n branch\n } = context;\n const {\n type\n } = struct;\n const {\n refinement,\n message = \"Expected a value of type `\" + type + \"`\" + (refinement ? \" with refinement `\" + refinement + \"`\" : '') + \", but received: `\" + print(value) + \"`\"\n } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message\n };\n}\n/**\n * Convert a validation result to an iterable of failures.\n */\n\nfunction* toFailures(result, context, struct, value) {\n if (!isIterable(result)) {\n result = [result];\n }\n\n for (const r of result) {\n const failure = toFailure(r, context, struct, value);\n\n if (failure) {\n yield failure;\n }\n }\n}\n/**\n * Check a value against a struct, traversing deeply into nested values, and\n * returning an iterator of failures or success.\n */\n\nfunction* run(value, struct, options = {}) {\n const {\n path = [],\n branch = [value],\n coerce = false\n } = options;\n const ctx = {\n path,\n branch\n };\n\n if (coerce) {\n value = struct.coercer(value, ctx);\n }\n\n let valid = true;\n\n for (const failure of struct.validator(value, ctx)) {\n valid = false;\n yield [failure, undefined];\n }\n\n for (let [k, v, s] of struct.entries(value, ctx)) {\n const ts = run(v, s, {\n path: k === undefined ? path : [...path, k],\n branch: k === undefined ? branch : [...branch, v],\n coerce\n });\n\n for (const t of ts) {\n if (t[0]) {\n valid = false;\n yield [t[0], undefined];\n } else if (coerce) {\n v = t[1];\n\n if (k === undefined) {\n value = v;\n } else if (value instanceof Map) {\n value.set(k, v);\n } else if (value instanceof Set) {\n value.add(v);\n } else if (isObject(value)) {\n value[k] = v;\n }\n }\n }\n }\n\n if (valid) {\n for (const failure of struct.refiner(value, ctx)) {\n valid = false;\n yield [failure, undefined];\n }\n }\n\n if (valid) {\n yield [undefined, value];\n }\n}\n\nfunction assign(...Structs) {\n const schemas = Structs.map(s => s.schema);\n const schema = Object.assign({}, ...schemas);\n return object(schema);\n}\n/**\n * Define a new struct type with a custom validation function.\n */\n\nfunction define(name, validator) {\n return new Struct({\n type: name,\n schema: null,\n validator\n });\n}\n/**\n * Create a struct with dynamic validation logic.\n *\n * The callback will receive the value currently being validated, and must\n * return a struct object to validate it with. This can be useful to model\n * validation logic that changes based on its input.\n */\n\nfunction dynamic(fn) {\n return new Struct({\n type: 'dynamic',\n schema: null,\n\n *entries(value, ctx) {\n const struct = fn(value, ctx);\n yield* struct.entries(value, ctx);\n },\n\n validator(value, ctx) {\n const struct = fn(value, ctx);\n return struct.validator(value, ctx);\n },\n\n coercer(value, ctx) {\n const struct = fn(value, ctx);\n return struct.coercer(value, ctx);\n }\n\n });\n}\n/**\n * Create a struct with lazily evaluated validation logic.\n *\n * The first time validation is run with the struct, the callback will be called\n * and must return a struct object to use. This is useful for cases where you\n * want to have self-referential structs for nested data structures to avoid a\n * circular definition problem.\n */\n\nfunction lazy(fn) {\n let struct;\n return new Struct({\n type: 'lazy',\n schema: null,\n\n *entries(value, ctx) {\n var _struct;\n\n (_struct = struct) != null ? _struct : struct = fn();\n yield* struct.entries(value, ctx);\n },\n\n validator(value, ctx) {\n var _struct2;\n\n (_struct2 = struct) != null ? _struct2 : struct = fn();\n return struct.validator(value, ctx);\n },\n\n coercer(value, ctx) {\n var _struct3;\n\n (_struct3 = struct) != null ? _struct3 : struct = fn();\n return struct.coercer(value, ctx);\n }\n\n });\n}\n/**\n * Create a new struct based on an existing object struct, but excluding\n * specific properties.\n *\n * Like TypeScript's `Omit` utility.\n */\n\nfunction omit(struct, keys) {\n const {\n schema\n } = struct;\n const subschema = { ...schema\n };\n\n for (const key of keys) {\n delete subschema[key];\n }\n\n return object(subschema);\n}\n/**\n * Create a new struct based on an existing object struct, but with all of its\n * properties allowed to be `undefined`.\n *\n * Like TypeScript's `Partial` utility.\n */\n\nfunction partial(struct) {\n const schema = struct instanceof Struct ? { ...struct.schema\n } : { ...struct\n };\n\n for (const key in schema) {\n schema[key] = optional(schema[key]);\n }\n\n return object(schema);\n}\n/**\n * Create a new struct based on an existing object struct, but only including\n * specific properties.\n *\n * Like TypeScript's `Pick` utility.\n */\n\nfunction pick(struct, keys) {\n const {\n schema\n } = struct;\n const subschema = {};\n\n for (const key of keys) {\n subschema[key] = schema[key];\n }\n\n return object(subschema);\n}\n/**\n * Define a new struct type with a custom validation function.\n *\n * @deprecated This function has been renamed to `define`.\n */\n\nfunction struct(name, validator) {\n console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.');\n return define(name, validator);\n}\n\n/**\n * Ensure that any value passes validation.\n */\n\nfunction any() {\n return define('any', () => true);\n}\nfunction array(Element) {\n return new Struct({\n type: 'array',\n schema: Element,\n\n *entries(value) {\n if (Element && Array.isArray(value)) {\n for (const [i, v] of value.entries()) {\n yield [i, v, Element];\n }\n }\n },\n\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n\n validator(value) {\n return Array.isArray(value) || \"Expected an array value, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a boolean.\n */\n\nfunction boolean() {\n return define('boolean', value => {\n return typeof value === 'boolean';\n });\n}\n/**\n * Ensure that a value is a valid `Date`.\n *\n * Note: this also ensures that the value is *not* an invalid `Date` object,\n * which can occur when parsing a date fails but still returns a `Date`.\n */\n\nfunction date() {\n return define('date', value => {\n return value instanceof Date && !isNaN(value.getTime()) || \"Expected a valid `Date` object, but received: \" + print(value);\n });\n}\nfunction enums(values) {\n const schema = {};\n const description = values.map(v => print(v)).join();\n\n for (const key of values) {\n schema[key] = key;\n }\n\n return new Struct({\n type: 'enums',\n schema,\n\n validator(value) {\n return values.includes(value) || \"Expected one of `\" + description + \"`, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a function.\n */\n\nfunction func() {\n return define('func', value => {\n return typeof value === 'function' || \"Expected a function, but received: \" + print(value);\n });\n}\n/**\n * Ensure that a value is an instance of a specific class.\n */\n\nfunction instance(Class) {\n return define('instance', value => {\n return value instanceof Class || \"Expected a `\" + Class.name + \"` instance, but received: \" + print(value);\n });\n}\n/**\n * Ensure that a value is an integer.\n */\n\nfunction integer() {\n return define('integer', value => {\n return typeof value === 'number' && !isNaN(value) && Number.isInteger(value) || \"Expected an integer, but received: \" + print(value);\n });\n}\nfunction intersection(Structs) {\n return new Struct({\n type: 'intersection',\n schema: null,\n\n *entries(value, ctx) {\n for (const S of Structs) {\n yield* S.entries(value, ctx);\n }\n },\n\n *validator(value, ctx) {\n for (const S of Structs) {\n yield* S.validator(value, ctx);\n }\n },\n\n *refiner(value, ctx) {\n for (const S of Structs) {\n yield* S.refiner(value, ctx);\n }\n }\n\n });\n}\nfunction literal(constant) {\n const description = print(constant);\n return define('literal', value => {\n return value === constant || \"Expected the literal `\" + description + \"`, but received: \" + print(value);\n });\n}\nfunction map(Key, Value) {\n return new Struct({\n type: 'map',\n schema: null,\n\n *entries(value) {\n if (Key && Value && value instanceof Map) {\n for (const [k, v] of value.entries()) {\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n\n coercer(value) {\n return value instanceof Map ? new Map(value) : value;\n },\n\n validator(value) {\n return value instanceof Map || \"Expected a `Map` object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that no value ever passes validation.\n */\n\nfunction never() {\n return define('never', () => false);\n}\n/**\n * Augment an existing struct to allow `null` values.\n */\n\nfunction nullable(struct) {\n return new Struct({ ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx)\n });\n}\n/**\n * Ensure that a value is a number.\n */\n\nfunction number() {\n return define('number', value => {\n return typeof value === 'number' && !isNaN(value) || \"Expected a number, but received: \" + print(value);\n });\n}\nfunction object(schema) {\n const knowns = schema ? Object.keys(schema) : [];\n const Never = never();\n return new Struct({\n type: 'object',\n schema: schema ? schema : null,\n\n *entries(value) {\n if (schema && isObject(value)) {\n const unknowns = new Set(Object.keys(value));\n\n for (const key of knowns) {\n unknowns.delete(key);\n yield [key, value[key], schema[key]];\n }\n\n for (const key of unknowns) {\n yield [key, value[key], Never];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n },\n\n coercer(value) {\n return isObject(value) ? { ...value\n } : value;\n }\n\n });\n}\n/**\n * Augment a struct to allow `undefined` values.\n */\n\nfunction optional(struct) {\n return new Struct({ ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx)\n });\n}\n/**\n * Ensure that a value is an object with keys and values of specific types, but\n * without ensuring any specific shape of properties.\n *\n * Like TypeScript's `Record` utility.\n */\n\nfunction record(Key, Value) {\n return new Struct({\n type: 'record',\n schema: null,\n\n *entries(value) {\n if (isObject(value)) {\n for (const k in value) {\n const v = value[k];\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a `RegExp`.\n *\n * Note: this does not test the value against the regular expression! For that\n * you need to use the `pattern()` refinement.\n */\n\nfunction regexp() {\n return define('regexp', value => {\n return value instanceof RegExp;\n });\n}\nfunction set(Element) {\n return new Struct({\n type: 'set',\n schema: null,\n\n *entries(value) {\n if (Element && value instanceof Set) {\n for (const v of value) {\n yield [v, v, Element];\n }\n }\n },\n\n coercer(value) {\n return value instanceof Set ? new Set(value) : value;\n },\n\n validator(value) {\n return value instanceof Set || \"Expected a `Set` object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a string.\n */\n\nfunction string() {\n return define('string', value => {\n return typeof value === 'string' || \"Expected a string, but received: \" + print(value);\n });\n}\nfunction tuple(Elements) {\n const Never = never();\n return new Struct({\n type: 'tuple',\n schema: null,\n\n *entries(value) {\n if (Array.isArray(value)) {\n const length = Math.max(Elements.length, value.length);\n\n for (let i = 0; i < length; i++) {\n yield [i, value[i], Elements[i] || Never];\n }\n }\n },\n\n validator(value) {\n return Array.isArray(value) || \"Expected an array, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value has a set of known properties of specific types.\n *\n * Note: Unrecognized properties are allowed and untouched. This is similar to\n * how TypeScript's structural typing works.\n */\n\nfunction type(schema) {\n const keys = Object.keys(schema);\n return new Struct({\n type: 'type',\n schema,\n\n *entries(value) {\n if (isObject(value)) {\n for (const k of keys) {\n yield [k, value[k], schema[k]];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n }\n\n });\n}\nfunction union(Structs) {\n const description = Structs.map(s => s.type).join(' | ');\n return new Struct({\n type: 'union',\n schema: null,\n\n validator(value, ctx) {\n const failures = [];\n\n for (const S of Structs) {\n const [...tuples] = run(value, S, ctx);\n const [first] = tuples;\n\n if (!first[0]) {\n return [];\n } else {\n for (const [failure] of tuples) {\n if (failure) {\n failures.push(failure);\n }\n }\n }\n }\n\n return [\"Expected the value to satisfy a union of `\" + description + \"`, but received: \" + print(value), ...failures];\n }\n\n });\n}\n/**\n * Ensure that any value passes validation, without widening its type to `any`.\n */\n\nfunction unknown() {\n return define('unknown', () => true);\n}\n\n/**\n * Augment a `Struct` to add an additional coercion step to its input.\n *\n * This allows you to transform input data before validating it, to increase the\n * likelihood that it passes validation—for example for default values, parsing\n * different formats, etc.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction coerce(struct, condition, coercer) {\n return new Struct({ ...struct,\n coercer: (value, ctx) => {\n return is(value, condition) ? struct.coercer(coercer(value, ctx), ctx) : struct.coercer(value, ctx);\n }\n });\n}\n/**\n * Augment a struct to replace `undefined` values with a default.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction defaulted(struct, fallback, options = {}) {\n return coerce(struct, unknown(), x => {\n const f = typeof fallback === 'function' ? fallback() : fallback;\n\n if (x === undefined) {\n return f;\n }\n\n if (!options.strict && isPlainObject(x) && isPlainObject(f)) {\n const ret = { ...x\n };\n let changed = false;\n\n for (const key in f) {\n if (ret[key] === undefined) {\n ret[key] = f[key];\n changed = true;\n }\n }\n\n if (changed) {\n return ret;\n }\n }\n\n return x;\n });\n}\n/**\n * Augment a struct to mask its input to only properties defined in the struct.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction masked(struct) {\n return coerce(struct, unknown(), x => {\n if (typeof struct.schema !== 'object' || struct.schema == null || typeof x !== 'object' || x == null) {\n return x;\n } else {\n const ret = {};\n\n for (const key in struct.schema) {\n if (key in x) {\n ret[key] = x[key];\n }\n }\n\n return ret;\n }\n });\n}\n/**\n * Augment a struct to trim string inputs.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction trimmed(struct) {\n return coerce(struct, string(), x => x.trim());\n}\n\n/**\n * `Struct` objects encapsulate the validation logic for a specific type of\n * values. Once constructed, you use the `assert`, `is` or `validate` helpers to\n * validate unknown input data against the struct.\n */\n\nclass Struct {\n constructor(props) {\n const {\n type,\n schema,\n validator,\n refiner,\n coercer = value => value,\n entries = function* () {}\n } = props;\n this.type = type;\n this.schema = schema;\n this.entries = entries;\n this.coercer = coercer;\n\n if (validator) {\n this.validator = (value, context) => {\n const result = validator(value, context);\n return toFailures(result, context, this, value);\n };\n } else {\n this.validator = () => [];\n }\n\n if (refiner) {\n this.refiner = (value, context) => {\n const result = refiner(value, context);\n return toFailures(result, context, this, value);\n };\n } else {\n this.refiner = () => [];\n }\n }\n /**\n * Assert that a value passes the struct's validation, throwing if it doesn't.\n */\n\n\n assert(value) {\n return assert(value, this);\n }\n /**\n * Create a value with the struct's coercion logic, then validate it.\n */\n\n\n create(value) {\n return create(value, this);\n }\n /**\n * Check if a value passes the struct's validation.\n */\n\n\n is(value) {\n return is(value, this);\n }\n /**\n * Mask a value, coercing and validating it, but returning only the subset of\n * properties defined by the struct's schema.\n */\n\n\n mask(value) {\n return mask(value, this);\n }\n /**\n * Validate a value with the struct's validation logic, returning a tuple\n * representing the result.\n *\n * You may optionally pass `true` for the `withCoercion` argument to coerce\n * the value before attempting to validate it. If you do, the result will\n * contain the coerced result when successful.\n */\n\n\n validate(value, options = {}) {\n return validate(value, this, options);\n }\n\n}\n/**\n * Assert that a value passes a struct, throwing if it doesn't.\n */\n\nfunction assert(value, struct) {\n const result = validate(value, struct);\n\n if (result[0]) {\n throw result[0];\n }\n}\n/**\n * Create a value with the coercion logic of struct and validate it.\n */\n\nfunction create(value, struct) {\n const result = validate(value, struct, {\n coerce: true\n });\n\n if (result[0]) {\n throw result[0];\n } else {\n return result[1];\n }\n}\n/**\n * Mask a value, returning only the subset of properties defined by a struct.\n */\n\nfunction mask(value, struct) {\n const M = masked(struct);\n const ret = create(value, M);\n return ret;\n}\n/**\n * Check if a value passes a struct.\n */\n\nfunction is(value, struct) {\n const result = validate(value, struct);\n return !result[0];\n}\n/**\n * Validate a value against a struct, returning an error if invalid, or the\n * value (with potential coercion) if valid.\n */\n\nfunction validate(value, struct, options = {}) {\n const tuples = run(value, struct, options);\n const tuple = shiftIterator(tuples);\n\n if (tuple[0]) {\n const error = new StructError(tuple[0], function* () {\n for (const t of tuples) {\n if (t[0]) {\n yield t[0];\n }\n }\n });\n return [error, undefined];\n } else {\n const v = tuple[1];\n return [undefined, v];\n }\n}\n\n/**\n * Ensure that a string, array, map, or set is empty.\n */\n\nfunction empty(struct) {\n const expected = \"Expected an empty \" + struct.type;\n return refine(struct, 'empty', value => {\n if (value instanceof Map || value instanceof Set) {\n const {\n size\n } = value;\n return size === 0 || expected + \" but received one with a size of `\" + size + \"`\";\n } else {\n const {\n length\n } = value;\n return length === 0 || expected + \" but received one with a length of `\" + length + \"`\";\n }\n });\n}\n/**\n * Ensure that a number or date is below a threshold.\n */\n\nfunction max(struct, threshold, options = {}) {\n const {\n exclusive\n } = options;\n return refine(struct, 'max', value => {\n return exclusive ? value < threshold : value <= threshold || \"Expected a \" + struct.type + \" greater than \" + (exclusive ? '' : 'or equal to ') + threshold + \" but received `\" + value + \"`\";\n });\n}\n/**\n * Ensure that a number or date is above a threshold.\n */\n\nfunction min(struct, threshold, options = {}) {\n const {\n exclusive\n } = options;\n return refine(struct, 'min', value => {\n return exclusive ? value > threshold : value >= threshold || \"Expected a \" + struct.type + \" greater than \" + (exclusive ? '' : 'or equal to ') + threshold + \" but received `\" + value + \"`\";\n });\n}\n/**\n * Ensure that a string matches a regular expression.\n */\n\nfunction pattern(struct, regexp) {\n return refine(struct, 'pattern', value => {\n return regexp.test(value) || \"Expected a \" + struct.type + \" matching `/\" + regexp.source + \"/` but received \\\"\" + value + \"\\\"\";\n });\n}\n/**\n * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`.\n */\n\nfunction size(struct, min, max = min) {\n const expected = \"Expected a \" + struct.type;\n const of = min === max ? \"of `\" + min + \"`\" : \"between `\" + min + \"` and `\" + max + \"`\";\n return refine(struct, 'size', value => {\n if (typeof value === 'number' || value instanceof Date) {\n return min <= value && value <= max || expected + \" \" + of + \" but received `\" + value + \"`\";\n } else if (value instanceof Map || value instanceof Set) {\n const {\n size\n } = value;\n return min <= size && size <= max || expected + \" with a size \" + of + \" but received one with a size of `\" + size + \"`\";\n } else {\n const {\n length\n } = value;\n return min <= length && length <= max || expected + \" with a length \" + of + \" but received one with a length of `\" + length + \"`\";\n }\n });\n}\n/**\n * Augment a `Struct` to add an additional refinement to the validation.\n *\n * The refiner function is guaranteed to receive a value of the struct's type,\n * because the struct's existing validation will already have passed. This\n * allows you to layer additional validation on top of existing structs.\n */\n\nfunction refine(struct, name, refiner) {\n return new Struct({ ...struct,\n\n *refiner(value, ctx) {\n yield* struct.refiner(value, ctx);\n const result = refiner(value, ctx);\n const failures = toFailures(result, ctx, struct, value);\n\n for (const failure of failures) {\n yield { ...failure,\n refinement: name\n };\n }\n }\n\n });\n}\n\nexport { Struct, StructError, any, array, assert, assign, boolean, coerce, create, date, defaulted, define, dynamic, empty, enums, func, instance, integer, intersection, is, lazy, literal, map, mask, masked, max, min, never, nullable, number, object, omit, optional, partial, pattern, pick, record, refine, regexp, set, size, string, struct, trimmed, tuple, type, union, unknown, validate };\n//# sourceMappingURL=index.es.js.map\n","import { appendErrors, transformToNestObject } from 'react-hook-form';\nimport { StructError, validate } from 'superstruct';\n// @ts-expect-error maybe fixed after the first publish ?\nimport { convertArrayToPathName } from '@hookform/resolvers';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n error: StructError,\n validateAllFieldCriteria: boolean,\n) =>\n error\n .failures()\n .reduce((previous: Record<string, any>, { path, message = '', type }) => {\n const currentPath = convertArrayToPathName(path);\n return {\n ...previous,\n ...(path\n ? previous[currentPath] && validateAllFieldCriteria\n ? {\n [currentPath]: appendErrors(\n currentPath,\n validateAllFieldCriteria,\n previous,\n type || '',\n message,\n ),\n }\n : {\n [currentPath]: previous[currentPath] || {\n message,\n type,\n ...(validateAllFieldCriteria\n ? {\n types: { [type || '']: message || true },\n }\n : {}),\n },\n }\n : {}),\n };\n }, {});\n\nexport const superstructResolver: Resolver = (schema, options) => async (\n values,\n _context,\n { criteriaMode },\n) => {\n const [errors, result] = validate(values, schema, options);\n\n if (errors != null) {\n return {\n values: {},\n errors: transformToNestObject(\n parseErrorSchema(errors, criteriaMode === 'all'),\n ),\n };\n }\n\n return {\n values: result,\n errors: {},\n };\n};\n"],"names":["StructError","TypeError","[object Object]","failure","failures","cached","message","rest","path","super","length","join","Object","assign","this","name","constructor","_cached","run","value","struct","options","branch","coerce","ctx","coercer","valid","validator","undefined","k","v","s","entries","ts","t","Map","set","Set","add","x","refiner","validate","tuples","tuple","input","done","next","shiftIterator","superstructResolver","schema","async","values","_context","criteriaMode","errors","result","transformToNestObject","error","validateAllFieldCriteria","reduce","previous","type","currentPath","convertArrayToPathName","appendErrors","types"],"mappings":"sVAYA,MAAMA,UAAoBC,UACxBC,YAAYC,EAASC,GACnB,IAAIC,EACJ,MAAMC,QACJA,KACGC,GACDJ,GACEK,KACJA,GACEL,EAEJM,MAD4B,IAAhBD,EAAKE,OAAeJ,EAAU,YAAcE,EAAKG,KAAK,KAAO,OAASL,GAElFM,OAAOC,OAAOC,KAAMP,GACpBO,KAAKC,KAAOD,KAAKE,YAAYD,KAE7BD,KAAKV,SAAW,KACd,IAAIa,EAEJ,OAA6B,OAArBA,EAAUZ,GAAkBY,EAAUZ,EAAS,CAACF,KAAYC,OA8G1E,SAAUc,EAAIC,EAAOC,EAAQC,EAAU,IACrC,MAAMb,KACJA,EAAO,GAAEc,OACTA,EAAS,CAACH,GAAMI,OAChBA,GAAS,GACPF,EACEG,EAAM,CACVhB,KAAAA,EACAc,OAAAA,GAGEC,IACFJ,EAAQC,EAAOK,QAAQN,EAAOK,IAGhC,IAAIE,GAAQ,EAEZ,IAAK,MAAMvB,KAAWiB,EAAOO,UAAUR,EAAOK,GAC5CE,GAAQ,OACF,CAACvB,OAASyB,GAGlB,IAAK,IAAKC,EAAGC,EAAGC,KAAMX,EAAOY,QAAQb,EAAOK,GAAM,CAChD,MAAMS,EAAKf,EAAIY,EAAGC,EAAG,CACnBvB,UAAYoB,IAANC,EAAkBrB,EAAO,IAAIA,EAAMqB,GACzCP,YAAcM,IAANC,EAAkBP,EAAS,IAAIA,EAAQQ,GAC/CP,OAAAA,IAGF,IAAK,MAAMW,KAAKD,EACVC,EAAE,IACJR,GAAQ,OACF,CAACQ,EAAE,QAAIN,IACJL,IACTO,EAAII,EAAE,QAEIN,IAANC,EACFV,EAAQW,EACCX,aAAiBgB,IAC1BhB,EAAMiB,IAAIP,EAAGC,GACJX,aAAiBkB,IAC1BlB,EAAMmB,IAAIR,GArIE,iBADJS,EAuIUpB,IAtIW,MAALoB,IAuIxBpB,EAAMU,GAAKC,IAxIrB,IAAkBS,EA8IhB,GAAIb,EACF,IAAK,MAAMvB,KAAWiB,EAAOoB,QAAQrB,EAAOK,GAC1CE,GAAQ,OACF,CAACvB,OAASyB,GAIhBF,SACI,MAACE,EAAWT,IAqvBtB,SAASsB,EAAStB,EAAOC,EAAQC,EAAU,IACzC,MAAMqB,EAASxB,EAAIC,EAAOC,EAAQC,GAC5BsB,EAl3BR,SAAuBC,GACrB,MAAMC,KACJA,EAAI1B,MACJA,GACEyB,EAAME,OACV,OAAOD,OAAOjB,EAAYT,EA62BZ4B,CAAcL,GAE5B,OAAIC,EAAM,GAQD,CAPO,IAAI3C,EAAY2C,EAAM,GAAI,YACtC,IAAK,MAAMT,KAAKQ,EACVR,EAAE,WACEA,EAAE,WAICN,GAGR,MAACA,EADEe,EAAM,ICl8BpB,MAoCaK,EAAgC,CAACC,EAAQ5B,IAAY6B,MAChEC,EACAC,GACEC,aAAAA,MAEF,MAAOC,EAAQC,GAAUd,EAASU,EAAQF,EAAQ5B,GAElD,OAAc,MAAViC,EACK,CACLH,OAAQ,GACRG,OAAQE,GA7CZC,EA8CuBH,EA7CvBI,EA6CgD,QAAjBL,EA3C/BI,EACGrD,WACAuD,OAAO,CAACC,GAAiCpD,KAAAA,EAAMF,QAAAA,EAAU,GAAIuD,KAAAA,MAC5D,MAAMC,EAAcC,EAAuBvD,GAC3C,YACKoD,EACCpD,EACAoD,EAASE,IAAgBJ,EACvB,CACExD,CAAC4D,GAAcE,EACbF,EACAJ,EACAE,EACAC,GAAQ,GACRvD,IAGJ,CACEJ,CAAC4D,GAAcF,EAASE,OACtBxD,QAAAA,EACAuD,KAAAA,GACIH,EACA,CACEO,MAAO,CAAE/D,CAAC2D,GAAQ,IAAKvD,IAAW,IAEpC,KAGV,KAEL,OAkBE,CACL6C,OAAQI,EACRD,OAAQ,IAtDa,IACvBG,EACAC"}
1
+ {"version":3,"file":"superstruct.modern.js","sources":["../src/superstruct.ts"],"sourcesContent":["import { FieldError } from 'react-hook-form';\nimport { toNestError } from '@hookform/resolvers';\n\nimport { StructError, validate } from 'superstruct';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (error: StructError) =>\n error.failures().reduce<Record<string, FieldError>>(\n (previous, error) =>\n (previous[error.path.join('.')] = {\n message: error.message,\n type: error.type,\n }) && previous,\n {},\n );\n\nexport const superstructResolver: Resolver = (schema, resolverOptions) => (\n values,\n _,\n options,\n) => {\n const result = validate(values, schema, resolverOptions);\n\n return {\n values: result[1] || {},\n errors: result[0]\n ? toNestError(parseErrorSchema(result[0]), options.fields)\n : {},\n };\n};\n"],"names":["superstructResolver","schema","resolverOptions","values","_","options","result","validate","errors","toNestError","error","failures","reduce","previous","path","join","message","type","fields"],"mappings":"yFAMA,MAUaA,EAAgC,CAACC,EAAQC,IAAoB,CACxEC,EACAC,EACAC,KAEA,MAAMC,EAASC,EAASJ,EAAQF,EAAQC,GAExC,MAAO,CACLC,OAAQG,EAAO,IAAM,GACrBE,OAAQF,EAAO,GACXG,GApBkBC,EAoBWJ,EAAO,GAnB1CI,EAAMC,WAAWC,OACf,CAACC,EAAUH,KACRG,EAASH,EAAMI,KAAKC,KAAK,MAAQ,CAChCC,QAASN,EAAMM,QACfC,KAAMP,EAAMO,QACRJ,EACR,KAa6CR,EAAQa,QACjD,IArBkBR,IAAAA"}
@@ -1,2 +1,2 @@
1
- import{transformToNestObject as r,appendErrors as e}from"react-hook-form";import{convertArrayToPathName as o}from"@hookform/resolvers";function t(){return(t=Object.assign||function(r){for(var e=1;e<arguments.length;e++){var o=arguments[e];for(var t in o)Object.prototype.hasOwnProperty.call(o,t)&&(r[t]=o[t])}return r}).apply(this,arguments)}class n extends TypeError{constructor(r,e){let o;const{message:t,...n}=r,{path:i}=r;super(0===i.length?t:"At path: "+i.join(".")+" -- "+t),Object.assign(this,n),this.name=this.constructor.name,this.failures=()=>{var t;return null!=(t=o)?t:o=[r,...e()]}}}function*i(r,e,o={}){const{path:t=[],branch:n=[r],coerce:s=!1}=o,c={path:t,branch:n};s&&(r=e.coercer(r,c));let a=!0;for(const o of e.validator(r,c))a=!1,yield[o,void 0];for(let[o,l,u]of e.entries(r,c)){const e=i(l,u,{path:void 0===o?t:[...t,o],branch:void 0===o?n:[...n,l],coerce:s});for(const t of e)t[0]?(a=!1,yield[t[0],void 0]):s&&(l=t[1],void 0===o?r=l:r instanceof Map?r.set(o,l):r instanceof Set?r.add(l):"object"==typeof(f=r)&&null!=f&&(r[o]=l))}var f;if(a)for(const o of e.refiner(r,c))a=!1,yield[o,void 0];a&&(yield[void 0,r])}function s(r,e,o={}){const t=i(r,e,o),s=function(r){const{done:e,value:o}=r.next();return e?void 0:o}(t);return s[0]?[new n(s[0],function*(){for(const r of t)r[0]&&(yield r[0])}),void 0]:[void 0,s[1]]}var c=function(n,i){return function(c,a,f){var l,u,v=f.criteriaMode;try{var d=s(c,n,i),p=d[0],h=d[1];return Promise.resolve(null!=p?{values:{},errors:r((l=p,u="all"===v,l.failures().reduce(function(r,n){var i,s,c,a=n.path,f=n.message,l=void 0===f?"":f,v=n.type,d=o(a);return t({},r,a?r[d]&&u?((i={})[d]=e(d,u,r,v||"",l),i):((c={})[d]=r[d]||t({message:l,type:v},u?{types:(s={},s[v||""]=l||!0,s)}:{}),c):{})},{})))}:{values:h,errors:{}})}catch(r){return Promise.reject(r)}}};export{c as superstructResolver};
1
+ import{toNestError as r}from"@hookform/resolvers";import{validate as e}from"superstruct";var o=function(o,t){return function(s,u,n){var f,i=e(s,o,t);return{values:i[1]||{},errors:i[0]?r((f=i[0],f.failures().reduce(function(r,e){return(r[e.path.join(".")]={message:e.message,type:e.type})&&r},{})),n.fields):{}}}};export{o as superstructResolver};
2
2
  //# sourceMappingURL=superstruct.module.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"superstruct.module.js","sources":["../../node_modules/superstruct/lib/index.es.js","../src/superstruct.ts"],"sourcesContent":["/**\n * A `StructFailure` represents a single specific failure in validation.\n */\n\n/**\n * `StructError` objects are thrown (or returned) when validation fails.\n *\n * Validation logic is design to exit early for maximum performance. The error\n * represents the first error encountered during validation. For more detail,\n * the `error.failures` property is a generator function that can be run to\n * continue validation and receive all the failures in the data.\n */\nclass StructError extends TypeError {\n constructor(failure, failures) {\n let cached;\n const {\n message,\n ...rest\n } = failure;\n const {\n path\n } = failure;\n const msg = path.length === 0 ? message : \"At path: \" + path.join('.') + \" -- \" + message;\n super(msg);\n Object.assign(this, rest);\n this.name = this.constructor.name;\n\n this.failures = () => {\n var _cached;\n\n return (_cached = cached) != null ? _cached : cached = [failure, ...failures()];\n };\n }\n\n}\n\n/**\n * Check if a value is an iterator.\n */\nfunction isIterable(x) {\n return isObject(x) && typeof x[Symbol.iterator] === 'function';\n}\n/**\n * Check if a value is a plain object.\n */\n\n\nfunction isObject(x) {\n return typeof x === 'object' && x != null;\n}\n/**\n * Check if a value is a plain object.\n */\n\nfunction isPlainObject(x) {\n if (Object.prototype.toString.call(x) !== '[object Object]') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(x);\n return prototype === null || prototype === Object.prototype;\n}\n/**\n * Return a value as a printable string.\n */\n\nfunction print(value) {\n return typeof value === 'string' ? JSON.stringify(value) : \"\" + value;\n}\n/**\n * Shifts (removes and returns) the first value from the `input` iterator.\n * Like `Array.prototype.shift()` but for an `Iterator`.\n */\n\nfunction shiftIterator(input) {\n const {\n done,\n value\n } = input.next();\n return done ? undefined : value;\n}\n/**\n * Convert a single validation result to a failure.\n */\n\nfunction toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n } else if (result === false) {\n result = {};\n } else if (typeof result === 'string') {\n result = {\n message: result\n };\n }\n\n const {\n path,\n branch\n } = context;\n const {\n type\n } = struct;\n const {\n refinement,\n message = \"Expected a value of type `\" + type + \"`\" + (refinement ? \" with refinement `\" + refinement + \"`\" : '') + \", but received: `\" + print(value) + \"`\"\n } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message\n };\n}\n/**\n * Convert a validation result to an iterable of failures.\n */\n\nfunction* toFailures(result, context, struct, value) {\n if (!isIterable(result)) {\n result = [result];\n }\n\n for (const r of result) {\n const failure = toFailure(r, context, struct, value);\n\n if (failure) {\n yield failure;\n }\n }\n}\n/**\n * Check a value against a struct, traversing deeply into nested values, and\n * returning an iterator of failures or success.\n */\n\nfunction* run(value, struct, options = {}) {\n const {\n path = [],\n branch = [value],\n coerce = false\n } = options;\n const ctx = {\n path,\n branch\n };\n\n if (coerce) {\n value = struct.coercer(value, ctx);\n }\n\n let valid = true;\n\n for (const failure of struct.validator(value, ctx)) {\n valid = false;\n yield [failure, undefined];\n }\n\n for (let [k, v, s] of struct.entries(value, ctx)) {\n const ts = run(v, s, {\n path: k === undefined ? path : [...path, k],\n branch: k === undefined ? branch : [...branch, v],\n coerce\n });\n\n for (const t of ts) {\n if (t[0]) {\n valid = false;\n yield [t[0], undefined];\n } else if (coerce) {\n v = t[1];\n\n if (k === undefined) {\n value = v;\n } else if (value instanceof Map) {\n value.set(k, v);\n } else if (value instanceof Set) {\n value.add(v);\n } else if (isObject(value)) {\n value[k] = v;\n }\n }\n }\n }\n\n if (valid) {\n for (const failure of struct.refiner(value, ctx)) {\n valid = false;\n yield [failure, undefined];\n }\n }\n\n if (valid) {\n yield [undefined, value];\n }\n}\n\nfunction assign(...Structs) {\n const schemas = Structs.map(s => s.schema);\n const schema = Object.assign({}, ...schemas);\n return object(schema);\n}\n/**\n * Define a new struct type with a custom validation function.\n */\n\nfunction define(name, validator) {\n return new Struct({\n type: name,\n schema: null,\n validator\n });\n}\n/**\n * Create a struct with dynamic validation logic.\n *\n * The callback will receive the value currently being validated, and must\n * return a struct object to validate it with. This can be useful to model\n * validation logic that changes based on its input.\n */\n\nfunction dynamic(fn) {\n return new Struct({\n type: 'dynamic',\n schema: null,\n\n *entries(value, ctx) {\n const struct = fn(value, ctx);\n yield* struct.entries(value, ctx);\n },\n\n validator(value, ctx) {\n const struct = fn(value, ctx);\n return struct.validator(value, ctx);\n },\n\n coercer(value, ctx) {\n const struct = fn(value, ctx);\n return struct.coercer(value, ctx);\n }\n\n });\n}\n/**\n * Create a struct with lazily evaluated validation logic.\n *\n * The first time validation is run with the struct, the callback will be called\n * and must return a struct object to use. This is useful for cases where you\n * want to have self-referential structs for nested data structures to avoid a\n * circular definition problem.\n */\n\nfunction lazy(fn) {\n let struct;\n return new Struct({\n type: 'lazy',\n schema: null,\n\n *entries(value, ctx) {\n var _struct;\n\n (_struct = struct) != null ? _struct : struct = fn();\n yield* struct.entries(value, ctx);\n },\n\n validator(value, ctx) {\n var _struct2;\n\n (_struct2 = struct) != null ? _struct2 : struct = fn();\n return struct.validator(value, ctx);\n },\n\n coercer(value, ctx) {\n var _struct3;\n\n (_struct3 = struct) != null ? _struct3 : struct = fn();\n return struct.coercer(value, ctx);\n }\n\n });\n}\n/**\n * Create a new struct based on an existing object struct, but excluding\n * specific properties.\n *\n * Like TypeScript's `Omit` utility.\n */\n\nfunction omit(struct, keys) {\n const {\n schema\n } = struct;\n const subschema = { ...schema\n };\n\n for (const key of keys) {\n delete subschema[key];\n }\n\n return object(subschema);\n}\n/**\n * Create a new struct based on an existing object struct, but with all of its\n * properties allowed to be `undefined`.\n *\n * Like TypeScript's `Partial` utility.\n */\n\nfunction partial(struct) {\n const schema = struct instanceof Struct ? { ...struct.schema\n } : { ...struct\n };\n\n for (const key in schema) {\n schema[key] = optional(schema[key]);\n }\n\n return object(schema);\n}\n/**\n * Create a new struct based on an existing object struct, but only including\n * specific properties.\n *\n * Like TypeScript's `Pick` utility.\n */\n\nfunction pick(struct, keys) {\n const {\n schema\n } = struct;\n const subschema = {};\n\n for (const key of keys) {\n subschema[key] = schema[key];\n }\n\n return object(subschema);\n}\n/**\n * Define a new struct type with a custom validation function.\n *\n * @deprecated This function has been renamed to `define`.\n */\n\nfunction struct(name, validator) {\n console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.');\n return define(name, validator);\n}\n\n/**\n * Ensure that any value passes validation.\n */\n\nfunction any() {\n return define('any', () => true);\n}\nfunction array(Element) {\n return new Struct({\n type: 'array',\n schema: Element,\n\n *entries(value) {\n if (Element && Array.isArray(value)) {\n for (const [i, v] of value.entries()) {\n yield [i, v, Element];\n }\n }\n },\n\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n\n validator(value) {\n return Array.isArray(value) || \"Expected an array value, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a boolean.\n */\n\nfunction boolean() {\n return define('boolean', value => {\n return typeof value === 'boolean';\n });\n}\n/**\n * Ensure that a value is a valid `Date`.\n *\n * Note: this also ensures that the value is *not* an invalid `Date` object,\n * which can occur when parsing a date fails but still returns a `Date`.\n */\n\nfunction date() {\n return define('date', value => {\n return value instanceof Date && !isNaN(value.getTime()) || \"Expected a valid `Date` object, but received: \" + print(value);\n });\n}\nfunction enums(values) {\n const schema = {};\n const description = values.map(v => print(v)).join();\n\n for (const key of values) {\n schema[key] = key;\n }\n\n return new Struct({\n type: 'enums',\n schema,\n\n validator(value) {\n return values.includes(value) || \"Expected one of `\" + description + \"`, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a function.\n */\n\nfunction func() {\n return define('func', value => {\n return typeof value === 'function' || \"Expected a function, but received: \" + print(value);\n });\n}\n/**\n * Ensure that a value is an instance of a specific class.\n */\n\nfunction instance(Class) {\n return define('instance', value => {\n return value instanceof Class || \"Expected a `\" + Class.name + \"` instance, but received: \" + print(value);\n });\n}\n/**\n * Ensure that a value is an integer.\n */\n\nfunction integer() {\n return define('integer', value => {\n return typeof value === 'number' && !isNaN(value) && Number.isInteger(value) || \"Expected an integer, but received: \" + print(value);\n });\n}\nfunction intersection(Structs) {\n return new Struct({\n type: 'intersection',\n schema: null,\n\n *entries(value, ctx) {\n for (const S of Structs) {\n yield* S.entries(value, ctx);\n }\n },\n\n *validator(value, ctx) {\n for (const S of Structs) {\n yield* S.validator(value, ctx);\n }\n },\n\n *refiner(value, ctx) {\n for (const S of Structs) {\n yield* S.refiner(value, ctx);\n }\n }\n\n });\n}\nfunction literal(constant) {\n const description = print(constant);\n return define('literal', value => {\n return value === constant || \"Expected the literal `\" + description + \"`, but received: \" + print(value);\n });\n}\nfunction map(Key, Value) {\n return new Struct({\n type: 'map',\n schema: null,\n\n *entries(value) {\n if (Key && Value && value instanceof Map) {\n for (const [k, v] of value.entries()) {\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n\n coercer(value) {\n return value instanceof Map ? new Map(value) : value;\n },\n\n validator(value) {\n return value instanceof Map || \"Expected a `Map` object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that no value ever passes validation.\n */\n\nfunction never() {\n return define('never', () => false);\n}\n/**\n * Augment an existing struct to allow `null` values.\n */\n\nfunction nullable(struct) {\n return new Struct({ ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx)\n });\n}\n/**\n * Ensure that a value is a number.\n */\n\nfunction number() {\n return define('number', value => {\n return typeof value === 'number' && !isNaN(value) || \"Expected a number, but received: \" + print(value);\n });\n}\nfunction object(schema) {\n const knowns = schema ? Object.keys(schema) : [];\n const Never = never();\n return new Struct({\n type: 'object',\n schema: schema ? schema : null,\n\n *entries(value) {\n if (schema && isObject(value)) {\n const unknowns = new Set(Object.keys(value));\n\n for (const key of knowns) {\n unknowns.delete(key);\n yield [key, value[key], schema[key]];\n }\n\n for (const key of unknowns) {\n yield [key, value[key], Never];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n },\n\n coercer(value) {\n return isObject(value) ? { ...value\n } : value;\n }\n\n });\n}\n/**\n * Augment a struct to allow `undefined` values.\n */\n\nfunction optional(struct) {\n return new Struct({ ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx)\n });\n}\n/**\n * Ensure that a value is an object with keys and values of specific types, but\n * without ensuring any specific shape of properties.\n *\n * Like TypeScript's `Record` utility.\n */\n\nfunction record(Key, Value) {\n return new Struct({\n type: 'record',\n schema: null,\n\n *entries(value) {\n if (isObject(value)) {\n for (const k in value) {\n const v = value[k];\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a `RegExp`.\n *\n * Note: this does not test the value against the regular expression! For that\n * you need to use the `pattern()` refinement.\n */\n\nfunction regexp() {\n return define('regexp', value => {\n return value instanceof RegExp;\n });\n}\nfunction set(Element) {\n return new Struct({\n type: 'set',\n schema: null,\n\n *entries(value) {\n if (Element && value instanceof Set) {\n for (const v of value) {\n yield [v, v, Element];\n }\n }\n },\n\n coercer(value) {\n return value instanceof Set ? new Set(value) : value;\n },\n\n validator(value) {\n return value instanceof Set || \"Expected a `Set` object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a string.\n */\n\nfunction string() {\n return define('string', value => {\n return typeof value === 'string' || \"Expected a string, but received: \" + print(value);\n });\n}\nfunction tuple(Elements) {\n const Never = never();\n return new Struct({\n type: 'tuple',\n schema: null,\n\n *entries(value) {\n if (Array.isArray(value)) {\n const length = Math.max(Elements.length, value.length);\n\n for (let i = 0; i < length; i++) {\n yield [i, value[i], Elements[i] || Never];\n }\n }\n },\n\n validator(value) {\n return Array.isArray(value) || \"Expected an array, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value has a set of known properties of specific types.\n *\n * Note: Unrecognized properties are allowed and untouched. This is similar to\n * how TypeScript's structural typing works.\n */\n\nfunction type(schema) {\n const keys = Object.keys(schema);\n return new Struct({\n type: 'type',\n schema,\n\n *entries(value) {\n if (isObject(value)) {\n for (const k of keys) {\n yield [k, value[k], schema[k]];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n }\n\n });\n}\nfunction union(Structs) {\n const description = Structs.map(s => s.type).join(' | ');\n return new Struct({\n type: 'union',\n schema: null,\n\n validator(value, ctx) {\n const failures = [];\n\n for (const S of Structs) {\n const [...tuples] = run(value, S, ctx);\n const [first] = tuples;\n\n if (!first[0]) {\n return [];\n } else {\n for (const [failure] of tuples) {\n if (failure) {\n failures.push(failure);\n }\n }\n }\n }\n\n return [\"Expected the value to satisfy a union of `\" + description + \"`, but received: \" + print(value), ...failures];\n }\n\n });\n}\n/**\n * Ensure that any value passes validation, without widening its type to `any`.\n */\n\nfunction unknown() {\n return define('unknown', () => true);\n}\n\n/**\n * Augment a `Struct` to add an additional coercion step to its input.\n *\n * This allows you to transform input data before validating it, to increase the\n * likelihood that it passes validation—for example for default values, parsing\n * different formats, etc.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction coerce(struct, condition, coercer) {\n return new Struct({ ...struct,\n coercer: (value, ctx) => {\n return is(value, condition) ? struct.coercer(coercer(value, ctx), ctx) : struct.coercer(value, ctx);\n }\n });\n}\n/**\n * Augment a struct to replace `undefined` values with a default.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction defaulted(struct, fallback, options = {}) {\n return coerce(struct, unknown(), x => {\n const f = typeof fallback === 'function' ? fallback() : fallback;\n\n if (x === undefined) {\n return f;\n }\n\n if (!options.strict && isPlainObject(x) && isPlainObject(f)) {\n const ret = { ...x\n };\n let changed = false;\n\n for (const key in f) {\n if (ret[key] === undefined) {\n ret[key] = f[key];\n changed = true;\n }\n }\n\n if (changed) {\n return ret;\n }\n }\n\n return x;\n });\n}\n/**\n * Augment a struct to mask its input to only properties defined in the struct.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction masked(struct) {\n return coerce(struct, unknown(), x => {\n if (typeof struct.schema !== 'object' || struct.schema == null || typeof x !== 'object' || x == null) {\n return x;\n } else {\n const ret = {};\n\n for (const key in struct.schema) {\n if (key in x) {\n ret[key] = x[key];\n }\n }\n\n return ret;\n }\n });\n}\n/**\n * Augment a struct to trim string inputs.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction trimmed(struct) {\n return coerce(struct, string(), x => x.trim());\n}\n\n/**\n * `Struct` objects encapsulate the validation logic for a specific type of\n * values. Once constructed, you use the `assert`, `is` or `validate` helpers to\n * validate unknown input data against the struct.\n */\n\nclass Struct {\n constructor(props) {\n const {\n type,\n schema,\n validator,\n refiner,\n coercer = value => value,\n entries = function* () {}\n } = props;\n this.type = type;\n this.schema = schema;\n this.entries = entries;\n this.coercer = coercer;\n\n if (validator) {\n this.validator = (value, context) => {\n const result = validator(value, context);\n return toFailures(result, context, this, value);\n };\n } else {\n this.validator = () => [];\n }\n\n if (refiner) {\n this.refiner = (value, context) => {\n const result = refiner(value, context);\n return toFailures(result, context, this, value);\n };\n } else {\n this.refiner = () => [];\n }\n }\n /**\n * Assert that a value passes the struct's validation, throwing if it doesn't.\n */\n\n\n assert(value) {\n return assert(value, this);\n }\n /**\n * Create a value with the struct's coercion logic, then validate it.\n */\n\n\n create(value) {\n return create(value, this);\n }\n /**\n * Check if a value passes the struct's validation.\n */\n\n\n is(value) {\n return is(value, this);\n }\n /**\n * Mask a value, coercing and validating it, but returning only the subset of\n * properties defined by the struct's schema.\n */\n\n\n mask(value) {\n return mask(value, this);\n }\n /**\n * Validate a value with the struct's validation logic, returning a tuple\n * representing the result.\n *\n * You may optionally pass `true` for the `withCoercion` argument to coerce\n * the value before attempting to validate it. If you do, the result will\n * contain the coerced result when successful.\n */\n\n\n validate(value, options = {}) {\n return validate(value, this, options);\n }\n\n}\n/**\n * Assert that a value passes a struct, throwing if it doesn't.\n */\n\nfunction assert(value, struct) {\n const result = validate(value, struct);\n\n if (result[0]) {\n throw result[0];\n }\n}\n/**\n * Create a value with the coercion logic of struct and validate it.\n */\n\nfunction create(value, struct) {\n const result = validate(value, struct, {\n coerce: true\n });\n\n if (result[0]) {\n throw result[0];\n } else {\n return result[1];\n }\n}\n/**\n * Mask a value, returning only the subset of properties defined by a struct.\n */\n\nfunction mask(value, struct) {\n const M = masked(struct);\n const ret = create(value, M);\n return ret;\n}\n/**\n * Check if a value passes a struct.\n */\n\nfunction is(value, struct) {\n const result = validate(value, struct);\n return !result[0];\n}\n/**\n * Validate a value against a struct, returning an error if invalid, or the\n * value (with potential coercion) if valid.\n */\n\nfunction validate(value, struct, options = {}) {\n const tuples = run(value, struct, options);\n const tuple = shiftIterator(tuples);\n\n if (tuple[0]) {\n const error = new StructError(tuple[0], function* () {\n for (const t of tuples) {\n if (t[0]) {\n yield t[0];\n }\n }\n });\n return [error, undefined];\n } else {\n const v = tuple[1];\n return [undefined, v];\n }\n}\n\n/**\n * Ensure that a string, array, map, or set is empty.\n */\n\nfunction empty(struct) {\n const expected = \"Expected an empty \" + struct.type;\n return refine(struct, 'empty', value => {\n if (value instanceof Map || value instanceof Set) {\n const {\n size\n } = value;\n return size === 0 || expected + \" but received one with a size of `\" + size + \"`\";\n } else {\n const {\n length\n } = value;\n return length === 0 || expected + \" but received one with a length of `\" + length + \"`\";\n }\n });\n}\n/**\n * Ensure that a number or date is below a threshold.\n */\n\nfunction max(struct, threshold, options = {}) {\n const {\n exclusive\n } = options;\n return refine(struct, 'max', value => {\n return exclusive ? value < threshold : value <= threshold || \"Expected a \" + struct.type + \" greater than \" + (exclusive ? '' : 'or equal to ') + threshold + \" but received `\" + value + \"`\";\n });\n}\n/**\n * Ensure that a number or date is above a threshold.\n */\n\nfunction min(struct, threshold, options = {}) {\n const {\n exclusive\n } = options;\n return refine(struct, 'min', value => {\n return exclusive ? value > threshold : value >= threshold || \"Expected a \" + struct.type + \" greater than \" + (exclusive ? '' : 'or equal to ') + threshold + \" but received `\" + value + \"`\";\n });\n}\n/**\n * Ensure that a string matches a regular expression.\n */\n\nfunction pattern(struct, regexp) {\n return refine(struct, 'pattern', value => {\n return regexp.test(value) || \"Expected a \" + struct.type + \" matching `/\" + regexp.source + \"/` but received \\\"\" + value + \"\\\"\";\n });\n}\n/**\n * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`.\n */\n\nfunction size(struct, min, max = min) {\n const expected = \"Expected a \" + struct.type;\n const of = min === max ? \"of `\" + min + \"`\" : \"between `\" + min + \"` and `\" + max + \"`\";\n return refine(struct, 'size', value => {\n if (typeof value === 'number' || value instanceof Date) {\n return min <= value && value <= max || expected + \" \" + of + \" but received `\" + value + \"`\";\n } else if (value instanceof Map || value instanceof Set) {\n const {\n size\n } = value;\n return min <= size && size <= max || expected + \" with a size \" + of + \" but received one with a size of `\" + size + \"`\";\n } else {\n const {\n length\n } = value;\n return min <= length && length <= max || expected + \" with a length \" + of + \" but received one with a length of `\" + length + \"`\";\n }\n });\n}\n/**\n * Augment a `Struct` to add an additional refinement to the validation.\n *\n * The refiner function is guaranteed to receive a value of the struct's type,\n * because the struct's existing validation will already have passed. This\n * allows you to layer additional validation on top of existing structs.\n */\n\nfunction refine(struct, name, refiner) {\n return new Struct({ ...struct,\n\n *refiner(value, ctx) {\n yield* struct.refiner(value, ctx);\n const result = refiner(value, ctx);\n const failures = toFailures(result, ctx, struct, value);\n\n for (const failure of failures) {\n yield { ...failure,\n refinement: name\n };\n }\n }\n\n });\n}\n\nexport { Struct, StructError, any, array, assert, assign, boolean, coerce, create, date, defaulted, define, dynamic, empty, enums, func, instance, integer, intersection, is, lazy, literal, map, mask, masked, max, min, never, nullable, number, object, omit, optional, partial, pattern, pick, record, refine, regexp, set, size, string, struct, trimmed, tuple, type, union, unknown, validate };\n//# sourceMappingURL=index.es.js.map\n","import { appendErrors, transformToNestObject } from 'react-hook-form';\nimport { StructError, validate } from 'superstruct';\n// @ts-expect-error maybe fixed after the first publish ?\nimport { convertArrayToPathName } from '@hookform/resolvers';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n error: StructError,\n validateAllFieldCriteria: boolean,\n) =>\n error\n .failures()\n .reduce((previous: Record<string, any>, { path, message = '', type }) => {\n const currentPath = convertArrayToPathName(path);\n return {\n ...previous,\n ...(path\n ? previous[currentPath] && validateAllFieldCriteria\n ? {\n [currentPath]: appendErrors(\n currentPath,\n validateAllFieldCriteria,\n previous,\n type || '',\n message,\n ),\n }\n : {\n [currentPath]: previous[currentPath] || {\n message,\n type,\n ...(validateAllFieldCriteria\n ? {\n types: { [type || '']: message || true },\n }\n : {}),\n },\n }\n : {}),\n };\n }, {});\n\nexport const superstructResolver: Resolver = (schema, options) => async (\n values,\n _context,\n { criteriaMode },\n) => {\n const [errors, result] = validate(values, schema, options);\n\n if (errors != null) {\n return {\n values: {},\n errors: transformToNestObject(\n parseErrorSchema(errors, criteriaMode === 'all'),\n ),\n };\n }\n\n return {\n values: result,\n errors: {},\n };\n};\n"],"names":["StructError","TypeError","[object Object]","failure","failures","cached","message","rest","path","super","length","join","Object","assign","this","name","constructor","_cached","run","value","struct","options","branch","coerce","ctx","coercer","valid","validator","undefined","k","v","s","entries","ts","t","Map","set","Set","add","x","refiner","validate","tuples","tuple","input","done","next","shiftIterator","superstructResolver","schema","values","_context","error","validateAllFieldCriteria","criteriaMode","errors","result","transformToNestObject","reduce","previous","type","currentPath","convertArrayToPathName","appendErrors","types"],"mappings":"sVAYA,MAAMA,UAAoBC,UACxBC,YAAYC,EAASC,GACnB,IAAIC,EACJ,MAAMC,QACJA,KACGC,GACDJ,GACEK,KACJA,GACEL,EAEJM,MAD4B,IAAhBD,EAAKE,OAAeJ,EAAU,YAAcE,EAAKG,KAAK,KAAO,OAASL,GAElFM,OAAOC,OAAOC,KAAMP,GACpBO,KAAKC,KAAOD,KAAKE,YAAYD,KAE7BD,KAAKV,SAAW,KACd,IAAIa,EAEJ,OAA6B,OAArBA,EAAUZ,GAAkBY,EAAUZ,EAAS,CAACF,KAAYC,OA8G1E,SAAUc,EAAIC,EAAOC,EAAQC,EAAU,IACrC,MAAMb,KACJA,EAAO,GAAEc,OACTA,EAAS,CAACH,GAAMI,OAChBA,GAAS,GACPF,EACEG,EAAM,CACVhB,KAAAA,EACAc,OAAAA,GAGEC,IACFJ,EAAQC,EAAOK,QAAQN,EAAOK,IAGhC,IAAIE,GAAQ,EAEZ,IAAK,MAAMvB,KAAWiB,EAAOO,UAAUR,EAAOK,GAC5CE,GAAQ,OACF,CAACvB,OAASyB,GAGlB,IAAK,IAAKC,EAAGC,EAAGC,KAAMX,EAAOY,QAAQb,EAAOK,GAAM,CAChD,MAAMS,EAAKf,EAAIY,EAAGC,EAAG,CACnBvB,UAAYoB,IAANC,EAAkBrB,EAAO,IAAIA,EAAMqB,GACzCP,YAAcM,IAANC,EAAkBP,EAAS,IAAIA,EAAQQ,GAC/CP,OAAAA,IAGF,IAAK,MAAMW,KAAKD,EACVC,EAAE,IACJR,GAAQ,OACF,CAACQ,EAAE,QAAIN,IACJL,IACTO,EAAII,EAAE,QAEIN,IAANC,EACFV,EAAQW,EACCX,aAAiBgB,IAC1BhB,EAAMiB,IAAIP,EAAGC,GACJX,aAAiBkB,IAC1BlB,EAAMmB,IAAIR,GArIE,iBADJS,EAuIUpB,IAtIW,MAALoB,IAuIxBpB,EAAMU,GAAKC,IAxIrB,IAAkBS,EA8IhB,GAAIb,EACF,IAAK,MAAMvB,KAAWiB,EAAOoB,QAAQrB,EAAOK,GAC1CE,GAAQ,OACF,CAACvB,OAASyB,GAIhBF,SACI,MAACE,EAAWT,IAqvBtB,SAASsB,EAAStB,EAAOC,EAAQC,EAAU,IACzC,MAAMqB,EAASxB,EAAIC,EAAOC,EAAQC,GAC5BsB,EAl3BR,SAAuBC,GACrB,MAAMC,KACJA,EAAI1B,MACJA,GACEyB,EAAME,OACV,OAAOD,OAAOjB,EAAYT,EA62BZ4B,CAAcL,GAE5B,OAAIC,EAAM,GAQD,CAPO,IAAI3C,EAAY2C,EAAM,GAAI,YACtC,IAAK,MAAMT,KAAKQ,EACVR,EAAE,WACEA,EAAE,WAICN,GAGR,MAACA,EADEe,EAAM,ICl8BpB,IAoCaK,EAAgC,SAACC,EAAQ5B,mBACpD6B,EACAC,SArCAC,EACAC,EAqCEC,IAAAA,uBAEuBb,EAASS,EAAQD,EAAQ5B,GAA3CkC,OAAQC,OAEf,uBAAc,MAAVD,EACK,CACLL,OAAQ,GACRK,OAAQE,GA7CZL,EA8CuBG,EA7CvBF,EA6CgD,QAAjBC,EA3C/BF,EACGhD,WACAsD,OAAO,SAACC,eAAiCnD,IAAAA,SAAMF,QAAAA,aAAU,KAAIsD,IAAAA,KACtDC,EAAcC,EAAuBtD,GAC3C,YACKmD,EACCnD,EACAmD,EAASE,IAAgBR,UAEpBQ,GAAcE,EACbF,EACAR,EACAM,EACAC,GAAQ,GACRtD,cAIDuD,GAAcF,EAASE,OACtBvD,QAAAA,EACAsD,KAAAA,GACIP,EACA,CACEW,cAAUJ,GAAQ,IAAKtD,IAAW,MAEpC,OAGV,KAEL,OAkBE,CACL4C,OAAQM,EACRD,OAAQ,KAlBiC"}
1
+ {"version":3,"file":"superstruct.module.js","sources":["../src/superstruct.ts"],"sourcesContent":["import { FieldError } from 'react-hook-form';\nimport { toNestError } from '@hookform/resolvers';\n\nimport { StructError, validate } from 'superstruct';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (error: StructError) =>\n error.failures().reduce<Record<string, FieldError>>(\n (previous, error) =>\n (previous[error.path.join('.')] = {\n message: error.message,\n type: error.type,\n }) && previous,\n {},\n );\n\nexport const superstructResolver: Resolver = (schema, resolverOptions) => (\n values,\n _,\n options,\n) => {\n const result = validate(values, schema, resolverOptions);\n\n return {\n values: result[1] || {},\n errors: result[0]\n ? toNestError(parseErrorSchema(result[0]), options.fields)\n : {},\n };\n};\n"],"names":["superstructResolver","schema","resolverOptions","values","_","options","error","result","validate","errors","toNestError","failures","reduce","previous","path","join","message","type","fields"],"mappings":"yFAMA,IAUaA,EAAgC,SAACC,EAAQC,mBACpDC,EACAC,EACAC,GAEA,IAfwBC,EAelBC,EAASC,EAASL,EAAQF,EAAQC,GAExC,MAAO,CACLC,OAAQI,EAAO,IAAM,GACrBE,OAAQF,EAAO,GACXG,GApBkBJ,EAoBWC,EAAO,GAnB1CD,EAAMK,WAAWC,OACf,SAACC,EAAUP,UACRO,EAASP,EAAMQ,KAAKC,KAAK,MAAQ,CAChCC,QAASV,EAAMU,QACfC,KAAMX,EAAMW,QACRJ,GACR,KAa6CR,EAAQa,QACjD"}
@@ -1,2 +1,2 @@
1
- !function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("react-hook-form"),require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","react-hook-form","@hookform/resolvers"],o):o((e||self).hookformResolversSuperstruct={},e.reactHookForm,e.hookformResolvers)}(this,function(e,o,r){function t(){return(t=Object.assign||function(e){for(var o=1;o<arguments.length;o++){var r=arguments[o];for(var t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=r[t])}return e}).apply(this,arguments)}class n extends TypeError{constructor(e,o){let r;const{message:t,...n}=e,{path:s}=e;super(0===s.length?t:"At path: "+s.join(".")+" -- "+t),Object.assign(this,n),this.name=this.constructor.name,this.failures=()=>{var t;return null!=(t=r)?t:r=[e,...o()]}}}function*s(e,o,r={}){const{path:t=[],branch:n=[e],coerce:i=!1}=r,c={path:t,branch:n};i&&(e=o.coercer(e,c));let a=!0;for(const r of o.validator(e,c))a=!1,yield[r,void 0];for(let[r,u,l]of o.entries(e,c)){const o=s(u,l,{path:void 0===r?t:[...t,r],branch:void 0===r?n:[...n,u],coerce:i});for(const t of o)t[0]?(a=!1,yield[t[0],void 0]):i&&(u=t[1],void 0===r?e=u:e instanceof Map?e.set(r,u):e instanceof Set?e.add(u):"object"==typeof(f=e)&&null!=f&&(e[r]=u))}var f;if(a)for(const r of o.refiner(e,c))a=!1,yield[r,void 0];a&&(yield[void 0,e])}function i(e,o,r={}){const t=s(e,o,r),i=function(e){const{done:o,value:r}=e.next();return o?void 0:r}(t);return i[0]?[new n(i[0],function*(){for(const e of t)e[0]&&(yield e[0])}),void 0]:[void 0,i[1]]}e.superstructResolver=function(e,n){return function(s,c,a){var f,u,l=a.criteriaMode;try{var d=i(s,e,n),v=d[0],p=d[1];return Promise.resolve(null!=v?{values:{},errors:o.transformToNestObject((f=v,u="all"===l,f.failures().reduce(function(e,n){var s,i,c,a=n.path,f=n.message,l=void 0===f?"":f,d=n.type,v=r.convertArrayToPathName(a);return t({},e,a?e[v]&&u?((s={})[v]=o.appendErrors(v,u,e,d||"",l),s):((c={})[v]=e[v]||t({message:l,type:d},u?{types:(i={},i[d||""]=l||!0,i)}:{}),c):{})},{})))}:{values:p,errors:{}})}catch(e){return Promise.reject(e)}}}});
1
+ !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("superstruct")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","superstruct"],r):r((e||self).hookformResolversSuperstruct={},e.hookformResolvers,e.superstruct)}(this,function(e,r,o){e.superstructResolver=function(e,s){return function(t,u,n){var f,i=o.validate(t,e,s);return{values:i[1]||{},errors:i[0]?r.toNestError((f=i[0],f.failures().reduce(function(e,r){return(e[r.path.join(".")]={message:r.message,type:r.type})&&e},{})),n.fields):{}}}}});
2
2
  //# sourceMappingURL=superstruct.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"superstruct.umd.js","sources":["../../node_modules/superstruct/lib/index.es.js","../src/superstruct.ts"],"sourcesContent":["/**\n * A `StructFailure` represents a single specific failure in validation.\n */\n\n/**\n * `StructError` objects are thrown (or returned) when validation fails.\n *\n * Validation logic is design to exit early for maximum performance. The error\n * represents the first error encountered during validation. For more detail,\n * the `error.failures` property is a generator function that can be run to\n * continue validation and receive all the failures in the data.\n */\nclass StructError extends TypeError {\n constructor(failure, failures) {\n let cached;\n const {\n message,\n ...rest\n } = failure;\n const {\n path\n } = failure;\n const msg = path.length === 0 ? message : \"At path: \" + path.join('.') + \" -- \" + message;\n super(msg);\n Object.assign(this, rest);\n this.name = this.constructor.name;\n\n this.failures = () => {\n var _cached;\n\n return (_cached = cached) != null ? _cached : cached = [failure, ...failures()];\n };\n }\n\n}\n\n/**\n * Check if a value is an iterator.\n */\nfunction isIterable(x) {\n return isObject(x) && typeof x[Symbol.iterator] === 'function';\n}\n/**\n * Check if a value is a plain object.\n */\n\n\nfunction isObject(x) {\n return typeof x === 'object' && x != null;\n}\n/**\n * Check if a value is a plain object.\n */\n\nfunction isPlainObject(x) {\n if (Object.prototype.toString.call(x) !== '[object Object]') {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(x);\n return prototype === null || prototype === Object.prototype;\n}\n/**\n * Return a value as a printable string.\n */\n\nfunction print(value) {\n return typeof value === 'string' ? JSON.stringify(value) : \"\" + value;\n}\n/**\n * Shifts (removes and returns) the first value from the `input` iterator.\n * Like `Array.prototype.shift()` but for an `Iterator`.\n */\n\nfunction shiftIterator(input) {\n const {\n done,\n value\n } = input.next();\n return done ? undefined : value;\n}\n/**\n * Convert a single validation result to a failure.\n */\n\nfunction toFailure(result, context, struct, value) {\n if (result === true) {\n return;\n } else if (result === false) {\n result = {};\n } else if (typeof result === 'string') {\n result = {\n message: result\n };\n }\n\n const {\n path,\n branch\n } = context;\n const {\n type\n } = struct;\n const {\n refinement,\n message = \"Expected a value of type `\" + type + \"`\" + (refinement ? \" with refinement `\" + refinement + \"`\" : '') + \", but received: `\" + print(value) + \"`\"\n } = result;\n return {\n value,\n type,\n refinement,\n key: path[path.length - 1],\n path,\n branch,\n ...result,\n message\n };\n}\n/**\n * Convert a validation result to an iterable of failures.\n */\n\nfunction* toFailures(result, context, struct, value) {\n if (!isIterable(result)) {\n result = [result];\n }\n\n for (const r of result) {\n const failure = toFailure(r, context, struct, value);\n\n if (failure) {\n yield failure;\n }\n }\n}\n/**\n * Check a value against a struct, traversing deeply into nested values, and\n * returning an iterator of failures or success.\n */\n\nfunction* run(value, struct, options = {}) {\n const {\n path = [],\n branch = [value],\n coerce = false\n } = options;\n const ctx = {\n path,\n branch\n };\n\n if (coerce) {\n value = struct.coercer(value, ctx);\n }\n\n let valid = true;\n\n for (const failure of struct.validator(value, ctx)) {\n valid = false;\n yield [failure, undefined];\n }\n\n for (let [k, v, s] of struct.entries(value, ctx)) {\n const ts = run(v, s, {\n path: k === undefined ? path : [...path, k],\n branch: k === undefined ? branch : [...branch, v],\n coerce\n });\n\n for (const t of ts) {\n if (t[0]) {\n valid = false;\n yield [t[0], undefined];\n } else if (coerce) {\n v = t[1];\n\n if (k === undefined) {\n value = v;\n } else if (value instanceof Map) {\n value.set(k, v);\n } else if (value instanceof Set) {\n value.add(v);\n } else if (isObject(value)) {\n value[k] = v;\n }\n }\n }\n }\n\n if (valid) {\n for (const failure of struct.refiner(value, ctx)) {\n valid = false;\n yield [failure, undefined];\n }\n }\n\n if (valid) {\n yield [undefined, value];\n }\n}\n\nfunction assign(...Structs) {\n const schemas = Structs.map(s => s.schema);\n const schema = Object.assign({}, ...schemas);\n return object(schema);\n}\n/**\n * Define a new struct type with a custom validation function.\n */\n\nfunction define(name, validator) {\n return new Struct({\n type: name,\n schema: null,\n validator\n });\n}\n/**\n * Create a struct with dynamic validation logic.\n *\n * The callback will receive the value currently being validated, and must\n * return a struct object to validate it with. This can be useful to model\n * validation logic that changes based on its input.\n */\n\nfunction dynamic(fn) {\n return new Struct({\n type: 'dynamic',\n schema: null,\n\n *entries(value, ctx) {\n const struct = fn(value, ctx);\n yield* struct.entries(value, ctx);\n },\n\n validator(value, ctx) {\n const struct = fn(value, ctx);\n return struct.validator(value, ctx);\n },\n\n coercer(value, ctx) {\n const struct = fn(value, ctx);\n return struct.coercer(value, ctx);\n }\n\n });\n}\n/**\n * Create a struct with lazily evaluated validation logic.\n *\n * The first time validation is run with the struct, the callback will be called\n * and must return a struct object to use. This is useful for cases where you\n * want to have self-referential structs for nested data structures to avoid a\n * circular definition problem.\n */\n\nfunction lazy(fn) {\n let struct;\n return new Struct({\n type: 'lazy',\n schema: null,\n\n *entries(value, ctx) {\n var _struct;\n\n (_struct = struct) != null ? _struct : struct = fn();\n yield* struct.entries(value, ctx);\n },\n\n validator(value, ctx) {\n var _struct2;\n\n (_struct2 = struct) != null ? _struct2 : struct = fn();\n return struct.validator(value, ctx);\n },\n\n coercer(value, ctx) {\n var _struct3;\n\n (_struct3 = struct) != null ? _struct3 : struct = fn();\n return struct.coercer(value, ctx);\n }\n\n });\n}\n/**\n * Create a new struct based on an existing object struct, but excluding\n * specific properties.\n *\n * Like TypeScript's `Omit` utility.\n */\n\nfunction omit(struct, keys) {\n const {\n schema\n } = struct;\n const subschema = { ...schema\n };\n\n for (const key of keys) {\n delete subschema[key];\n }\n\n return object(subschema);\n}\n/**\n * Create a new struct based on an existing object struct, but with all of its\n * properties allowed to be `undefined`.\n *\n * Like TypeScript's `Partial` utility.\n */\n\nfunction partial(struct) {\n const schema = struct instanceof Struct ? { ...struct.schema\n } : { ...struct\n };\n\n for (const key in schema) {\n schema[key] = optional(schema[key]);\n }\n\n return object(schema);\n}\n/**\n * Create a new struct based on an existing object struct, but only including\n * specific properties.\n *\n * Like TypeScript's `Pick` utility.\n */\n\nfunction pick(struct, keys) {\n const {\n schema\n } = struct;\n const subschema = {};\n\n for (const key of keys) {\n subschema[key] = schema[key];\n }\n\n return object(subschema);\n}\n/**\n * Define a new struct type with a custom validation function.\n *\n * @deprecated This function has been renamed to `define`.\n */\n\nfunction struct(name, validator) {\n console.warn('superstruct@0.11 - The `struct` helper has been renamed to `define`.');\n return define(name, validator);\n}\n\n/**\n * Ensure that any value passes validation.\n */\n\nfunction any() {\n return define('any', () => true);\n}\nfunction array(Element) {\n return new Struct({\n type: 'array',\n schema: Element,\n\n *entries(value) {\n if (Element && Array.isArray(value)) {\n for (const [i, v] of value.entries()) {\n yield [i, v, Element];\n }\n }\n },\n\n coercer(value) {\n return Array.isArray(value) ? value.slice() : value;\n },\n\n validator(value) {\n return Array.isArray(value) || \"Expected an array value, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a boolean.\n */\n\nfunction boolean() {\n return define('boolean', value => {\n return typeof value === 'boolean';\n });\n}\n/**\n * Ensure that a value is a valid `Date`.\n *\n * Note: this also ensures that the value is *not* an invalid `Date` object,\n * which can occur when parsing a date fails but still returns a `Date`.\n */\n\nfunction date() {\n return define('date', value => {\n return value instanceof Date && !isNaN(value.getTime()) || \"Expected a valid `Date` object, but received: \" + print(value);\n });\n}\nfunction enums(values) {\n const schema = {};\n const description = values.map(v => print(v)).join();\n\n for (const key of values) {\n schema[key] = key;\n }\n\n return new Struct({\n type: 'enums',\n schema,\n\n validator(value) {\n return values.includes(value) || \"Expected one of `\" + description + \"`, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a function.\n */\n\nfunction func() {\n return define('func', value => {\n return typeof value === 'function' || \"Expected a function, but received: \" + print(value);\n });\n}\n/**\n * Ensure that a value is an instance of a specific class.\n */\n\nfunction instance(Class) {\n return define('instance', value => {\n return value instanceof Class || \"Expected a `\" + Class.name + \"` instance, but received: \" + print(value);\n });\n}\n/**\n * Ensure that a value is an integer.\n */\n\nfunction integer() {\n return define('integer', value => {\n return typeof value === 'number' && !isNaN(value) && Number.isInteger(value) || \"Expected an integer, but received: \" + print(value);\n });\n}\nfunction intersection(Structs) {\n return new Struct({\n type: 'intersection',\n schema: null,\n\n *entries(value, ctx) {\n for (const S of Structs) {\n yield* S.entries(value, ctx);\n }\n },\n\n *validator(value, ctx) {\n for (const S of Structs) {\n yield* S.validator(value, ctx);\n }\n },\n\n *refiner(value, ctx) {\n for (const S of Structs) {\n yield* S.refiner(value, ctx);\n }\n }\n\n });\n}\nfunction literal(constant) {\n const description = print(constant);\n return define('literal', value => {\n return value === constant || \"Expected the literal `\" + description + \"`, but received: \" + print(value);\n });\n}\nfunction map(Key, Value) {\n return new Struct({\n type: 'map',\n schema: null,\n\n *entries(value) {\n if (Key && Value && value instanceof Map) {\n for (const [k, v] of value.entries()) {\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n\n coercer(value) {\n return value instanceof Map ? new Map(value) : value;\n },\n\n validator(value) {\n return value instanceof Map || \"Expected a `Map` object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that no value ever passes validation.\n */\n\nfunction never() {\n return define('never', () => false);\n}\n/**\n * Augment an existing struct to allow `null` values.\n */\n\nfunction nullable(struct) {\n return new Struct({ ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx)\n });\n}\n/**\n * Ensure that a value is a number.\n */\n\nfunction number() {\n return define('number', value => {\n return typeof value === 'number' && !isNaN(value) || \"Expected a number, but received: \" + print(value);\n });\n}\nfunction object(schema) {\n const knowns = schema ? Object.keys(schema) : [];\n const Never = never();\n return new Struct({\n type: 'object',\n schema: schema ? schema : null,\n\n *entries(value) {\n if (schema && isObject(value)) {\n const unknowns = new Set(Object.keys(value));\n\n for (const key of knowns) {\n unknowns.delete(key);\n yield [key, value[key], schema[key]];\n }\n\n for (const key of unknowns) {\n yield [key, value[key], Never];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n },\n\n coercer(value) {\n return isObject(value) ? { ...value\n } : value;\n }\n\n });\n}\n/**\n * Augment a struct to allow `undefined` values.\n */\n\nfunction optional(struct) {\n return new Struct({ ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx)\n });\n}\n/**\n * Ensure that a value is an object with keys and values of specific types, but\n * without ensuring any specific shape of properties.\n *\n * Like TypeScript's `Record` utility.\n */\n\nfunction record(Key, Value) {\n return new Struct({\n type: 'record',\n schema: null,\n\n *entries(value) {\n if (isObject(value)) {\n for (const k in value) {\n const v = value[k];\n yield [k, k, Key];\n yield [k, v, Value];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a `RegExp`.\n *\n * Note: this does not test the value against the regular expression! For that\n * you need to use the `pattern()` refinement.\n */\n\nfunction regexp() {\n return define('regexp', value => {\n return value instanceof RegExp;\n });\n}\nfunction set(Element) {\n return new Struct({\n type: 'set',\n schema: null,\n\n *entries(value) {\n if (Element && value instanceof Set) {\n for (const v of value) {\n yield [v, v, Element];\n }\n }\n },\n\n coercer(value) {\n return value instanceof Set ? new Set(value) : value;\n },\n\n validator(value) {\n return value instanceof Set || \"Expected a `Set` object, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value is a string.\n */\n\nfunction string() {\n return define('string', value => {\n return typeof value === 'string' || \"Expected a string, but received: \" + print(value);\n });\n}\nfunction tuple(Elements) {\n const Never = never();\n return new Struct({\n type: 'tuple',\n schema: null,\n\n *entries(value) {\n if (Array.isArray(value)) {\n const length = Math.max(Elements.length, value.length);\n\n for (let i = 0; i < length; i++) {\n yield [i, value[i], Elements[i] || Never];\n }\n }\n },\n\n validator(value) {\n return Array.isArray(value) || \"Expected an array, but received: \" + print(value);\n }\n\n });\n}\n/**\n * Ensure that a value has a set of known properties of specific types.\n *\n * Note: Unrecognized properties are allowed and untouched. This is similar to\n * how TypeScript's structural typing works.\n */\n\nfunction type(schema) {\n const keys = Object.keys(schema);\n return new Struct({\n type: 'type',\n schema,\n\n *entries(value) {\n if (isObject(value)) {\n for (const k of keys) {\n yield [k, value[k], schema[k]];\n }\n }\n },\n\n validator(value) {\n return isObject(value) || \"Expected an object, but received: \" + print(value);\n }\n\n });\n}\nfunction union(Structs) {\n const description = Structs.map(s => s.type).join(' | ');\n return new Struct({\n type: 'union',\n schema: null,\n\n validator(value, ctx) {\n const failures = [];\n\n for (const S of Structs) {\n const [...tuples] = run(value, S, ctx);\n const [first] = tuples;\n\n if (!first[0]) {\n return [];\n } else {\n for (const [failure] of tuples) {\n if (failure) {\n failures.push(failure);\n }\n }\n }\n }\n\n return [\"Expected the value to satisfy a union of `\" + description + \"`, but received: \" + print(value), ...failures];\n }\n\n });\n}\n/**\n * Ensure that any value passes validation, without widening its type to `any`.\n */\n\nfunction unknown() {\n return define('unknown', () => true);\n}\n\n/**\n * Augment a `Struct` to add an additional coercion step to its input.\n *\n * This allows you to transform input data before validating it, to increase the\n * likelihood that it passes validation—for example for default values, parsing\n * different formats, etc.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction coerce(struct, condition, coercer) {\n return new Struct({ ...struct,\n coercer: (value, ctx) => {\n return is(value, condition) ? struct.coercer(coercer(value, ctx), ctx) : struct.coercer(value, ctx);\n }\n });\n}\n/**\n * Augment a struct to replace `undefined` values with a default.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction defaulted(struct, fallback, options = {}) {\n return coerce(struct, unknown(), x => {\n const f = typeof fallback === 'function' ? fallback() : fallback;\n\n if (x === undefined) {\n return f;\n }\n\n if (!options.strict && isPlainObject(x) && isPlainObject(f)) {\n const ret = { ...x\n };\n let changed = false;\n\n for (const key in f) {\n if (ret[key] === undefined) {\n ret[key] = f[key];\n changed = true;\n }\n }\n\n if (changed) {\n return ret;\n }\n }\n\n return x;\n });\n}\n/**\n * Augment a struct to mask its input to only properties defined in the struct.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction masked(struct) {\n return coerce(struct, unknown(), x => {\n if (typeof struct.schema !== 'object' || struct.schema == null || typeof x !== 'object' || x == null) {\n return x;\n } else {\n const ret = {};\n\n for (const key in struct.schema) {\n if (key in x) {\n ret[key] = x[key];\n }\n }\n\n return ret;\n }\n });\n}\n/**\n * Augment a struct to trim string inputs.\n *\n * Note: You must use `create(value, Struct)` on the value to have the coercion\n * take effect! Using simply `assert()` or `is()` will not use coercion.\n */\n\nfunction trimmed(struct) {\n return coerce(struct, string(), x => x.trim());\n}\n\n/**\n * `Struct` objects encapsulate the validation logic for a specific type of\n * values. Once constructed, you use the `assert`, `is` or `validate` helpers to\n * validate unknown input data against the struct.\n */\n\nclass Struct {\n constructor(props) {\n const {\n type,\n schema,\n validator,\n refiner,\n coercer = value => value,\n entries = function* () {}\n } = props;\n this.type = type;\n this.schema = schema;\n this.entries = entries;\n this.coercer = coercer;\n\n if (validator) {\n this.validator = (value, context) => {\n const result = validator(value, context);\n return toFailures(result, context, this, value);\n };\n } else {\n this.validator = () => [];\n }\n\n if (refiner) {\n this.refiner = (value, context) => {\n const result = refiner(value, context);\n return toFailures(result, context, this, value);\n };\n } else {\n this.refiner = () => [];\n }\n }\n /**\n * Assert that a value passes the struct's validation, throwing if it doesn't.\n */\n\n\n assert(value) {\n return assert(value, this);\n }\n /**\n * Create a value with the struct's coercion logic, then validate it.\n */\n\n\n create(value) {\n return create(value, this);\n }\n /**\n * Check if a value passes the struct's validation.\n */\n\n\n is(value) {\n return is(value, this);\n }\n /**\n * Mask a value, coercing and validating it, but returning only the subset of\n * properties defined by the struct's schema.\n */\n\n\n mask(value) {\n return mask(value, this);\n }\n /**\n * Validate a value with the struct's validation logic, returning a tuple\n * representing the result.\n *\n * You may optionally pass `true` for the `withCoercion` argument to coerce\n * the value before attempting to validate it. If you do, the result will\n * contain the coerced result when successful.\n */\n\n\n validate(value, options = {}) {\n return validate(value, this, options);\n }\n\n}\n/**\n * Assert that a value passes a struct, throwing if it doesn't.\n */\n\nfunction assert(value, struct) {\n const result = validate(value, struct);\n\n if (result[0]) {\n throw result[0];\n }\n}\n/**\n * Create a value with the coercion logic of struct and validate it.\n */\n\nfunction create(value, struct) {\n const result = validate(value, struct, {\n coerce: true\n });\n\n if (result[0]) {\n throw result[0];\n } else {\n return result[1];\n }\n}\n/**\n * Mask a value, returning only the subset of properties defined by a struct.\n */\n\nfunction mask(value, struct) {\n const M = masked(struct);\n const ret = create(value, M);\n return ret;\n}\n/**\n * Check if a value passes a struct.\n */\n\nfunction is(value, struct) {\n const result = validate(value, struct);\n return !result[0];\n}\n/**\n * Validate a value against a struct, returning an error if invalid, or the\n * value (with potential coercion) if valid.\n */\n\nfunction validate(value, struct, options = {}) {\n const tuples = run(value, struct, options);\n const tuple = shiftIterator(tuples);\n\n if (tuple[0]) {\n const error = new StructError(tuple[0], function* () {\n for (const t of tuples) {\n if (t[0]) {\n yield t[0];\n }\n }\n });\n return [error, undefined];\n } else {\n const v = tuple[1];\n return [undefined, v];\n }\n}\n\n/**\n * Ensure that a string, array, map, or set is empty.\n */\n\nfunction empty(struct) {\n const expected = \"Expected an empty \" + struct.type;\n return refine(struct, 'empty', value => {\n if (value instanceof Map || value instanceof Set) {\n const {\n size\n } = value;\n return size === 0 || expected + \" but received one with a size of `\" + size + \"`\";\n } else {\n const {\n length\n } = value;\n return length === 0 || expected + \" but received one with a length of `\" + length + \"`\";\n }\n });\n}\n/**\n * Ensure that a number or date is below a threshold.\n */\n\nfunction max(struct, threshold, options = {}) {\n const {\n exclusive\n } = options;\n return refine(struct, 'max', value => {\n return exclusive ? value < threshold : value <= threshold || \"Expected a \" + struct.type + \" greater than \" + (exclusive ? '' : 'or equal to ') + threshold + \" but received `\" + value + \"`\";\n });\n}\n/**\n * Ensure that a number or date is above a threshold.\n */\n\nfunction min(struct, threshold, options = {}) {\n const {\n exclusive\n } = options;\n return refine(struct, 'min', value => {\n return exclusive ? value > threshold : value >= threshold || \"Expected a \" + struct.type + \" greater than \" + (exclusive ? '' : 'or equal to ') + threshold + \" but received `\" + value + \"`\";\n });\n}\n/**\n * Ensure that a string matches a regular expression.\n */\n\nfunction pattern(struct, regexp) {\n return refine(struct, 'pattern', value => {\n return regexp.test(value) || \"Expected a \" + struct.type + \" matching `/\" + regexp.source + \"/` but received \\\"\" + value + \"\\\"\";\n });\n}\n/**\n * Ensure that a string, array, number, date, map, or set has a size (or length, or time) between `min` and `max`.\n */\n\nfunction size(struct, min, max = min) {\n const expected = \"Expected a \" + struct.type;\n const of = min === max ? \"of `\" + min + \"`\" : \"between `\" + min + \"` and `\" + max + \"`\";\n return refine(struct, 'size', value => {\n if (typeof value === 'number' || value instanceof Date) {\n return min <= value && value <= max || expected + \" \" + of + \" but received `\" + value + \"`\";\n } else if (value instanceof Map || value instanceof Set) {\n const {\n size\n } = value;\n return min <= size && size <= max || expected + \" with a size \" + of + \" but received one with a size of `\" + size + \"`\";\n } else {\n const {\n length\n } = value;\n return min <= length && length <= max || expected + \" with a length \" + of + \" but received one with a length of `\" + length + \"`\";\n }\n });\n}\n/**\n * Augment a `Struct` to add an additional refinement to the validation.\n *\n * The refiner function is guaranteed to receive a value of the struct's type,\n * because the struct's existing validation will already have passed. This\n * allows you to layer additional validation on top of existing structs.\n */\n\nfunction refine(struct, name, refiner) {\n return new Struct({ ...struct,\n\n *refiner(value, ctx) {\n yield* struct.refiner(value, ctx);\n const result = refiner(value, ctx);\n const failures = toFailures(result, ctx, struct, value);\n\n for (const failure of failures) {\n yield { ...failure,\n refinement: name\n };\n }\n }\n\n });\n}\n\nexport { Struct, StructError, any, array, assert, assign, boolean, coerce, create, date, defaulted, define, dynamic, empty, enums, func, instance, integer, intersection, is, lazy, literal, map, mask, masked, max, min, never, nullable, number, object, omit, optional, partial, pattern, pick, record, refine, regexp, set, size, string, struct, trimmed, tuple, type, union, unknown, validate };\n//# sourceMappingURL=index.es.js.map\n","import { appendErrors, transformToNestObject } from 'react-hook-form';\nimport { StructError, validate } from 'superstruct';\n// @ts-expect-error maybe fixed after the first publish ?\nimport { convertArrayToPathName } from '@hookform/resolvers';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n error: StructError,\n validateAllFieldCriteria: boolean,\n) =>\n error\n .failures()\n .reduce((previous: Record<string, any>, { path, message = '', type }) => {\n const currentPath = convertArrayToPathName(path);\n return {\n ...previous,\n ...(path\n ? previous[currentPath] && validateAllFieldCriteria\n ? {\n [currentPath]: appendErrors(\n currentPath,\n validateAllFieldCriteria,\n previous,\n type || '',\n message,\n ),\n }\n : {\n [currentPath]: previous[currentPath] || {\n message,\n type,\n ...(validateAllFieldCriteria\n ? {\n types: { [type || '']: message || true },\n }\n : {}),\n },\n }\n : {}),\n };\n }, {});\n\nexport const superstructResolver: Resolver = (schema, options) => async (\n values,\n _context,\n { criteriaMode },\n) => {\n const [errors, result] = validate(values, schema, options);\n\n if (errors != null) {\n return {\n values: {},\n errors: transformToNestObject(\n parseErrorSchema(errors, criteriaMode === 'all'),\n ),\n };\n }\n\n return {\n values: result,\n errors: {},\n };\n};\n"],"names":["StructError","TypeError","[object Object]","failure","failures","cached","message","rest","path","super","length","join","Object","assign","this","name","constructor","_cached","run","value","struct","options","branch","coerce","ctx","coercer","valid","validator","undefined","k","v","s","entries","ts","t","Map","set","Set","add","x","refiner","validate","tuples","tuple","input","done","next","shiftIterator","schema","values","_context","error","validateAllFieldCriteria","criteriaMode","errors","result","transformToNestObject","reduce","previous","type","currentPath","convertArrayToPathName","appendErrors","types"],"mappings":"+kBAYA,MAAMA,UAAoBC,UACxBC,YAAYC,EAASC,GACnB,IAAIC,EACJ,MAAMC,QACJA,KACGC,GACDJ,GACEK,KACJA,GACEL,EAEJM,MAD4B,IAAhBD,EAAKE,OAAeJ,EAAU,YAAcE,EAAKG,KAAK,KAAO,OAASL,GAElFM,OAAOC,OAAOC,KAAMP,GACpBO,KAAKC,KAAOD,KAAKE,YAAYD,KAE7BD,KAAKV,SAAW,KACd,IAAIa,EAEJ,OAA6B,OAArBA,EAAUZ,GAAkBY,EAAUZ,EAAS,CAACF,KAAYC,OA8G1E,SAAUc,EAAIC,EAAOC,EAAQC,EAAU,IACrC,MAAMb,KACJA,EAAO,GAAEc,OACTA,EAAS,CAACH,GAAMI,OAChBA,GAAS,GACPF,EACEG,EAAM,CACVhB,KAAAA,EACAc,OAAAA,GAGEC,IACFJ,EAAQC,EAAOK,QAAQN,EAAOK,IAGhC,IAAIE,GAAQ,EAEZ,IAAK,MAAMvB,KAAWiB,EAAOO,UAAUR,EAAOK,GAC5CE,GAAQ,OACF,CAACvB,OAASyB,GAGlB,IAAK,IAAKC,EAAGC,EAAGC,KAAMX,EAAOY,QAAQb,EAAOK,GAAM,CAChD,MAAMS,EAAKf,EAAIY,EAAGC,EAAG,CACnBvB,UAAYoB,IAANC,EAAkBrB,EAAO,IAAIA,EAAMqB,GACzCP,YAAcM,IAANC,EAAkBP,EAAS,IAAIA,EAAQQ,GAC/CP,OAAAA,IAGF,IAAK,MAAMW,KAAKD,EACVC,EAAE,IACJR,GAAQ,OACF,CAACQ,EAAE,QAAIN,IACJL,IACTO,EAAII,EAAE,QAEIN,IAANC,EACFV,EAAQW,EACCX,aAAiBgB,IAC1BhB,EAAMiB,IAAIP,EAAGC,GACJX,aAAiBkB,IAC1BlB,EAAMmB,IAAIR,GArIE,iBADJS,EAuIUpB,IAtIW,MAALoB,IAuIxBpB,EAAMU,GAAKC,IAxIrB,IAAkBS,EA8IhB,GAAIb,EACF,IAAK,MAAMvB,KAAWiB,EAAOoB,QAAQrB,EAAOK,GAC1CE,GAAQ,OACF,CAACvB,OAASyB,GAIhBF,SACI,MAACE,EAAWT,IAqvBtB,SAASsB,EAAStB,EAAOC,EAAQC,EAAU,IACzC,MAAMqB,EAASxB,EAAIC,EAAOC,EAAQC,GAC5BsB,EAl3BR,SAAuBC,GACrB,MAAMC,KACJA,EAAI1B,MACJA,GACEyB,EAAME,OACV,OAAOD,OAAOjB,EAAYT,EA62BZ4B,CAAcL,GAE5B,OAAIC,EAAM,GAQD,CAPO,IAAI3C,EAAY2C,EAAM,GAAI,YACtC,IAAK,MAAMT,KAAKQ,EACVR,EAAE,WACEA,EAAE,WAICN,GAGR,MAACA,EADEe,EAAM,0BC95ByB,SAACK,EAAQ3B,mBACpD4B,EACAC,SArCAC,EACAC,EAqCEC,IAAAA,uBAEuBZ,EAASQ,EAAQD,EAAQ3B,GAA3CiC,OAAQC,OAEf,uBAAc,MAAVD,EACK,CACLL,OAAQ,GACRK,OAAQE,yBA7CZL,EA8CuBG,EA7CvBF,EA6CgD,QAAjBC,EA3C/BF,EACG/C,WACAqD,OAAO,SAACC,eAAiClD,IAAAA,SAAMF,QAAAA,aAAU,KAAIqD,IAAAA,KACtDC,EAAcC,yBAAuBrD,GAC3C,YACKkD,EACClD,EACAkD,EAASE,IAAgBR,UAEpBQ,GAAcE,eACbF,EACAR,EACAM,EACAC,GAAQ,GACRrD,cAIDsD,GAAcF,EAASE,OACtBtD,QAAAA,EACAqD,KAAAA,GACIP,EACA,CACEW,cAAUJ,GAAQ,IAAKrD,IAAW,MAEpC,OAGV,KAEL,OAkBE,CACL2C,OAAQM,EACRD,OAAQ,KAlBiC"}
1
+ {"version":3,"file":"superstruct.umd.js","sources":["../src/superstruct.ts"],"sourcesContent":["import { FieldError } from 'react-hook-form';\nimport { toNestError } from '@hookform/resolvers';\n\nimport { StructError, validate } from 'superstruct';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (error: StructError) =>\n error.failures().reduce<Record<string, FieldError>>(\n (previous, error) =>\n (previous[error.path.join('.')] = {\n message: error.message,\n type: error.type,\n }) && previous,\n {},\n );\n\nexport const superstructResolver: Resolver = (schema, resolverOptions) => (\n values,\n _,\n options,\n) => {\n const result = validate(values, schema, resolverOptions);\n\n return {\n values: result[1] || {},\n errors: result[0]\n ? toNestError(parseErrorSchema(result[0]), options.fields)\n : {},\n };\n};\n"],"names":["schema","resolverOptions","values","_","options","error","result","validate","errors","toNestError","failures","reduce","previous","path","join","message","type","fields"],"mappings":"4YAgB6C,SAACA,EAAQC,mBACpDC,EACAC,EACAC,GAEA,IAfwBC,EAelBC,EAASC,WAASL,EAAQF,EAAQC,GAExC,MAAO,CACLC,OAAQI,EAAO,IAAM,GACrBE,OAAQF,EAAO,GACXG,eApBkBJ,EAoBWC,EAAO,GAnB1CD,EAAMK,WAAWC,OACf,SAACC,EAAUP,UACRO,EAASP,EAAMQ,KAAKC,KAAK,MAAQ,CAChCC,QAASV,EAAMU,QACfC,KAAMX,EAAMW,QACRJ,GACR,KAa6CR,EAAQa,QACjD"}
@@ -1,5 +1,5 @@
1
1
  import { FieldValues, ResolverOptions, ResolverResult, UnpackNestedValue } from 'react-hook-form';
2
2
  import { validate, Struct } from 'superstruct';
3
3
  declare type Options = Parameters<typeof validate>[2];
4
- export declare type Resolver = <T extends Struct<any, any>>(schema: T, factoryOtions?: Options) => <TFieldValues extends FieldValues, TContext>(values: UnpackNestedValue<TFieldValues>, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
4
+ export declare type Resolver = <T extends Struct<any, any>>(schema: T, factoryOtions?: Options) => <TFieldValues extends FieldValues, TContext>(values: UnpackNestedValue<TFieldValues>, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => ResolverResult<TFieldValues>;
5
5
  export {};
@@ -12,6 +12,7 @@
12
12
  "license": "MIT",
13
13
  "peerDependencies": {
14
14
  "react-hook-form": ">=6.6.0",
15
- "@hookform/resolvers": "^1.0.0"
15
+ "@hookform/resolvers": "^1.0.0",
16
+ "superstruct": ">=0.12.0"
16
17
  }
17
18
  }
@@ -0,0 +1,73 @@
1
+ import { Field, InternalFieldName } from 'react-hook-form';
2
+ import {
3
+ object,
4
+ number,
5
+ string,
6
+ optional,
7
+ pattern,
8
+ size,
9
+ union,
10
+ min,
11
+ max,
12
+ Infer,
13
+ define,
14
+ array,
15
+ boolean,
16
+ } from 'superstruct';
17
+
18
+ const Password = define('Password', (value, ctx) =>
19
+ value === ctx.branch[0].password);
20
+
21
+ export const schema = object({
22
+ username: size(pattern(string(), /^\w+$/), 3, 30),
23
+ password: pattern(string(), /^[a-zA-Z0-9]{3,30}/),
24
+ repeatPassword: Password,
25
+ accessToken: optional(union([string(), number()])),
26
+ birthYear: optional(max(min(number(), 1900), 2013)),
27
+ email: optional(pattern(string(), /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)),
28
+ tags: array(string()),
29
+ enabled: boolean(),
30
+ like: optional(array(object({ id: number(), name: size(string(), 4) }))),
31
+ });
32
+
33
+ export const validData: Infer<typeof schema> = {
34
+ username: 'Doe',
35
+ password: 'Password123',
36
+ repeatPassword: 'Password123',
37
+ birthYear: 2000,
38
+ email: 'john@doe.com',
39
+ tags: ['tag1', 'tag2'],
40
+ enabled: true,
41
+ like: [
42
+ {
43
+ id: 1,
44
+ name: 'name',
45
+ },
46
+ ],
47
+ };
48
+
49
+ export const invalidData = {
50
+ password: '___',
51
+ email: '',
52
+ birthYear: 'birthYear',
53
+ like: [{ id: 'z' }],
54
+ };
55
+
56
+ export const fields: Record<InternalFieldName, Field['_f']> = {
57
+ username: {
58
+ ref: { name: 'username' },
59
+ name: 'username',
60
+ },
61
+ password: {
62
+ ref: { name: 'password' },
63
+ name: 'password',
64
+ },
65
+ email: {
66
+ ref: { name: 'email' },
67
+ name: 'email',
68
+ },
69
+ birthday: {
70
+ ref: { name: 'birthday' },
71
+ name: 'birthday',
72
+ },
73
+ };
@@ -5,88 +5,58 @@ Object {
5
5
  "errors": Object {
6
6
  "birthYear": Object {
7
7
  "message": "Expected a number, but received: \\"birthYear\\"",
8
+ "ref": undefined,
8
9
  "type": "number",
9
10
  },
10
11
  "email": Object {
11
12
  "message": "Expected a string matching \`/^[\\\\w-\\\\.]+@([\\\\w-]+\\\\.)+[\\\\w-]{2,4}$/\` but received \\"\\"",
12
- "type": "string",
13
- },
14
- "enabled": Object {
15
- "message": "Expected a value of type \`boolean\`, but received: \`undefined\`",
16
- "type": "boolean",
17
- },
18
- "password": Object {
19
- "message": "Expected a string matching \`/^[a-zA-Z0-9]{3,30}/\` but received \\"___\\"",
20
- "type": "string",
21
- },
22
- "repeatPassword": Object {
23
- "message": "Expected a value of type \`Password\`, but received: \`undefined\`",
24
- "type": "Password",
25
- },
26
- "tags": Object {
27
- "message": "Expected an array value, but received: undefined",
28
- "type": "array",
29
- },
30
- "username": Object {
31
- "message": "Expected a string, but received: undefined",
32
- "type": "string",
33
- },
34
- },
35
- "values": Object {},
36
- }
37
- `;
38
-
39
- exports[`superstructResolver should return all the errors from superstructResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
40
- Object {
41
- "errors": Object {
42
- "birthYear": Object {
43
- "message": "Expected a number, but received: \\"birthYear\\"",
44
- "type": "number",
45
- "types": Object {
46
- "number": "Expected a number, but received: \\"birthYear\\"",
13
+ "ref": Object {
14
+ "name": "email",
47
15
  },
48
- },
49
- "email": Object {
50
- "message": "Expected a string matching \`/^[\\\\w-\\\\.]+@([\\\\w-]+\\\\.)+[\\\\w-]{2,4}$/\` but received \\"\\"",
51
16
  "type": "string",
52
- "types": Object {
53
- "string": "Expected a string matching \`/^[\\\\w-\\\\.]+@([\\\\w-]+\\\\.)+[\\\\w-]{2,4}$/\` but received \\"\\"",
54
- },
55
17
  },
56
18
  "enabled": Object {
57
19
  "message": "Expected a value of type \`boolean\`, but received: \`undefined\`",
20
+ "ref": undefined,
58
21
  "type": "boolean",
59
- "types": Object {
60
- "boolean": "Expected a value of type \`boolean\`, but received: \`undefined\`",
61
- },
62
22
  },
23
+ "like": Array [
24
+ Object {
25
+ "id": Object {
26
+ "message": "Expected a number, but received: \\"z\\"",
27
+ "ref": undefined,
28
+ "type": "number",
29
+ },
30
+ "name": Object {
31
+ "message": "Expected a string, but received: undefined",
32
+ "ref": undefined,
33
+ "type": "string",
34
+ },
35
+ },
36
+ ],
63
37
  "password": Object {
64
38
  "message": "Expected a string matching \`/^[a-zA-Z0-9]{3,30}/\` but received \\"___\\"",
65
- "type": "string",
66
- "types": Object {
67
- "string": "Expected a string matching \`/^[a-zA-Z0-9]{3,30}/\` but received \\"___\\"",
39
+ "ref": Object {
40
+ "name": "password",
68
41
  },
42
+ "type": "string",
69
43
  },
70
44
  "repeatPassword": Object {
71
45
  "message": "Expected a value of type \`Password\`, but received: \`undefined\`",
46
+ "ref": undefined,
72
47
  "type": "Password",
73
- "types": Object {
74
- "Password": "Expected a value of type \`Password\`, but received: \`undefined\`",
75
- },
76
48
  },
77
49
  "tags": Object {
78
50
  "message": "Expected an array value, but received: undefined",
51
+ "ref": undefined,
79
52
  "type": "array",
80
- "types": Object {
81
- "array": "Expected an array value, but received: undefined",
82
- },
83
53
  },
84
54
  "username": Object {
85
55
  "message": "Expected a string, but received: undefined",
86
- "type": "string",
87
- "types": Object {
88
- "string": "Expected a string, but received: undefined",
56
+ "ref": Object {
57
+ "name": "username",
89
58
  },
59
+ "type": "string",
90
60
  },
91
61
  },
92
62
  "values": Object {},