main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

21
node_modules/@hookform/resolvers/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019-present Beier(Bill) Luo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

794
node_modules/@hookform/resolvers/README.md generated vendored Normal file
View File

@@ -0,0 +1,794 @@
<div align="center">
<p align="center">
<a href="https://react-hook-form.com" title="React Hook Form - Simple React forms validation">
<img src="https://raw.githubusercontent.com/bluebill1049/react-hook-form/master/docs/logo.png" alt="React Hook Form Logo - React hook custom hook for form validation" />
</a>
</p>
</div>
<p align="center">Performant, flexible and extensible forms with easy to use validation.</p>
<div align="center">
[![npm downloads](https://img.shields.io/npm/dm/@hookform/resolvers.svg?style=for-the-badge)](https://www.npmjs.com/package/@hookform/resolvers)
[![npm](https://img.shields.io/npm/dt/@hookform/resolvers.svg?style=for-the-badge)](https://www.npmjs.com/package/@hookform/resolvers)
[![npm](https://img.shields.io/bundlephobia/minzip/@hookform/resolvers?style=for-the-badge)](https://bundlephobia.com/result?p=@hookform/resolvers)
</div>
## Install
npm install @hookform/resolvers
## Links
- [React-hook-form validation resolver documentation ](https://react-hook-form.com/api/useform/#resolver)
### Supported resolvers
- [Install](#install)
- [Links](#links)
- [Supported resolvers](#supported-resolvers)
- [API](#api)
- [Quickstart](#quickstart)
- [Yup](#yup)
- [Zod](#zod)
- [Superstruct](#superstruct)
- [Joi](#joi)
- [Vest](#vest)
- [Class Validator](#class-validator)
- [io-ts](#io-ts)
- [Nope](#nope)
- [computed-types](#computed-types)
- [typanion](#typanion)
- [Ajv](#ajv)
- [TypeBox](#typebox)
- [With `ValueCheck`](#with-valuecheck)
- [With `TypeCompiler`](#with-typecompiler)
- [ArkType](#arktype)
- [Valibot](#valibot)
- [TypeSchema](#typeschema)
- [effect-ts](#effect-ts)
- [VineJS](#vinejs)
- [fluentvalidation-ts](#fluentvalidation-ts)
- [Backers](#backers)
- [Sponsors](#sponsors)
- [Contributors](#contributors)
## API
```
type Options = {
mode: 'async' | 'sync',
raw?: boolean
}
resolver(schema: object, schemaOptions?: object, resolverOptions: Options)
```
| | type | Required | Description |
| --------------- | -------- | -------- | --------------------------------------------- |
| schema | `object` | ✓ | validation schema |
| schemaOptions | `object` | | validation library schema options |
| resolverOptions | `object` | | resolver options, `async` is the default mode |
## Quickstart
### [Yup](https://github.com/jquense/yup)
Dead simple Object schema validation.
[![npm](https://img.shields.io/bundlephobia/minzip/yup?style=for-the-badge)](https://bundlephobia.com/result?p=yup)
```typescript jsx
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
const schema = yup
.object()
.shape({
name: yup.string().required(),
age: yup.number().required(),
})
.required();
const App = () => {
const { register, handleSubmit } = useForm({
resolver: yupResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
```
### [Zod](https://github.com/vriad/zod)
TypeScript-first schema validation with static type inference
[![npm](https://img.shields.io/bundlephobia/minzip/zod?style=for-the-badge)](https://bundlephobia.com/result?p=zod)
> ⚠️ Example below uses the `valueAsNumber`, which requires `react-hook-form` v6.12.0 (released Nov 28, 2020) or later.
```tsx
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
const schema = z.object({
name: z.string().min(1, { message: 'Required' }),
age: z.number().min(10),
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age', { valueAsNumber: true })} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
```
### [Superstruct](https://github.com/ianstormtaylor/superstruct)
A simple and composable way to validate data in JavaScript (or TypeScript).
[![npm](https://img.shields.io/bundlephobia/minzip/superstruct?style=for-the-badge)](https://bundlephobia.com/result?p=superstruct)
```typescript jsx
import { useForm } from 'react-hook-form';
import { superstructResolver } from '@hookform/resolvers/superstruct';
import { object, string, number } from 'superstruct';
const schema = object({
name: string(),
age: number(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: superstructResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age', { valueAsNumber: true })} />
<input type="submit" />
</form>
);
};
```
### [Joi](https://github.com/sideway/joi)
The most powerful data validation library for JS.
[![npm](https://img.shields.io/bundlephobia/minzip/joi?style=for-the-badge)](https://bundlephobia.com/result?p=joi)
```typescript jsx
import { useForm } from 'react-hook-form';
import { joiResolver } from '@hookform/resolvers/joi';
import Joi from 'joi';
const schema = Joi.object({
name: Joi.string().required(),
age: Joi.number().required(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: joiResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
```
### [Vest](https://github.com/ealush/vest)
Vest 🦺 Declarative Validation Testing.
[![npm](https://img.shields.io/bundlephobia/minzip/vest?style=for-the-badge)](https://bundlephobia.com/result?p=vest)
```typescript jsx
import { useForm } from 'react-hook-form';
import { vestResolver } from '@hookform/resolvers/vest';
import { create, test, enforce } from 'vest';
const validationSuite = create((data = {}) => {
test('username', 'Username is required', () => {
enforce(data.username).isNotEmpty();
});
test('password', 'Password is required', () => {
enforce(data.password).isNotEmpty();
});
});
const App = () => {
const { register, handleSubmit, errors } = useForm({
resolver: vestResolver(validationSuite),
});
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [Class Validator](https://github.com/typestack/class-validator)
Decorator-based property validation for classes.
[![npm](https://img.shields.io/bundlephobia/minzip/class-validator?style=for-the-badge)](https://bundlephobia.com/result?p=class-validator)
> ⚠️ Remember to add these options to your `tsconfig.json`!
```
"strictPropertyInitialization": false,
"experimentalDecorators": true
```
```tsx
import { useForm } from 'react-hook-form';
import { classValidatorResolver } from '@hookform/resolvers/class-validator';
import { Length, Min, IsEmail } from 'class-validator';
class User {
@Length(2, 30)
username: string;
@IsEmail()
email: string;
}
const resolver = classValidatorResolver(User);
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<User>({ resolver });
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input type="text" {...register('username')} />
{errors.username && <span>{errors.username.message}</span>}
<input type="text" {...register('email')} />
{errors.email && <span>{errors.email.message}</span>}
<input type="submit" value="Submit" />
</form>
);
};
```
### [io-ts](https://github.com/gcanti/io-ts)
Validate your data with powerful decoders.
[![npm](https://img.shields.io/bundlephobia/minzip/io-ts?style=for-the-badge)](https://bundlephobia.com/result?p=io-ts)
```typescript jsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { ioTsResolver } from '@hookform/resolvers/io-ts';
import t from 'io-ts';
// you don't have to use io-ts-types, but it's very useful
import tt from 'io-ts-types';
const schema = t.type({
username: t.string,
age: tt.NumberFromString,
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: ioTsResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
export default App;
```
### [Nope](https://github.com/bvego/nope-validator)
A small, simple, and fast JS validator
[![npm](https://img.shields.io/bundlephobia/minzip/nope-validator?style=for-the-badge)](https://bundlephobia.com/result?p=nope-validator)
```typescript jsx
import { useForm } from 'react-hook-form';
import { nopeResolver } from '@hookform/resolvers/nope';
import Nope from 'nope-validator';
const schema = Nope.object().shape({
name: Nope.string().required(),
age: Nope.number().required(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: nopeResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
```
### [computed-types](https://github.com/neuledge/computed-types)
TypeScript-first schema validation with static type inference
[![npm](https://img.shields.io/bundlephobia/minzip/computed-types?style=for-the-badge)](https://bundlephobia.com/result?p=computed-types)
```tsx
import { useForm } from 'react-hook-form';
import { computedTypesResolver } from '@hookform/resolvers/computed-types';
import Schema, { number, string } from 'computed-types';
const schema = Schema({
username: string.min(1).error('username field is required'),
age: number,
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: computedTypesResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age', { valueAsNumber: true })} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
```
### [typanion](https://github.com/arcanis/typanion)
Static and runtime type assertion library with no dependencies
[![npm](https://img.shields.io/bundlephobia/minzip/typanion?style=for-the-badge)](https://bundlephobia.com/result?p=typanion)
```tsx
import { useForm } from 'react-hook-form';
import { typanionResolver } from '@hookform/resolvers/typanion';
import * as t from 'typanion';
const isUser = t.isObject({
username: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
age: t.applyCascade(t.isNumber(), [
t.isInteger(),
t.isInInclusiveRange(1, 100),
]),
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: typanionResolver(isUser),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age')} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
```
### [Ajv](https://github.com/ajv-validator/ajv)
The fastest JSON validator for Node.js and browser
[![npm](https://img.shields.io/bundlephobia/minzip/ajv?style=for-the-badge)](https://bundlephobia.com/result?p=ajv)
```tsx
import { useForm } from 'react-hook-form';
import { ajvResolver } from '@hookform/resolvers/ajv';
// must use `minLength: 1` to implement required field
const schema = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 1,
errorMessage: { minLength: 'username field is required' },
},
password: {
type: 'string',
minLength: 1,
errorMessage: { minLength: 'password field is required' },
},
},
required: ['username', 'password'],
additionalProperties: false,
};
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: ajvResolver(schema),
});
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register('username')} />
{errors.username && <span>{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span>{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
};
```
### [TypeBox](https://github.com/sinclairzx81/typebox)
JSON Schema Type Builder with Static Type Resolution for TypeScript
[![npm](https://img.shields.io/bundlephobia/minzip/@sinclair/typebox?style=for-the-badge)](https://bundlephobia.com/result?p=@sinclair/typebox)
#### With `ValueCheck`
```typescript jsx
import { useForm } from 'react-hook-form';
import { typeboxResolver } from '@hookform/resolvers/typebox';
import { Type } from '@sinclair/typebox';
const schema = Type.Object({
username: Type.String({ minLength: 1 }),
password: Type.String({ minLength: 1 }),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: typeboxResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
#### With `TypeCompiler`
A high-performance JIT of `TypeBox`, [read more](https://github.com/sinclairzx81/typebox#typecompiler)
```typescript jsx
import { useForm } from 'react-hook-form';
import { typeboxResolver } from '@hookform/resolvers/typebox';
import { Type } from '@sinclair/typebox';
import { TypeCompiler } from '@sinclair/typebox/compiler';
const schema = Type.Object({
username: Type.String({ minLength: 1 }),
password: Type.String({ minLength: 1 }),
});
const typecheck = TypeCompiler.Compile(schema);
const App = () => {
const { register, handleSubmit } = useForm({
resolver: typeboxResolver(typecheck),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [ArkType](https://github.com/arktypeio/arktype)
TypeScript's 1:1 validator, optimized from editor to runtime
[![npm](https://img.shields.io/bundlephobia/minzip/arktype?style=for-the-badge)](https://bundlephobia.com/result?p=arktype)
```typescript jsx
import { useForm } from 'react-hook-form';
import { arktypeResolver } from '@hookform/resolvers/arktype';
import { type } from 'arktype';
const schema = type({
username: 'string>1',
password: 'string>1',
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: arktypeResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [Valibot](https://github.com/fabian-hiller/valibot)
The modular and type safe schema library for validating structural data
[![npm](https://img.shields.io/bundlephobia/minzip/valibot?style=for-the-badge)](https://bundlephobia.com/result?p=valibot)
```typescript jsx
import { useForm } from 'react-hook-form';
import { valibotResolver } from '@hookform/resolvers/valibot';
import * as v from 'valibot';
const schema = v.object({
username: v.pipe(
v.string('username is required'),
v.minLength(3, 'Needs to be at least 3 characters'),
v.endsWith('cool', 'Needs to end with `cool`'),
),
password: v.string('password is required'),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: valibotResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [TypeSchema](https://typeschema.com)
Universal adapter for schema validation, compatible with [any validation library](https://typeschema.com/#coverage)
[![npm](https://img.shields.io/bundlephobia/minzip/@typeschema/main?style=for-the-badge)](https://bundlephobia.com/result?p=@typeschema/main)
```typescript jsx
import { useForm } from 'react-hook-form';
import { typeschemaResolver } from '@hookform/resolvers/typeschema';
import * as z from 'zod';
// Use your favorite validation library
const schema = z.object({
username: z.string().min(1, { message: 'Required' }),
password: z.number().min(1, { message: 'Required' }),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: typeschemaResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [effect-ts](https://github.com/Effect-TS/effect)
A powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library.
[![npm](https://img.shields.io/bundlephobia/minzip/@effect/schema?style=for-the-badge)](https://bundlephobia.com/result?p=effect)
```typescript jsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '@hookform/resolvers/effect-ts';
import { Schema } from '@effect/schema';
const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmpty({ message: () => 'username required' }),
),
password: Schema.String.pipe(
Schema.nonEmpty({ message: () => 'password required' }),
),
});
type FormData = Schema.Schema.Type<typeof schema>;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
// provide generic if TS has issues inferring types
} = useForm<FormData>({
resolver: effectTsResolver(schema),
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
```
### [VineJS](https://github.com/vinejs/vine)
VineJS is a form data validation library for Node.js
[![npm](https://img.shields.io/bundlephobia/minzip/@vinejs/vine?style=for-the-badge)](https://bundlephobia.com/result?p=@vinejs/vine)
```typescript jsx
import { useForm } from 'react-hook-form';
import { vineResolver } from '@hookform/resolvers/vine';
import vine from '@vinejs/vine';
const schema = vine.compile(
vine.object({
username: vine.string().minLength(1),
password: vine.string().minLength(1),
}),
);
const App = () => {
const { register, handleSubmit } = useForm({
resolver: vineResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
};
```
### [fluentvalidation-ts](https://github.com/AlexJPotter/fluentvalidation-ts)
A TypeScript-first library for building strongly-typed validation rules
[![npm](https://img.shields.io/bundlephobia/minzip/@vinejs/vine?style=for-the-badge)](https://bundlephobia.com/result?p=@vinejs/vine)
```typescript jsx
import { useForm } from 'react-hook-form';
import { fluentValidationResolver } from '@hookform/resolvers/fluentvalidation-ts';
import { Validator } from 'fluentvalidation-ts';
class FormDataValidator extends Validator<FormData> {
constructor() {
super();
this.ruleFor('username')
.notEmpty()
.withMessage('username is a required field');
this.ruleFor('password')
.notEmpty()
.withMessage('password is a required field');
}
}
const App = () => {
const { register, handleSubmit } = useForm({
resolver: fluentValidationResolver(new FormDataValidator()),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
};
```
## Backers
Thanks go to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].
<a href="https://opencollective.com/react-hook-form#backers">
<img src="https://opencollective.com/react-hook-form/backers.svg?width=950" />
</a>
## Contributors
Thanks go to these wonderful people! [[Become a contributor](CONTRIBUTING.md)].
<a href="https://github.com/react-hook-form/react-hook-form/graphs/contributors">
<img src="https://opencollective.com/react-hook-form/contributors.svg?width=950" />
</a>

2
node_modules/@hookform/resolvers/ajv/dist/ajv.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import { Resolver } from './types';
export declare const ajvResolver: Resolver;

2
node_modules/@hookform/resolvers/ajv/dist/ajv.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
var e=require("@hookform/resolvers"),r=require("ajv"),a=require("ajv-errors"),s=require("react-hook-form");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/t(r),i=/*#__PURE__*/t(a),n=function(e,r){return e.forEach(function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty)}),e.reduce(function(e,a){var t=a.instancePath.substring(1).replace(/\//g,".");if(e[t]||(e[t]={message:a.message,type:a.keyword}),r){var o=e[t].types,i=o&&o[a.keyword];e[t]=s.appendErrors(t,r,e,a.keyword,i?[].concat(i,a.message||""):a.message)}return e},{})};exports.ajvResolver=function(r,a,s){return void 0===s&&(s={}),function(t,u,c){try{var l=new o.default(Object.assign({},{allErrors:!0,validateSchema:!0},a));i.default(l);var d=l.compile(Object.assign({$async:s&&"async"===s.mode},r)),v=d(t);return c.shouldUseNativeValidation&&e.validateFieldsNatively({},c),Promise.resolve(v?{values:t,errors:{}}:{values:{},errors:e.toNestErrors(n(d.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)})}catch(e){return Promise.reject(e)}}};
//# sourceMappingURL=ajv.js.map

1
node_modules/@hookform/resolvers/ajv/dist/ajv.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"ajv.js","sources":["../src/ajv.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport Ajv, { DefinedError } from 'ajv';\nimport ajvErrors from 'ajv-errors';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n ajvErrors: DefinedError[],\n validateAllFieldCriteria: boolean,\n) => {\n // Ajv will return empty instancePath when require error\n ajvErrors.forEach((error) => {\n if (error.keyword === 'required') {\n error.instancePath += '/' + error.params.missingProperty;\n }\n });\n\n return ajvErrors.reduce<Record<string, FieldError>>((previous, error) => {\n // `/deepObject/data` -> `deepObject.data`\n const path = error.instancePath.substring(1).replace(/\\//g, '.');\n\n if (!previous[path]) {\n previous[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = previous[path].types;\n const messages = types && types[error.keyword];\n\n previous[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n previous,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n\n return previous;\n }, {});\n};\n\nexport const ajvResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, options) => {\n const ajv = new Ajv(\n Object.assign(\n {},\n {\n allErrors: true,\n validateSchema: true,\n },\n schemaOptions,\n ),\n );\n\n ajvErrors(ajv);\n\n const validate = ajv.compile(\n Object.assign(\n { $async: resolverOptions && resolverOptions.mode === 'async' },\n schema,\n ),\n );\n\n const valid = validate(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return valid\n ? { values, errors: {} }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validate.errors as DefinedError[],\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n"],"names":["parseErrorSchema","ajvErrors","validateAllFieldCriteria","forEach","error","keyword","instancePath","params","missingProperty","reduce","previous","path","substring","replace","message","type","types","messages","appendErrors","concat","schema","schemaOptions","resolverOptions","values","_","options","ajv","Ajv","Object","assign","allErrors","validateSchema","validate","compile","$async","mode","valid","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","errors","toNestErrors","criteriaMode","e","reject"],"mappings":"+NAMMA,EAAmB,SACvBC,EACAC,GASA,OANAD,EAAUE,QAAQ,SAACC,GACK,aAAlBA,EAAMC,UACRD,EAAME,cAAgB,IAAMF,EAAMG,OAAOC,gBAE7C,GAEOP,EAAUQ,OAAmC,SAACC,EAAUN,GAE7D,IAAMO,EAAOP,EAAME,aAAaM,UAAU,GAAGC,QAAQ,MAAO,KAS5D,GAPKH,EAASC,KACZD,EAASC,GAAQ,CACfG,QAASV,EAAMU,QACfC,KAAMX,EAAMC,UAIZH,EAA0B,CAC5B,IAAMc,EAAQN,EAASC,GAAMK,MACvBC,EAAWD,GAASA,EAAMZ,EAAMC,SAEtCK,EAASC,GAAQO,eACfP,EACAT,EACAQ,EACAN,EAAMC,QACNY,EACK,GAAgBE,OAAOF,EAAsBb,EAAMU,SAAW,IAC/DV,EAAMU,QAEd,CAEA,OAAOJ,CACT,EAAG,GACL,sBAGE,SAACU,EAAQC,EAAeC,GAAoB,gBAApBA,IAAAA,EAAkB,CAAA,GAAE,SACrCC,EAAQC,EAAGC,GAAO,IACvB,IAAMC,EAAM,IAAIC,UACdC,OAAOC,OACL,CAAE,EACF,CACEC,WAAW,EACXC,gBAAgB,GAElBV,IAIJpB,EAAS,QAACyB,GAEV,IAAMM,EAAWN,EAAIO,QACnBL,OAAOC,OACL,CAAEK,OAAQZ,GAA4C,UAAzBA,EAAgBa,MAC7Cf,IAIEgB,EAAQJ,EAAST,GAIvB,OAFAE,EAAQY,2BAA6BC,EAAAA,uBAAuB,CAAE,EAAEb,GAEhEc,QAAAC,QAAOJ,EACH,CAAEb,OAAAA,EAAQkB,OAAQ,CAAI,GACtB,CACElB,OAAQ,CAAA,EACRkB,OAAQC,eACN1C,EACEgC,EAASS,QACRhB,EAAQY,2BACkB,QAAzBZ,EAAQkB,cAEZlB,IAGV,CAAC,MAAAmB,GAAA,OAAAL,QAAAM,OAAAD,EAAA,CAAA,CAAA"}

2
node_modules/@hookform/resolvers/ajv/dist/ajv.mjs generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import o from"ajv";import a from"ajv-errors";import{appendErrors as s}from"react-hook-form";var t=function(r,e){return r.forEach(function(r){"required"===r.keyword&&(r.instancePath+="/"+r.params.missingProperty)}),r.reduce(function(r,o){var a=o.instancePath.substring(1).replace(/\//g,".");if(r[a]||(r[a]={message:o.message,type:o.keyword}),e){var t=r[a].types,i=t&&t[o.keyword];r[a]=s(a,e,r,o.keyword,i?[].concat(i,o.message||""):o.message)}return r},{})},i=function(s,i,n){return void 0===n&&(n={}),function(c,m,u){try{var l=new o(Object.assign({},{allErrors:!0,validateSchema:!0},i));a(l);var v=l.compile(Object.assign({$async:n&&"async"===n.mode},s)),d=v(c);return u.shouldUseNativeValidation&&r({},u),Promise.resolve(d?{values:c,errors:{}}:{values:{},errors:e(t(v.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)})}catch(r){return Promise.reject(r)}}};export{i as ajvResolver};
//# sourceMappingURL=ajv.module.js.map

View File

@@ -0,0 +1,2 @@
import{validateFieldsNatively as e,toNestErrors as r}from"@hookform/resolvers";import s from"ajv";import o from"ajv-errors";import{appendErrors as a}from"react-hook-form";const t=(e,r)=>(e.forEach(e=>{"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty)}),e.reduce((e,s)=>{const o=s.instancePath.substring(1).replace(/\//g,".");if(e[o]||(e[o]={message:s.message,type:s.keyword}),r){const t=e[o].types,i=t&&t[s.keyword];e[o]=a(o,r,e,s.keyword,i?[].concat(i,s.message||""):s.message)}return e},{})),i=(a,i,n={})=>async(c,m,l)=>{const d=new s(Object.assign({},{allErrors:!0,validateSchema:!0},i));o(d);const p=d.compile(Object.assign({$async:n&&"async"===n.mode},a)),y=p(c);return l.shouldUseNativeValidation&&e({},l),y?{values:c,errors:{}}:{values:{},errors:r(t(p.errors,!l.shouldUseNativeValidation&&"all"===l.criteriaMode),l)}};export{i as ajvResolver};
//# sourceMappingURL=ajv.modern.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ajv.modern.mjs","sources":["../src/ajv.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport Ajv, { DefinedError } from 'ajv';\nimport ajvErrors from 'ajv-errors';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n ajvErrors: DefinedError[],\n validateAllFieldCriteria: boolean,\n) => {\n // Ajv will return empty instancePath when require error\n ajvErrors.forEach((error) => {\n if (error.keyword === 'required') {\n error.instancePath += '/' + error.params.missingProperty;\n }\n });\n\n return ajvErrors.reduce<Record<string, FieldError>>((previous, error) => {\n // `/deepObject/data` -> `deepObject.data`\n const path = error.instancePath.substring(1).replace(/\\//g, '.');\n\n if (!previous[path]) {\n previous[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = previous[path].types;\n const messages = types && types[error.keyword];\n\n previous[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n previous,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n\n return previous;\n }, {});\n};\n\nexport const ajvResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, options) => {\n const ajv = new Ajv(\n Object.assign(\n {},\n {\n allErrors: true,\n validateSchema: true,\n },\n schemaOptions,\n ),\n );\n\n ajvErrors(ajv);\n\n const validate = ajv.compile(\n Object.assign(\n { $async: resolverOptions && resolverOptions.mode === 'async' },\n schema,\n ),\n );\n\n const valid = validate(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return valid\n ? { values, errors: {} }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validate.errors as DefinedError[],\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n"],"names":["parseErrorSchema","ajvErrors","validateAllFieldCriteria","forEach","error","keyword","instancePath","params","missingProperty","reduce","previous","path","substring","replace","message","type","types","messages","appendErrors","concat","ajvResolver","schema","schemaOptions","resolverOptions","async","values","_","options","ajv","Ajv","Object","assign","allErrors","validateSchema","validate","compile","$async","mode","valid","shouldUseNativeValidation","validateFieldsNatively","errors","toNestErrors","criteriaMode"],"mappings":"2KAMA,MAAMA,EAAmBA,CACvBC,EACAC,KAGAD,EAAUE,QAASC,IACK,aAAlBA,EAAMC,UACRD,EAAME,cAAgB,IAAMF,EAAMG,OAAOC,gBAC3C,GAGKP,EAAUQ,OAAmC,CAACC,EAAUN,KAE7D,MAAMO,EAAOP,EAAME,aAAaM,UAAU,GAAGC,QAAQ,MAAO,KAS5D,GAPKH,EAASC,KACZD,EAASC,GAAQ,CACfG,QAASV,EAAMU,QACfC,KAAMX,EAAMC,UAIZH,EAA0B,CAC5B,MAAMc,EAAQN,EAASC,GAAMK,MACvBC,EAAWD,GAASA,EAAMZ,EAAMC,SAEtCK,EAASC,GAAQO,EACfP,EACAT,EACAQ,EACAN,EAAMC,QACNY,EACK,GAAgBE,OAAOF,EAAsBb,EAAMU,SAAW,IAC/DV,EAAMU,QAEd,CAEA,OAAOJ,GACN,KAGQU,EACXA,CAACC,EAAQC,EAAeC,EAAkB,KAC1CC,MAAOC,EAAQC,EAAGC,KAChB,MAAMC,EAAM,IAAIC,EACdC,OAAOC,OACL,CAAE,EACF,CACEC,WAAW,EACXC,gBAAgB,GAElBX,IAIJrB,EAAU2B,GAEV,MAAMM,EAAWN,EAAIO,QACnBL,OAAOC,OACL,CAAEK,OAAQb,GAA4C,UAAzBA,EAAgBc,MAC7ChB,IAIEiB,EAAQJ,EAAST,GAIvB,OAFAE,EAAQY,2BAA6BC,EAAuB,GAAIb,GAEzDW,EACH,CAAEb,SAAQgB,OAAQ,CAAA,GAClB,CACEhB,OAAQ,GACRgB,OAAQC,EACN1C,EACEkC,EAASO,QACRd,EAAQY,2BACkB,QAAzBZ,EAAQgB,cAEZhB"}

View File

@@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import o from"ajv";import a from"ajv-errors";import{appendErrors as s}from"react-hook-form";var t=function(r,e){return r.forEach(function(r){"required"===r.keyword&&(r.instancePath+="/"+r.params.missingProperty)}),r.reduce(function(r,o){var a=o.instancePath.substring(1).replace(/\//g,".");if(r[a]||(r[a]={message:o.message,type:o.keyword}),e){var t=r[a].types,i=t&&t[o.keyword];r[a]=s(a,e,r,o.keyword,i?[].concat(i,o.message||""):o.message)}return r},{})},i=function(s,i,n){return void 0===n&&(n={}),function(c,m,u){try{var l=new o(Object.assign({},{allErrors:!0,validateSchema:!0},i));a(l);var v=l.compile(Object.assign({$async:n&&"async"===n.mode},s)),d=v(c);return u.shouldUseNativeValidation&&r({},u),Promise.resolve(d?{values:c,errors:{}}:{values:{},errors:e(t(v.errors,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)})}catch(r){return Promise.reject(r)}}};export{i as ajvResolver};
//# sourceMappingURL=ajv.module.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ajv.module.js","sources":["../src/ajv.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport Ajv, { DefinedError } from 'ajv';\nimport ajvErrors from 'ajv-errors';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n ajvErrors: DefinedError[],\n validateAllFieldCriteria: boolean,\n) => {\n // Ajv will return empty instancePath when require error\n ajvErrors.forEach((error) => {\n if (error.keyword === 'required') {\n error.instancePath += '/' + error.params.missingProperty;\n }\n });\n\n return ajvErrors.reduce<Record<string, FieldError>>((previous, error) => {\n // `/deepObject/data` -> `deepObject.data`\n const path = error.instancePath.substring(1).replace(/\\//g, '.');\n\n if (!previous[path]) {\n previous[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = previous[path].types;\n const messages = types && types[error.keyword];\n\n previous[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n previous,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n\n return previous;\n }, {});\n};\n\nexport const ajvResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, options) => {\n const ajv = new Ajv(\n Object.assign(\n {},\n {\n allErrors: true,\n validateSchema: true,\n },\n schemaOptions,\n ),\n );\n\n ajvErrors(ajv);\n\n const validate = ajv.compile(\n Object.assign(\n { $async: resolverOptions && resolverOptions.mode === 'async' },\n schema,\n ),\n );\n\n const valid = validate(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return valid\n ? { values, errors: {} }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validate.errors as DefinedError[],\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n"],"names":["parseErrorSchema","ajvErrors","validateAllFieldCriteria","forEach","error","keyword","instancePath","params","missingProperty","reduce","previous","path","substring","replace","message","type","types","messages","appendErrors","concat","ajvResolver","schema","schemaOptions","resolverOptions","values","_","options","ajv","Ajv","Object","assign","allErrors","validateSchema","validate","compile","$async","mode","valid","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","errors","toNestErrors","criteriaMode","e","reject"],"mappings":"2KAMA,IAAMA,EAAmB,SACvBC,EACAC,GASA,OANAD,EAAUE,QAAQ,SAACC,GACK,aAAlBA,EAAMC,UACRD,EAAME,cAAgB,IAAMF,EAAMG,OAAOC,gBAE7C,GAEOP,EAAUQ,OAAmC,SAACC,EAAUN,GAE7D,IAAMO,EAAOP,EAAME,aAAaM,UAAU,GAAGC,QAAQ,MAAO,KAS5D,GAPKH,EAASC,KACZD,EAASC,GAAQ,CACfG,QAASV,EAAMU,QACfC,KAAMX,EAAMC,UAIZH,EAA0B,CAC5B,IAAMc,EAAQN,EAASC,GAAMK,MACvBC,EAAWD,GAASA,EAAMZ,EAAMC,SAEtCK,EAASC,GAAQO,EACfP,EACAT,EACAQ,EACAN,EAAMC,QACNY,EACK,GAAgBE,OAAOF,EAAsBb,EAAMU,SAAW,IAC/DV,EAAMU,QAEd,CAEA,OAAOJ,CACT,EAAG,GACL,EAEaU,EACX,SAACC,EAAQC,EAAeC,GAAoB,gBAApBA,IAAAA,EAAkB,CAAA,GAAE,SACrCC,EAAQC,EAAGC,GAAO,IACvB,IAAMC,EAAM,IAAIC,EACdC,OAAOC,OACL,CAAE,EACF,CACEC,WAAW,EACXC,gBAAgB,GAElBV,IAIJrB,EAAU0B,GAEV,IAAMM,EAAWN,EAAIO,QACnBL,OAAOC,OACL,CAAEK,OAAQZ,GAA4C,UAAzBA,EAAgBa,MAC7Cf,IAIEgB,EAAQJ,EAAST,GAIvB,OAFAE,EAAQY,2BAA6BC,EAAuB,CAAE,EAAEb,GAEhEc,QAAAC,QAAOJ,EACH,CAAEb,OAAAA,EAAQkB,OAAQ,CAAI,GACtB,CACElB,OAAQ,CAAA,EACRkB,OAAQC,EACN3C,EACEiC,EAASS,QACRhB,EAAQY,2BACkB,QAAzBZ,EAAQkB,cAEZlB,IAGV,CAAC,MAAAmB,GAAA,OAAAL,QAAAM,OAAAD,EAAA,CAAA,CAAA"}

2
node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("ajv"),require("ajv-errors"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","ajv","ajv-errors","react-hook-form"],r):r((e||self).hookformResolversAjv={},e.hookformResolvers,e.ajv,e.ajvErrors,e.ReactHookForm)}(this,function(e,r,o,a,s){function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/t(o),n=/*#__PURE__*/t(a),u=function(e,r){return e.forEach(function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty)}),e.reduce(function(e,o){var a=o.instancePath.substring(1).replace(/\//g,".");if(e[a]||(e[a]={message:o.message,type:o.keyword}),r){var t=e[a].types,i=t&&t[o.keyword];e[a]=s.appendErrors(a,r,e,o.keyword,i?[].concat(i,o.message||""):o.message)}return e},{})};e.ajvResolver=function(e,o,a){return void 0===a&&(a={}),function(s,t,f){try{var l=new i.default(Object.assign({},{allErrors:!0,validateSchema:!0},o));n.default(l);var c=l.compile(Object.assign({$async:a&&"async"===a.mode},e)),d=c(s);return f.shouldUseNativeValidation&&r.validateFieldsNatively({},f),Promise.resolve(d?{values:s,errors:{}}:{values:{},errors:r.toNestErrors(u(c.errors,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)})}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=ajv.umd.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ajv.umd.js","sources":["../src/ajv.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport Ajv, { DefinedError } from 'ajv';\nimport ajvErrors from 'ajv-errors';\nimport { FieldError, appendErrors } from 'react-hook-form';\nimport { Resolver } from './types';\n\nconst parseErrorSchema = (\n ajvErrors: DefinedError[],\n validateAllFieldCriteria: boolean,\n) => {\n // Ajv will return empty instancePath when require error\n ajvErrors.forEach((error) => {\n if (error.keyword === 'required') {\n error.instancePath += '/' + error.params.missingProperty;\n }\n });\n\n return ajvErrors.reduce<Record<string, FieldError>>((previous, error) => {\n // `/deepObject/data` -> `deepObject.data`\n const path = error.instancePath.substring(1).replace(/\\//g, '.');\n\n if (!previous[path]) {\n previous[path] = {\n message: error.message,\n type: error.keyword,\n };\n }\n\n if (validateAllFieldCriteria) {\n const types = previous[path].types;\n const messages = types && types[error.keyword];\n\n previous[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n previous,\n error.keyword,\n messages\n ? ([] as string[]).concat(messages as string[], error.message || '')\n : error.message,\n ) as FieldError;\n }\n\n return previous;\n }, {});\n};\n\nexport const ajvResolver: Resolver =\n (schema, schemaOptions, resolverOptions = {}) =>\n async (values, _, options) => {\n const ajv = new Ajv(\n Object.assign(\n {},\n {\n allErrors: true,\n validateSchema: true,\n },\n schemaOptions,\n ),\n );\n\n ajvErrors(ajv);\n\n const validate = ajv.compile(\n Object.assign(\n { $async: resolverOptions && resolverOptions.mode === 'async' },\n schema,\n ),\n );\n\n const valid = validate(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return valid\n ? { values, errors: {} }\n : {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n validate.errors as DefinedError[],\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n };\n"],"names":["parseErrorSchema","ajvErrors","validateAllFieldCriteria","forEach","error","keyword","instancePath","params","missingProperty","reduce","previous","path","substring","replace","message","type","types","messages","appendErrors","concat","schema","schemaOptions","resolverOptions","values","_","options","ajv","Ajv","Object","assign","allErrors","validateSchema","validate","compile","$async","mode","valid","shouldUseNativeValidation","validateFieldsNatively","Promise","resolve","errors","toNestErrors","criteriaMode","e","reject"],"mappings":"0jBAMMA,EAAmB,SACvBC,EACAC,GASA,OANAD,EAAUE,QAAQ,SAACC,GACK,aAAlBA,EAAMC,UACRD,EAAME,cAAgB,IAAMF,EAAMG,OAAOC,gBAE7C,GAEOP,EAAUQ,OAAmC,SAACC,EAAUN,GAE7D,IAAMO,EAAOP,EAAME,aAAaM,UAAU,GAAGC,QAAQ,MAAO,KAS5D,GAPKH,EAASC,KACZD,EAASC,GAAQ,CACfG,QAASV,EAAMU,QACfC,KAAMX,EAAMC,UAIZH,EAA0B,CAC5B,IAAMc,EAAQN,EAASC,GAAMK,MACvBC,EAAWD,GAASA,EAAMZ,EAAMC,SAEtCK,EAASC,GAAQO,eACfP,EACAT,EACAQ,EACAN,EAAMC,QACNY,EACK,GAAgBE,OAAOF,EAAsBb,EAAMU,SAAW,IAC/DV,EAAMU,QAEd,CAEA,OAAOJ,CACT,EAAG,GACL,gBAGE,SAACU,EAAQC,EAAeC,GAAoB,gBAApBA,IAAAA,EAAkB,CAAA,GAAE,SACrCC,EAAQC,EAAGC,GAAO,IACvB,IAAMC,EAAM,IAAIC,UACdC,OAAOC,OACL,CAAE,EACF,CACEC,WAAW,EACXC,gBAAgB,GAElBV,IAIJpB,EAAS,QAACyB,GAEV,IAAMM,EAAWN,EAAIO,QACnBL,OAAOC,OACL,CAAEK,OAAQZ,GAA4C,UAAzBA,EAAgBa,MAC7Cf,IAIEgB,EAAQJ,EAAST,GAIvB,OAFAE,EAAQY,2BAA6BC,EAAAA,uBAAuB,CAAE,EAAEb,GAEhEc,QAAAC,QAAOJ,EACH,CAAEb,OAAAA,EAAQkB,OAAQ,CAAI,GACtB,CACElB,OAAQ,CAAA,EACRkB,OAAQC,eACN1C,EACEgC,EAASS,QACRhB,EAAQY,2BACkB,QAAzBZ,EAAQkB,cAEZlB,IAGV,CAAC,MAAAmB,GAAA,OAAAL,QAAAM,OAAAD,EAAA,CAAA,CAAA"}

2
node_modules/@hookform/resolvers/ajv/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export * from './ajv';
export * from './types';

5
node_modules/@hookform/resolvers/ajv/dist/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import * as Ajv from 'ajv';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T>(schema: Ajv.JSONSchemaType<T>, schemaOptions?: Ajv.Options, factoryOptions?: {
mode?: 'async' | 'sync';
}) => <TFieldValues extends FieldValues, TContext>(values: TFieldValues, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;

19
node_modules/@hookform/resolvers/ajv/package.json generated vendored Normal file
View File

@@ -0,0 +1,19 @@
{
"name": "@hookform/resolvers/ajv",
"amdName": "hookformResolversAjv",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: ajv",
"main": "dist/ajv.js",
"module": "dist/ajv.module.js",
"umd:main": "dist/ajv.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.0.0",
"@hookform/resolvers": "^2.0.0",
"ajv": "^8.12.0",
"ajv-errors": "^3.0.0"
}
}

View File

@@ -0,0 +1,94 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { JSONSchemaType } from 'ajv';
import React from 'react';
import { useForm } from 'react-hook-form';
import { ajvResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
type FormData = { username: string; password: string };
const schema: JSONSchemaType<FormData> = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 1,
errorMessage: { minLength: USERNAME_REQUIRED_MESSAGE },
},
password: {
type: 'string',
minLength: 1,
errorMessage: { minLength: PASSWORD_REQUIRED_MESSAGE },
},
},
required: ['username', 'password'],
additionalProperties: false,
};
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: ajvResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Ajv", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View File

@@ -0,0 +1,65 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { JSONSchemaType } from 'ajv';
import React from 'react';
import { useForm } from 'react-hook-form';
import { ajvResolver } from '..';
type FormData = { username: string; password: string };
const schema: JSONSchemaType<FormData> = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 1,
errorMessage: { minLength: 'username field is required' },
},
password: {
type: 'string',
minLength: 1,
errorMessage: { minLength: 'password field is required' },
},
},
required: ['username', 'password'],
additionalProperties: false,
};
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<FormData>({
resolver: ajvResolver(schema), // Useful to check TypeScript regressions
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with Ajv and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(screen.getByText(/username field is required/i)).toBeInTheDocument();
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,90 @@
import { JSONSchemaType } from 'ajv';
import { Field, InternalFieldName } from 'react-hook-form';
interface Data {
username: string;
password: string;
deepObject: { data: string; twoLayersDeep: { name: string } };
}
export const schema: JSONSchemaType<Data> = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 3,
},
password: {
type: 'string',
pattern: '.*[A-Z].*',
errorMessage: {
pattern: 'One uppercase character',
},
},
deepObject: {
type: 'object',
properties: {
data: { type: 'string' },
twoLayersDeep: {
type: 'object',
properties: { name: { type: 'string' } },
additionalProperties: false,
required: ['name'],
},
},
required: ['data', 'twoLayersDeep'],
},
},
required: ['username', 'password', 'deepObject'],
additionalProperties: false,
};
export const validData: Data = {
username: 'jsun969',
password: 'validPassword',
deepObject: {
twoLayersDeep: {
name: 'deeper',
},
data: 'data',
},
};
export const invalidData = {
username: '__',
password: 'invalid-password',
deepObject: {
data: 233,
twoLayersDeep: { name: 123 },
},
};
export const invalidDataWithUndefined = {
username: 'jsun969',
password: undefined,
deepObject: {
twoLayersDeep: {
name: 'deeper',
},
data: undefined,
},
};
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View File

@@ -0,0 +1,245 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true 1`] = `
{
"errors": {
"deepObject": {
"message": "must have required property 'deepObject'",
"ref": undefined,
"type": "required",
},
"password": {
"message": "must have required property 'password'",
"ref": {
"name": "password",
},
"type": "required",
},
"username": {
"message": "must have required property 'username'",
"ref": {
"name": "username",
},
"type": "required",
},
},
"values": {},
}
`;
exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true and \`mode: sync\` 1`] = `
{
"errors": {
"deepObject": {
"message": "must have required property 'deepObject'",
"ref": undefined,
"type": "required",
},
"password": {
"message": "must have required property 'password'",
"ref": {
"name": "password",
},
"type": "required",
},
"username": {
"message": "must have required property 'username'",
"ref": {
"name": "username",
},
"type": "required",
},
},
"values": {},
}
`;
exports[`ajvResolver > should return all the error messages from ajvResolver when some property is undefined and result will keep the input data structure 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must have required property 'data'",
"ref": undefined,
"type": "required",
},
},
"password": {
"message": "must have required property 'password'",
"ref": {
"name": "password",
},
"type": "required",
},
},
"values": {},
}
`;
exports[`ajvResolver > should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must be string",
"ref": undefined,
"type": "type",
"types": {
"type": "must be string",
},
},
"twoLayersDeep": {
"name": {
"message": "must be string",
"ref": undefined,
"type": "type",
"types": {
"type": "must be string",
},
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "errorMessage",
"types": {
"errorMessage": "One uppercase character",
},
},
"username": {
"message": "must NOT have fewer than 3 characters",
"ref": {
"name": "username",
},
"type": "minLength",
"types": {
"minLength": "must NOT have fewer than 3 characters",
},
},
},
"values": {},
}
`;
exports[`ajvResolver > should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true and \`mode: sync\` 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must be string",
"ref": undefined,
"type": "type",
"types": {
"type": "must be string",
},
},
"twoLayersDeep": {
"name": {
"message": "must be string",
"ref": undefined,
"type": "type",
"types": {
"type": "must be string",
},
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "errorMessage",
"types": {
"errorMessage": "One uppercase character",
},
},
"username": {
"message": "must NOT have fewer than 3 characters",
"ref": {
"name": "username",
},
"type": "minLength",
"types": {
"minLength": "must NOT have fewer than 3 characters",
},
},
},
"values": {},
}
`;
exports[`ajvResolver > should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must be string",
"ref": undefined,
"type": "type",
},
"twoLayersDeep": {
"name": {
"message": "must be string",
"ref": undefined,
"type": "type",
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "errorMessage",
},
"username": {
"message": "must NOT have fewer than 3 characters",
"ref": {
"name": "username",
},
"type": "minLength",
},
},
"values": {},
}
`;
exports[`ajvResolver > should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false and \`mode: sync\` 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must be string",
"ref": undefined,
"type": "type",
},
"twoLayersDeep": {
"name": {
"message": "must be string",
"ref": undefined,
"type": "type",
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "errorMessage",
},
"username": {
"message": "must NOT have fewer than 3 characters",
"ref": {
"name": "username",
},
"type": "minLength",
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,103 @@
import { ajvResolver } from '..';
import {
fields,
invalidData,
invalidDataWithUndefined,
schema,
validData,
} from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('ajvResolver', () => {
it('should return values from ajvResolver when validation pass', async () => {
expect(
await ajvResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
}),
).toEqual({
values: validData,
errors: {},
});
});
it('should return values from ajvResolver with `mode: sync` when validation pass', async () => {
expect(
await ajvResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation }),
).toEqual({
values: validData,
errors: {},
});
});
it('should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false', async () => {
expect(
await ajvResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false and `mode: sync`', async () => {
expect(
await ajvResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation }),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true', async () => {
expect(
await ajvResolver(schema)(
invalidData,
{},
{ fields, criteriaMode: 'all', shouldUseNativeValidation },
),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true and `mode: sync`', async () => {
expect(
await ajvResolver(schema, undefined, { mode: 'sync' })(
invalidData,
{},
{ fields, criteriaMode: 'all', shouldUseNativeValidation },
),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true', async () => {
expect(
await ajvResolver(schema)({}, undefined, {
fields,
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true and `mode: sync`', async () => {
expect(
await ajvResolver(schema, undefined, { mode: 'sync' })({}, undefined, {
fields,
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when some property is undefined and result will keep the input data structure', async () => {
expect(
await ajvResolver(schema, undefined, { mode: 'sync' })(
invalidDataWithUndefined,
undefined,
{
fields,
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
});

88
node_modules/@hookform/resolvers/ajv/src/ajv.ts generated vendored Normal file
View File

@@ -0,0 +1,88 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import Ajv, { DefinedError } from 'ajv';
import ajvErrors from 'ajv-errors';
import { FieldError, appendErrors } from 'react-hook-form';
import { Resolver } from './types';
const parseErrorSchema = (
ajvErrors: DefinedError[],
validateAllFieldCriteria: boolean,
) => {
// Ajv will return empty instancePath when require error
ajvErrors.forEach((error) => {
if (error.keyword === 'required') {
error.instancePath += '/' + error.params.missingProperty;
}
});
return ajvErrors.reduce<Record<string, FieldError>>((previous, error) => {
// `/deepObject/data` -> `deepObject.data`
const path = error.instancePath.substring(1).replace(/\//g, '.');
if (!previous[path]) {
previous[path] = {
message: error.message,
type: error.keyword,
};
}
if (validateAllFieldCriteria) {
const types = previous[path].types;
const messages = types && types[error.keyword];
previous[path] = appendErrors(
path,
validateAllFieldCriteria,
previous,
error.keyword,
messages
? ([] as string[]).concat(messages as string[], error.message || '')
: error.message,
) as FieldError;
}
return previous;
}, {});
};
export const ajvResolver: Resolver =
(schema, schemaOptions, resolverOptions = {}) =>
async (values, _, options) => {
const ajv = new Ajv(
Object.assign(
{},
{
allErrors: true,
validateSchema: true,
},
schemaOptions,
),
);
ajvErrors(ajv);
const validate = ajv.compile(
Object.assign(
{ $async: resolverOptions && resolverOptions.mode === 'async' },
schema,
),
);
const valid = validate(values);
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return valid
? { values, errors: {} }
: {
values: {},
errors: toNestErrors(
parseErrorSchema(
validate.errors as DefinedError[],
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
};

2
node_modules/@hookform/resolvers/ajv/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export * from './ajv';
export * from './types';

12
node_modules/@hookform/resolvers/ajv/src/types.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
import * as Ajv from 'ajv';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T>(
schema: Ajv.JSONSchemaType<T>,
schemaOptions?: Ajv.Options,
factoryOptions?: { mode?: 'async' | 'sync' },
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;

View File

@@ -0,0 +1,2 @@
import type { Resolver } from './types';
export declare const arktypeResolver: Resolver;

View File

@@ -0,0 +1,2 @@
var r=require("@hookform/resolvers"),e=require("arktype");exports.arktypeResolver=function(o,t,a){return void 0===a&&(a={}),function(t,s,i){var n,u=o(t);return u instanceof e.ArkErrors?{values:{},errors:r.toNestErrors((n=u,n.forEach(function(r){return Object.assign(r,{type:r.code})}),n.byPath),i)}:(i.shouldUseNativeValidation&&r.validateFieldsNatively({},i),{errors:{},values:a.raw?t:u})}};
//# sourceMappingURL=arktype.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"arktype.js","sources":["../src/arktype.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ArkErrors } from 'arktype';\nimport { FieldError, FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst parseErrorSchema = (e: ArkErrors): Record<string, FieldError> => {\n // copy code to type to match FieldError shape\n e.forEach((e) => Object.assign(e, { type: e.code }));\n // need to cast here because TS doesn't understand we added the type field\n return e.byPath as never;\n};\n\nexport const arktypeResolver: Resolver =\n (schema, _schemaOptions, resolverOptions = {}) =>\n (values, _, options) => {\n const out = schema(values);\n\n if (out instanceof ArkErrors) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(out), options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? values : out,\n };\n };\n"],"names":["schema","_schemaOptions","resolverOptions","values","_","options","e","out","ArkErrors","errors","toNestErrors","forEach","Object","assign","type","code","byPath","shouldUseNativeValidation","validateFieldsNatively","raw"],"mappings":"kFAaE,SAACA,EAAQC,EAAgBC,GACzB,YADyBA,IAAAA,IAAAA,EAAkB,CAAA,GAC3C,SAACC,EAAQC,EAAGC,GACV,IAVsBC,EAUhBC,EAAMP,EAAOG,GAEnB,OAAII,aAAeC,EAAAA,UACV,CACLL,OAAQ,CAAE,EACVM,OAAQC,EAAYA,cAfFJ,EAeoBC,EAb5CD,EAAEK,QAAQ,SAACL,UAAMM,OAAOC,OAAOP,EAAG,CAAEQ,KAAMR,EAAES,MAAO,GAE5CT,EAAEU,QAWyCX,KAIhDA,EAAQY,2BAA6BC,EAAsBA,uBAAC,CAAE,EAAEb,GAEzD,CACLI,OAAQ,CAAiB,EACzBN,OAAQD,EAAgBiB,IAAMhB,EAASI,GAE3C,CAAC"}

View File

@@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as o}from"@hookform/resolvers";import{ArkErrors as e}from"arktype";var t=function(t,a,n){return void 0===n&&(n={}),function(a,i,s){var u,f=t(a);return f instanceof e?{values:{},errors:r((u=f,u.forEach(function(r){return Object.assign(r,{type:r.code})}),u.byPath),s)}:(s.shouldUseNativeValidation&&o({},s),{errors:{},values:n.raw?a:f})}};export{t as arktypeResolver};
//# sourceMappingURL=arktype.module.js.map

View File

@@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as o}from"@hookform/resolvers";import{ArkErrors as e}from"arktype";const s=(s,t,a={})=>(t,i,n)=>{const c=s(t);return c instanceof e?{values:{},errors:r((f=c,f.forEach(r=>Object.assign(r,{type:r.code})),f.byPath),n)}:(n.shouldUseNativeValidation&&o({},n),{errors:{},values:a.raw?t:c});var f};export{s as arktypeResolver};
//# sourceMappingURL=arktype.modern.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"arktype.modern.mjs","sources":["../src/arktype.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ArkErrors } from 'arktype';\nimport { FieldError, FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst parseErrorSchema = (e: ArkErrors): Record<string, FieldError> => {\n // copy code to type to match FieldError shape\n e.forEach((e) => Object.assign(e, { type: e.code }));\n // need to cast here because TS doesn't understand we added the type field\n return e.byPath as never;\n};\n\nexport const arktypeResolver: Resolver =\n (schema, _schemaOptions, resolverOptions = {}) =>\n (values, _, options) => {\n const out = schema(values);\n\n if (out instanceof ArkErrors) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(out), options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? values : out,\n };\n };\n"],"names":["arktypeResolver","schema","_schemaOptions","resolverOptions","values","_","options","out","ArkErrors","errors","toNestErrors","e","forEach","Object","assign","type","code","byPath","shouldUseNativeValidation","validateFieldsNatively","raw"],"mappings":"mHAKA,MAOaA,EACXA,CAACC,EAAQC,EAAgBC,EAAkB,CAAA,IAC3C,CAACC,EAAQC,EAAGC,KACV,MAAMC,EAAMN,EAAOG,GAEnB,OAAIG,aAAeC,EACV,CACLJ,OAAQ,CAAE,EACVK,OAAQC,GAfUC,EAeoBJ,EAb5CI,EAAEC,QAASD,GAAME,OAAOC,OAAOH,EAAG,CAAEI,KAAMJ,EAAEK,QAErCL,EAAEM,QAWyCX,KAIhDA,EAAQY,2BAA6BC,EAAuB,GAAIb,GAEzD,CACLG,OAAQ,CAAA,EACRL,OAAQD,EAAgBiB,IAAMhB,EAASG,IAvBnBI"}

View File

@@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as o}from"@hookform/resolvers";import{ArkErrors as e}from"arktype";var t=function(t,a,n){return void 0===n&&(n={}),function(a,i,s){var u,f=t(a);return f instanceof e?{values:{},errors:r((u=f,u.forEach(function(r){return Object.assign(r,{type:r.code})}),u.byPath),s)}:(s.shouldUseNativeValidation&&o({},s),{errors:{},values:n.raw?a:f})}};export{t as arktypeResolver};
//# sourceMappingURL=arktype.module.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"arktype.module.js","sources":["../src/arktype.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ArkErrors } from 'arktype';\nimport { FieldError, FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst parseErrorSchema = (e: ArkErrors): Record<string, FieldError> => {\n // copy code to type to match FieldError shape\n e.forEach((e) => Object.assign(e, { type: e.code }));\n // need to cast here because TS doesn't understand we added the type field\n return e.byPath as never;\n};\n\nexport const arktypeResolver: Resolver =\n (schema, _schemaOptions, resolverOptions = {}) =>\n (values, _, options) => {\n const out = schema(values);\n\n if (out instanceof ArkErrors) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(out), options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? values : out,\n };\n };\n"],"names":["arktypeResolver","schema","_schemaOptions","resolverOptions","values","_","options","e","out","ArkErrors","errors","toNestErrors","forEach","Object","assign","type","code","byPath","shouldUseNativeValidation","validateFieldsNatively","raw"],"mappings":"mHAKA,IAOaA,EACX,SAACC,EAAQC,EAAgBC,GACzB,YADyBA,IAAAA,IAAAA,EAAkB,CAAA,GAC3C,SAACC,EAAQC,EAAGC,GACV,IAVsBC,EAUhBC,EAAMP,EAAOG,GAEnB,OAAII,aAAeC,EACV,CACLL,OAAQ,CAAE,EACVM,OAAQC,GAfUJ,EAeoBC,EAb5CD,EAAEK,QAAQ,SAACL,UAAMM,OAAOC,OAAOP,EAAG,CAAEQ,KAAMR,EAAES,MAAO,GAE5CT,EAAEU,QAWyCX,KAIhDA,EAAQY,2BAA6BC,EAAuB,CAAE,EAAEb,GAEzD,CACLI,OAAQ,CAAiB,EACzBN,OAAQD,EAAgBiB,IAAMhB,EAASI,GAE3C,CAAC"}

View File

@@ -0,0 +1,2 @@
!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("@hookform/resolvers"),require("arktype")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","arktype"],o):o((e||self).hookformResolversArktype={},e.hookformResolvers,e.arktype)}(this,function(e,o,r){e.arktypeResolver=function(e,t,s){return void 0===s&&(s={}),function(t,n,i){var f,a=e(t);return a instanceof r.ArkErrors?{values:{},errors:o.toNestErrors((f=a,f.forEach(function(e){return Object.assign(e,{type:e.code})}),f.byPath),i)}:(i.shouldUseNativeValidation&&o.validateFieldsNatively({},i),{errors:{},values:s.raw?t:a})}}});
//# sourceMappingURL=arktype.umd.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"arktype.umd.js","sources":["../src/arktype.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ArkErrors } from 'arktype';\nimport { FieldError, FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst parseErrorSchema = (e: ArkErrors): Record<string, FieldError> => {\n // copy code to type to match FieldError shape\n e.forEach((e) => Object.assign(e, { type: e.code }));\n // need to cast here because TS doesn't understand we added the type field\n return e.byPath as never;\n};\n\nexport const arktypeResolver: Resolver =\n (schema, _schemaOptions, resolverOptions = {}) =>\n (values, _, options) => {\n const out = schema(values);\n\n if (out instanceof ArkErrors) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(out), options),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? values : out,\n };\n };\n"],"names":["schema","_schemaOptions","resolverOptions","values","_","options","e","out","ArkErrors","errors","toNestErrors","forEach","Object","assign","type","code","byPath","shouldUseNativeValidation","validateFieldsNatively","raw"],"mappings":"wXAaE,SAACA,EAAQC,EAAgBC,GACzB,YADyBA,IAAAA,IAAAA,EAAkB,CAAA,GAC3C,SAACC,EAAQC,EAAGC,GACV,IAVsBC,EAUhBC,EAAMP,EAAOG,GAEnB,OAAII,aAAeC,EAAAA,UACV,CACLL,OAAQ,CAAE,EACVM,OAAQC,EAAYA,cAfFJ,EAeoBC,EAb5CD,EAAEK,QAAQ,SAACL,UAAMM,OAAOC,OAAOP,EAAG,CAAEQ,KAAMR,EAAES,MAAO,GAE5CT,EAAEU,QAWyCX,KAIhDA,EAAQY,2BAA6BC,EAAsBA,uBAAC,CAAE,EAAEb,GAEzD,CACLI,OAAQ,CAAiB,EACzBN,OAAQD,EAAgBiB,IAAMhB,EAASI,GAE3C,CAAC"}

View File

@@ -0,0 +1,2 @@
export * from './arktype';
export * from './types';

View File

@@ -0,0 +1,9 @@
import { Type } from 'arktype';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T extends Type<any>>(schema: T, schemaOptions?: undefined, factoryOptions?: {
/**
* Return the raw input values rather than the parsed values.
* @default false
*/
raw?: boolean;
}) => <TFieldValues extends FieldValues, TContext>(values: TFieldValues, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => ResolverResult<TFieldValues>;

18
node_modules/@hookform/resolvers/arktype/package.json generated vendored Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "@hookform/resolvers/arktype",
"amdName": "hookformResolversArktype",
"version": "2.0.0",
"private": true,
"description": "React Hook Form validation resolver: arktype",
"main": "dist/arktype.js",
"module": "dist/arktype.module.js",
"umd:main": "dist/arktype.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.0.0",
"@hookform/resolvers": "^2.0.0",
"arktype": "2.0.0-dev.14"
}
}

View File

@@ -0,0 +1,82 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { type } from 'arktype';
import React from 'react';
import { useForm } from 'react-hook-form';
import { arktypeResolver } from '..';
const schema = type({
username: 'string>1',
password: 'string>1',
});
type FormData = typeof schema.infer;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: arktypeResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Zod", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(
'username must be more than length 1',
);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
'password must be more than length 1',
);
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View File

@@ -0,0 +1,56 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { type } from 'arktype';
import React from 'react';
import { useForm } from 'react-hook-form';
import { arktypeResolver } from '..';
const schema = type({
username: 'string>1',
password: 'string>1',
});
type FormData = typeof schema.infer & { unusedProperty: string };
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: arktypeResolver(schema), // Useful to check TypeScript regressions
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with arkType and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(
screen.getByText('username must be more than length 1 (was 0)'),
).toBeInTheDocument();
expect(
screen.getByText('password must be more than length 1 (was 0)'),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,65 @@
import { type } from 'arktype';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = type({
username: 'string>2',
password: '/.*[A-Za-z].*/>8|/.*\\d.*/',
repeatPassword: 'string>1',
accessToken: 'string|number',
birthYear: '1900<number<2013',
email: 'email',
tags: 'string[]',
enabled: 'boolean',
url: 'string>1',
'like?': type({
id: 'number',
name: 'string>3',
}).array(),
dateStr: 'Date',
});
export const validData: typeof schema.infer = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
url: 'https://react-hook-form.com/',
like: [
{
id: 1,
name: 'name',
},
],
dateStr: new Date('2020-01-01'),
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
url: 'abc',
};
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View File

@@ -0,0 +1,467 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`arktypeResolver > should return a single error from arktypeResolver when validation fails 1`] = `
{
"errors": {
"accessToken": ArkError {
"code": "required",
"data": {
"birthYear": "birthYear",
"email": "",
"like": [
{
"id": "z",
},
],
"password": "___",
"url": "abc",
},
"input": {
"code": "required",
"missingValueDescription": "a number or a string",
"relativePath": [
"accessToken",
],
},
"missingValueDescription": "a number or a string",
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"accessToken",
],
"ref": undefined,
"relativePath": [
"accessToken",
],
"type": "required",
Symbol(ArkTypeInternalKind): "error",
},
"birthYear": ArkError {
"code": "domain",
"data": "birthYear",
"description": "a number",
"domain": "number",
"input": {
"code": "domain",
"description": "a number",
"domain": "number",
},
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"birthYear",
],
"ref": undefined,
"type": "domain",
Symbol(ArkTypeInternalKind): "error",
},
"dateStr": ArkError {
"code": "required",
"data": {
"birthYear": "birthYear",
"email": "",
"like": [
{
"id": "z",
},
],
"password": "___",
"url": "abc",
},
"input": {
"code": "required",
"missingValueDescription": "a Date",
"relativePath": [
"dateStr",
],
},
"missingValueDescription": "a Date",
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"dateStr",
],
"ref": undefined,
"relativePath": [
"dateStr",
],
"type": "required",
Symbol(ArkTypeInternalKind): "error",
},
"email": ArkError {
"code": "pattern",
"data": "",
"description": "a valid email",
"flags": "",
"input": {
"code": "pattern",
"description": "a valid email",
"flags": "",
"rule": "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$",
},
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"email",
],
"ref": {
"name": "email",
},
"rule": "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$",
"type": "pattern",
Symbol(ArkTypeInternalKind): "error",
},
"enabled": ArkError {
"code": "required",
"data": {
"birthYear": "birthYear",
"email": "",
"like": [
{
"id": "z",
},
],
"password": "___",
"url": "abc",
},
"input": {
"code": "required",
"missingValueDescription": "boolean",
"relativePath": [
"enabled",
],
},
"missingValueDescription": "boolean",
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"enabled",
],
"ref": undefined,
"relativePath": [
"enabled",
],
"type": "required",
Symbol(ArkTypeInternalKind): "error",
},
"like": [
{
"id": ArkError {
"code": "domain",
"data": "z",
"description": "a number",
"domain": "number",
"input": {
"code": "domain",
"description": "a number",
"domain": "number",
},
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"like",
0,
"id",
],
"ref": undefined,
"type": "domain",
Symbol(ArkTypeInternalKind): "error",
},
"name": ArkError {
"code": "required",
"data": {
"id": "z",
},
"input": {
"code": "required",
"missingValueDescription": "a string",
"relativePath": [
"name",
],
},
"missingValueDescription": "a string",
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"like",
0,
"name",
],
"ref": undefined,
"relativePath": [
"name",
],
"type": "required",
Symbol(ArkTypeInternalKind): "error",
},
},
],
"password": ArkError {
"code": "union",
"data": "___",
"errors": [
ArkError {
"code": "pattern",
"data": "___",
"description": "matched by .*[A-Za-z].*",
"input": {
"code": "pattern",
"description": "matched by .*[A-Za-z].*",
"rule": ".*[A-Za-z].*",
},
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"password",
],
"rule": ".*[A-Za-z].*",
Symbol(ArkTypeInternalKind): "error",
},
ArkError {
"code": "pattern",
"data": "___",
"description": "matched by .*\\d.*",
"input": {
"code": "pattern",
"description": "matched by .*\\d.*",
"rule": ".*\\d.*",
},
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"password",
],
"rule": ".*\\d.*",
Symbol(ArkTypeInternalKind): "error",
},
],
"input": {
"code": "union",
"errors": [
ArkError {
"code": "pattern",
"data": "___",
"description": "matched by .*[A-Za-z].*",
"input": {
"code": "pattern",
"description": "matched by .*[A-Za-z].*",
"rule": ".*[A-Za-z].*",
},
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"password",
],
"rule": ".*[A-Za-z].*",
Symbol(ArkTypeInternalKind): "error",
},
ArkError {
"code": "pattern",
"data": "___",
"description": "matched by .*\\d.*",
"input": {
"code": "pattern",
"description": "matched by .*\\d.*",
"rule": ".*\\d.*",
},
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"password",
],
"rule": ".*\\d.*",
Symbol(ArkTypeInternalKind): "error",
},
],
},
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"password",
],
"ref": {
"name": "password",
},
"type": "union",
Symbol(ArkTypeInternalKind): "error",
},
"repeatPassword": ArkError {
"code": "required",
"data": {
"birthYear": "birthYear",
"email": "",
"like": [
{
"id": "z",
},
],
"password": "___",
"url": "abc",
},
"input": {
"code": "required",
"missingValueDescription": "a string",
"relativePath": [
"repeatPassword",
],
},
"missingValueDescription": "a string",
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"repeatPassword",
],
"ref": undefined,
"relativePath": [
"repeatPassword",
],
"type": "required",
Symbol(ArkTypeInternalKind): "error",
},
"tags": ArkError {
"code": "required",
"data": {
"birthYear": "birthYear",
"email": "",
"like": [
{
"id": "z",
},
],
"password": "___",
"url": "abc",
},
"input": {
"code": "required",
"missingValueDescription": "an array",
"relativePath": [
"tags",
],
},
"missingValueDescription": "an array",
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"tags",
],
"ref": undefined,
"relativePath": [
"tags",
],
"type": "required",
Symbol(ArkTypeInternalKind): "error",
},
"username": ArkError {
"code": "required",
"data": {
"birthYear": "birthYear",
"email": "",
"like": [
{
"id": "z",
},
],
"password": "___",
"url": "abc",
},
"input": {
"code": "required",
"missingValueDescription": "a string",
"relativePath": [
"username",
],
},
"missingValueDescription": "a string",
"nodeConfig": {
"actual": [Function],
"description": [Function],
"expected": [Function],
"message": [Function],
"problem": [Function],
},
"path": [
"username",
],
"ref": {
"name": "username",
},
"relativePath": [
"username",
],
"type": "required",
Symbol(ArkTypeInternalKind): "error",
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,26 @@
import { arktypeResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('arktypeResolver', () => {
it('should return values from arktypeResolver when validation pass & raw=true', async () => {
const result = await arktypeResolver(schema, undefined, {
raw: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from arktypeResolver when validation fails', async () => {
const result = await arktypeResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
});

View File

@@ -0,0 +1,31 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { ArkErrors } from 'arktype';
import { FieldError, FieldErrors } from 'react-hook-form';
import type { Resolver } from './types';
const parseErrorSchema = (e: ArkErrors): Record<string, FieldError> => {
// copy code to type to match FieldError shape
e.forEach((e) => Object.assign(e, { type: e.code }));
// need to cast here because TS doesn't understand we added the type field
return e.byPath as never;
};
export const arktypeResolver: Resolver =
(schema, _schemaOptions, resolverOptions = {}) =>
(values, _, options) => {
const out = schema(values);
if (out instanceof ArkErrors) {
return {
values: {},
errors: toNestErrors(parseErrorSchema(out), options),
};
}
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
errors: {} as FieldErrors,
values: resolverOptions.raw ? values : out,
};
};

View File

@@ -0,0 +1,2 @@
export * from './arktype';
export * from './types';

18
node_modules/@hookform/resolvers/arktype/src/types.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import { Type } from 'arktype';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T extends Type<any>>(
schema: T,
schemaOptions?: undefined,
factoryOptions?: {
/**
* Return the raw input values rather than the parsed values.
* @default false
*/
raw?: boolean;
},
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => ResolverResult<TFieldValues>;

View File

@@ -0,0 +1,2 @@
import type { Resolver } from './types';
export declare const classValidatorResolver: Resolver;

View File

@@ -0,0 +1,2 @@
var r=require("@hookform/resolvers"),e=require("class-transformer"),t=require("class-validator"),a=function r(e,t,a,s){return void 0===a&&(a={}),void 0===s&&(s=""),e.reduce(function(e,a){var i=s?s+"."+a.property:a.property;if(a.constraints){var o=Object.keys(a.constraints)[0];e[i]={type:o,message:a.constraints[o]};var n=e[i];t&&n&&Object.assign(n,{types:a.constraints})}return a.children&&a.children.length&&r(a.children,t,e,i),e},a)};exports.classValidatorResolver=function(s,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),function(n,l,c){try{var v=i.validator,d=e.plainToClass(s,n,i.transformer);return Promise.resolve(("sync"===o.mode?t.validateSync:t.validate)(d,v)).then(function(e){return e.length?{values:{},errors:r.toNestErrors(a(e,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}:(c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{values:o.rawValues?n:d,errors:{}})})}catch(r){return Promise.reject(r)}}};
//# sourceMappingURL=class-validator.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"class-validator.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { plainToClass } from 'class-transformer';\nimport { ValidationError, validate, validateSync } from 'class-validator';\nimport { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst parseErrors = (\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) => {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrors(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n};\n\nexport const classValidatorResolver: Resolver =\n (schema, schemaOptions = {}, resolverOptions = {}) =>\n async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrors(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.rawValues ? values : data,\n errors: {},\n };\n };\n"],"names":["parseErrors","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","rawValues","e","reject"],"mappings":"iGAMMA,EAAc,SAAdA,EACJC,EACAC,EACAC,EACAC,GAEA,gBAHAD,IAAAA,EAA4B,CAAE,QAC1B,IAAJC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAQG,IAAAA,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAYO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAGtDF,CACT,EAAGH,EACL,iCAGE,SAACkB,EAAQC,EAAoBC,GAAoB,YAAxCD,IAAAA,IAAAA,EAAgB,SAAmB,IAAfC,IAAAA,EAAkB,IAAE,SAC1CC,EAAQC,EAAGC,GAAO,IACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,eAAaR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,EAAAA,aACAC,EAAQA,UAAEP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUjB,OACL,CACLI,OAAQ,GACRvB,OAAQqC,EAAAA,aACNtC,EACEqC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,yBAAuB,CAAA,EAAIf,GAEzD,CACLF,OAAQD,EAAgBmB,UAAYlB,EAASI,EAC7C3B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA0C,GAAA,OAAAZ,QAAAa,OAAAD,EAAA,CAAA,CAAA"}

View File

@@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as o,validate as n}from"class-validator";var s=function r(e,t,o,n){return void 0===o&&(o={}),void 0===n&&(n=""),e.reduce(function(e,o){var s=n?n+"."+o.property:o.property;if(o.constraints){var i=Object.keys(o.constraints)[0];e[s]={type:i,message:o.constraints[i]};var a=e[s];t&&a&&Object.assign(a,{types:o.constraints})}return o.children&&o.children.length&&r(o.children,t,e,s),e},o)},i=function(i,a,c){return void 0===a&&(a={}),void 0===c&&(c={}),function(l,u,v){try{var d=a.validator,m=t(i,l,a.transformer);return Promise.resolve(("sync"===c.mode?o:n)(m,d)).then(function(t){return t.length?{values:{},errors:r(s(t,!v.shouldUseNativeValidation&&"all"===v.criteriaMode),v)}:(v.shouldUseNativeValidation&&e({},v),{values:c.rawValues?l:m,errors:{}})})}catch(r){return Promise.reject(r)}}};export{i as classValidatorResolver};
//# sourceMappingURL=class-validator.module.js.map

View File

@@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as s}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as e,validate as o}from"class-validator";const a=(r,s,t={},e="")=>r.reduce((r,t)=>{const o=e?`${e}.${t.property}`:t.property;if(t.constraints){const e=Object.keys(t.constraints)[0];r[o]={type:e,message:t.constraints[e]};const a=r[o];s&&a&&Object.assign(a,{types:t.constraints})}return t.children&&t.children.length&&a(t.children,s,r,o),r},t),n=(n,i={},c={})=>async(l,d,m)=>{const{transformer:p,validator:h}=i,u=t(n,l,p),f=await("sync"===c.mode?e:o)(u,h);return f.length?{values:{},errors:r(a(f,!m.shouldUseNativeValidation&&"all"===m.criteriaMode),m)}:(m.shouldUseNativeValidation&&s({},m),{values:c.rawValues?l:u,errors:{}})};export{n as classValidatorResolver};
//# sourceMappingURL=class-validator.modern.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"class-validator.modern.mjs","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { plainToClass } from 'class-transformer';\nimport { ValidationError, validate, validateSync } from 'class-validator';\nimport { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst parseErrors = (\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) => {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrors(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n};\n\nexport const classValidatorResolver: Resolver =\n (schema, schemaOptions = {}, resolverOptions = {}) =>\n async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrors(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.rawValues ? values : data,\n errors: {},\n };\n };\n"],"names":["parseErrors","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","classValidatorResolver","schema","schemaOptions","resolverOptions","async","values","_","options","transformer","validator","data","plainToClass","rawErrors","mode","validateSync","validate","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","rawValues"],"mappings":"6LAMA,MAAMA,EAAcA,CAClBC,EACAC,EACAC,EAA4B,CAAA,EAC5BC,EAAO,KAEAH,EAAOI,OAAO,CAACC,EAAKC,KACzB,MAAMC,EAAQJ,EAAO,GAAGA,KAAQG,EAAME,WAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,MAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,MAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAYO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAGtDF,GACNH,GAGQkB,EACXA,CAACC,EAAQC,EAAgB,CAAA,EAAIC,EAAkB,CAAE,IACjDC,MAAOC,EAAQC,EAAGC,KAChB,MAAMC,YAAEA,EAAWC,UAAEA,GAAcP,EAC7BQ,EAAOC,EAAaV,EAAQI,EAAQG,GAEpCI,QAA4C,SAAzBT,EAAgBU,KACrCC,EACAC,GAAUL,EAAMD,GAEpB,OAAIG,EAAUb,OACL,CACLM,OAAQ,CAAE,EACVzB,OAAQoC,EACNrC,EACEiC,GACCL,EAAQU,2BACkB,QAAzBV,EAAQW,cAEZX,KAKNA,EAAQU,2BAA6BE,EAAuB,CAAA,EAAIZ,GAEzD,CACLF,OAAQF,EAAgBiB,UAAYf,EAASK,EAC7C9B,OAAQ"}

View File

@@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as o,validate as n}from"class-validator";var s=function r(e,t,o,n){return void 0===o&&(o={}),void 0===n&&(n=""),e.reduce(function(e,o){var s=n?n+"."+o.property:o.property;if(o.constraints){var i=Object.keys(o.constraints)[0];e[s]={type:i,message:o.constraints[i]};var a=e[s];t&&a&&Object.assign(a,{types:o.constraints})}return o.children&&o.children.length&&r(o.children,t,e,s),e},o)},i=function(i,a,c){return void 0===a&&(a={}),void 0===c&&(c={}),function(l,u,v){try{var d=a.validator,m=t(i,l,a.transformer);return Promise.resolve(("sync"===c.mode?o:n)(m,d)).then(function(t){return t.length?{values:{},errors:r(s(t,!v.shouldUseNativeValidation&&"all"===v.criteriaMode),v)}:(v.shouldUseNativeValidation&&e({},v),{values:c.rawValues?l:m,errors:{}})})}catch(r){return Promise.reject(r)}}};export{i as classValidatorResolver};
//# sourceMappingURL=class-validator.module.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"class-validator.module.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { plainToClass } from 'class-transformer';\nimport { ValidationError, validate, validateSync } from 'class-validator';\nimport { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst parseErrors = (\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) => {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrors(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n};\n\nexport const classValidatorResolver: Resolver =\n (schema, schemaOptions = {}, resolverOptions = {}) =>\n async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrors(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.rawValues ? values : data,\n errors: {},\n };\n };\n"],"names":["parseErrors","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","classValidatorResolver","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","rawValues","e","reject"],"mappings":"6LAMA,IAAMA,EAAc,SAAdA,EACJC,EACAC,EACAC,EACAC,GAEA,gBAHAD,IAAAA,EAA4B,CAAE,QAC1B,IAAJC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAQG,IAAAA,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAYO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAGtDF,CACT,EAAGH,EACL,EAEakB,EACX,SAACC,EAAQC,EAAoBC,GAAoB,YAAxCD,IAAAA,IAAAA,EAAgB,SAAmB,IAAfC,IAAAA,EAAkB,IAAE,SAC1CC,EAAQC,EAAGC,GAAO,IACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,EAAaR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,EACAC,GAAUP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUlB,OACL,CACLK,OAAQ,GACRxB,OAAQsC,EACNvC,EACEsC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAuB,CAAA,EAAIf,GAEzD,CACLF,OAAQD,EAAgBmB,UAAYlB,EAASI,EAC7C5B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA2C,GAAA,OAAAZ,QAAAa,OAAAD,EAAA,CAAA,CAAA"}

View File

@@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("class-transformer"),require("class-validator")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","class-transformer","class-validator"],r):r((e||self).hookformResolversClassValidator={},e.hookformResolvers,e.classTransformer,e.classValidator)}(this,function(e,r,o,s){var t=function e(r,o,s,t){return void 0===s&&(s={}),void 0===t&&(t=""),r.reduce(function(r,s){var a=t?t+"."+s.property:s.property;if(s.constraints){var i=Object.keys(s.constraints)[0];r[a]={type:i,message:s.constraints[i]};var n=r[a];o&&n&&Object.assign(n,{types:s.constraints})}return s.children&&s.children.length&&e(s.children,o,r,a),r},s)};e.classValidatorResolver=function(e,a,i){return void 0===a&&(a={}),void 0===i&&(i={}),function(n,l,d){try{var c=a.validator,f=o.plainToClass(e,n,a.transformer);return Promise.resolve(("sync"===i.mode?s.validateSync:s.validate)(f,c)).then(function(e){return e.length?{values:{},errors:r.toNestErrors(t(e,!d.shouldUseNativeValidation&&"all"===d.criteriaMode),d)}:(d.shouldUseNativeValidation&&r.validateFieldsNatively({},d),{values:i.rawValues?n:f,errors:{}})})}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=class-validator.umd.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"class-validator.umd.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { plainToClass } from 'class-transformer';\nimport { ValidationError, validate, validateSync } from 'class-validator';\nimport { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst parseErrors = (\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) => {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrors(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n};\n\nexport const classValidatorResolver: Resolver =\n (schema, schemaOptions = {}, resolverOptions = {}) =>\n async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrors(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.rawValues ? values : data,\n errors: {},\n };\n };\n"],"names":["parseErrors","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","rawValues","e","reject"],"mappings":"0cAMA,IAAMA,EAAc,SAAdA,EACJC,EACAC,EACAC,EACAC,GAEA,gBAHAD,IAAAA,EAA4B,CAAE,QAC1B,IAAJC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAQG,IAAAA,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAYO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAGtDF,CACT,EAAGH,EACL,2BAGE,SAACkB,EAAQC,EAAoBC,GAAoB,YAAxCD,IAAAA,IAAAA,EAAgB,SAAmB,IAAfC,IAAAA,EAAkB,IAAE,SAC1CC,EAAQC,EAAGC,GAAO,IACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,eAAaR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,EAAAA,aACAC,EAAQA,UAAEP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUjB,OACL,CACLI,OAAQ,GACRvB,OAAQqC,EAAAA,aACNtC,EACEqC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,yBAAuB,CAAA,EAAIf,GAEzD,CACLF,OAAQD,EAAgBmB,UAAYlB,EAASI,EAC7C3B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA0C,GAAA,OAAAZ,QAAAa,OAAAD,EAAA,CAAA,CAAA"}

View File

@@ -0,0 +1,2 @@
export * from './class-validator';
export * from './types';

View File

@@ -0,0 +1,12 @@
import { ClassConstructor, ClassTransformOptions } from 'class-transformer';
import { ValidatorOptions } from 'class-validator';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T extends {
[_: string]: any;
}>(schema: ClassConstructor<T>, schemaOptions?: {
validator?: ValidatorOptions;
transformer?: ClassTransformOptions;
}, resolverOptions?: {
mode?: 'async' | 'sync';
rawValues?: boolean;
}) => <TFieldValues extends FieldValues, TContext>(values: TFieldValues, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;

View File

@@ -0,0 +1,19 @@
{
"name": "@hookform/resolvers/class-validator",
"amdName": "hookformResolversClassValidator",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: class-validator",
"main": "dist/class-validator.js",
"module": "dist/class-validator.module.js",
"umd:main": "dist/class-validator.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": ">=6.6.0",
"@hookform/resolvers": ">=2.0.0",
"class-transformer": "^0.4.0",
"class-validator": "^0.12.0"
}
}

View File

@@ -0,0 +1,79 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { IsNotEmpty } from 'class-validator';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { classValidatorResolver } from '..';
class Schema {
@IsNotEmpty()
username: string;
@IsNotEmpty()
password: string;
}
interface Props {
onSubmit: SubmitHandler<Schema>;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<Schema>({
resolver: classValidatorResolver(Schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Class Validator", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe('username should not be empty');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe('password should not be empty');
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View File

@@ -0,0 +1,53 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { IsNotEmpty } from 'class-validator';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { classValidatorResolver } from '..';
class Schema {
@IsNotEmpty()
username: string;
@IsNotEmpty()
password: string;
}
interface Props {
onSubmit: SubmitHandler<Schema>;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<Schema>({
resolver: classValidatorResolver(Schema),
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with Class Validator and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(screen.getByText(/username should not be empty/i)).toBeInTheDocument();
expect(screen.getByText(/password should not be empty/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,88 @@
import 'reflect-metadata';
import { Type } from 'class-transformer';
import {
IsEmail,
IsNotEmpty,
Length,
Matches,
Max,
Min,
ValidateNested,
} from 'class-validator';
import { Field, InternalFieldName } from 'react-hook-form';
class Like {
@IsNotEmpty()
id: number;
@Length(4)
name: string;
}
export class Schema {
@Matches(/^\w+$/)
@Length(3, 30)
username: string;
@Matches(/^[a-zA-Z0-9]{3,30}/)
password: string;
@Min(1900)
@Max(2013)
birthYear: number;
@IsEmail()
email: string;
accessToken: string;
tags: string[];
enabled: boolean;
@ValidateNested({ each: true })
@Type(() => Like)
like: Like[];
}
export const validData: Schema = {
username: 'Doe',
password: 'Password123',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
like: [
{
id: 1,
name: 'name',
},
],
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
};
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View File

@@ -0,0 +1,242 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`classValidatorResolver > should return a single error from classValidatorResolver when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must not be greater than 2013",
"ref": undefined,
"type": "max",
},
"email": {
"message": "email must be an email",
"ref": {
"name": "email",
},
"type": "isEmail",
},
"like": [
{
"name": {
"message": "name must be longer than or equal to 4 characters",
"ref": undefined,
"type": "isLength",
},
},
],
"password": {
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
"ref": {
"name": "password",
},
"type": "matches",
},
"username": {
"message": "username must be longer than or equal to 3 characters",
"ref": {
"name": "username",
},
"type": "isLength",
},
},
"values": {},
}
`;
exports[`classValidatorResolver > should return a single error from classValidatorResolver with \`mode: sync\` when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must not be greater than 2013",
"ref": undefined,
"type": "max",
},
"email": {
"message": "email must be an email",
"ref": {
"name": "email",
},
"type": "isEmail",
},
"like": [
{
"name": {
"message": "name must be longer than or equal to 4 characters",
"ref": undefined,
"type": "isLength",
},
},
],
"password": {
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
"ref": {
"name": "password",
},
"type": "matches",
},
"username": {
"message": "username must be longer than or equal to 3 characters",
"ref": {
"name": "username",
},
"type": "isLength",
},
},
"values": {},
}
`;
exports[`classValidatorResolver > should return all the errors from classValidatorResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must not be greater than 2013",
"ref": undefined,
"type": "max",
"types": {
"max": "birthYear must not be greater than 2013",
"min": "birthYear must not be less than 1900",
},
},
"email": {
"message": "email must be an email",
"ref": {
"name": "email",
},
"type": "isEmail",
"types": {
"isEmail": "email must be an email",
},
},
"like": [
{
"name": {
"message": "name must be longer than or equal to 4 characters",
"ref": undefined,
"type": "isLength",
"types": {
"isLength": "name must be longer than or equal to 4 characters",
},
},
},
],
"password": {
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
"ref": {
"name": "password",
},
"type": "matches",
"types": {
"matches": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
},
},
"username": {
"message": "username must be longer than or equal to 3 characters",
"ref": {
"name": "username",
},
"type": "isLength",
"types": {
"isLength": "username must be longer than or equal to 3 characters",
"matches": "username must match /^\\w+$/ regular expression",
},
},
},
"values": {},
}
`;
exports[`classValidatorResolver > should return all the errors from classValidatorResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must not be greater than 2013",
"ref": undefined,
"type": "max",
"types": {
"max": "birthYear must not be greater than 2013",
"min": "birthYear must not be less than 1900",
},
},
"email": {
"message": "email must be an email",
"ref": {
"name": "email",
},
"type": "isEmail",
"types": {
"isEmail": "email must be an email",
},
},
"like": [
{
"name": {
"message": "name must be longer than or equal to 4 characters",
"ref": undefined,
"type": "isLength",
"types": {
"isLength": "name must be longer than or equal to 4 characters",
},
},
},
],
"password": {
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
"ref": {
"name": "password",
},
"type": "matches",
"types": {
"matches": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
},
},
"username": {
"message": "username must be longer than or equal to 3 characters",
"ref": {
"name": "username",
},
"type": "isLength",
"types": {
"isLength": "username must be longer than or equal to 3 characters",
"matches": "username must match /^\\w+$/ regular expression",
},
},
},
"values": {},
}
`;
exports[`validate data with transformer option 1`] = `
{
"errors": {
"random": {
"message": "All fields must be defined.",
"ref": undefined,
"type": "isDefined",
"types": {
"isDefined": "All fields must be defined.",
"isNumber": "Must be a number",
"max": "Cannot be greater than 255",
"min": "Cannot be lower than 0",
},
},
},
"values": {},
}
`;
exports[`validate data with validator option 1`] = `
{
"errors": {
"random": {
"message": "All fields must be defined.",
"ref": undefined,
"type": "isDefined",
"types": {
"isDefined": "All fields must be defined.",
},
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,188 @@
import { Expose, Type } from 'class-transformer';
import * as classValidator from 'class-validator';
import { IsDefined, IsNumber, Max, Min } from 'class-validator';
/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */
import { classValidatorResolver } from '..';
import { Schema, fields, invalidData, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('classValidatorResolver', () => {
it('should return values from classValidatorResolver when validation pass', async () => {
const schemaSpy = vi.spyOn(classValidator, 'validate');
const schemaSyncSpy = vi.spyOn(classValidator, 'validateSync');
const result = await classValidatorResolver(Schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(schemaSyncSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: validData });
expect(result.values).toBeInstanceOf(Schema);
});
it('should return values as a raw object from classValidatorResolver when `rawValues` set to true', async () => {
const result = await classValidatorResolver(Schema, undefined, {
rawValues: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
expect(result.values).not.toBeInstanceOf(Schema);
});
it('should return values from classValidatorResolver with `mode: sync` when validation pass', async () => {
const validateSyncSpy = vi.spyOn(classValidator, 'validateSync');
const validateSpy = vi.spyOn(classValidator, 'validate');
const result = await classValidatorResolver(Schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation });
expect(validateSyncSpy).toHaveBeenCalledTimes(1);
expect(validateSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: validData });
expect(result.values).toBeInstanceOf(Schema);
});
it('should return a single error from classValidatorResolver when validation fails', async () => {
const result = await classValidatorResolver(Schema)(
invalidData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return a single error from classValidatorResolver with `mode: sync` when validation fails', async () => {
const validateSyncSpy = vi.spyOn(classValidator, 'validateSync');
const validateSpy = vi.spyOn(classValidator, 'validate');
const result = await classValidatorResolver(Schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation });
expect(validateSyncSpy).toHaveBeenCalledTimes(1);
expect(validateSpy).not.toHaveBeenCalled();
expect(result).toMatchSnapshot();
});
it('should return all the errors from classValidatorResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await classValidatorResolver(Schema)(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return all the errors from classValidatorResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await classValidatorResolver(Schema, undefined, {
mode: 'sync',
})(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
});
it('validate data with transformer option', async () => {
class SchemaTest {
@Expose({ groups: ['find', 'create', 'update'] })
@Type(() => Number)
@IsDefined({
message: `All fields must be defined.`,
groups: ['publish'],
})
@IsNumber({}, { message: `Must be a number`, always: true })
@Min(0, { message: `Cannot be lower than 0`, always: true })
@Max(255, { message: `Cannot be greater than 255`, always: true })
random: number;
}
const result = await classValidatorResolver(
SchemaTest,
{ transformer: { groups: ['update'] } },
{
mode: 'sync',
},
)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('validate data with validator option', async () => {
class SchemaTest {
@Expose({ groups: ['find', 'create', 'update'] })
@Type(() => Number)
@IsDefined({
message: `All fields must be defined.`,
groups: ['publish'],
})
@IsNumber({}, { message: `Must be a number`, always: true })
@Min(0, { message: `Cannot be lower than 0`, always: true })
@Max(255, { message: `Cannot be greater than 255`, always: true })
random: number;
}
const result = await classValidatorResolver(
SchemaTest,
{ validator: { stopAtFirstError: true } },
{
mode: 'sync',
},
)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return from classValidatorResolver with `excludeExtraneousValues` set to true', async () => {
class SchemaTest {
@Expose()
@IsNumber({}, { message: `Must be a number`, always: true })
random: number;
}
const result = await classValidatorResolver(SchemaTest, {
transformer: {
excludeExtraneousValues: true,
},
})(
{
random: 10,
extraneousField: true,
},
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(result).toEqual({ errors: {}, values: { random: 10 } });
expect(result.values).toBeInstanceOf(SchemaTest);
});

View File

@@ -0,0 +1,67 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { plainToClass } from 'class-transformer';
import { ValidationError, validate, validateSync } from 'class-validator';
import { FieldErrors } from 'react-hook-form';
import type { Resolver } from './types';
const parseErrors = (
errors: ValidationError[],
validateAllFieldCriteria: boolean,
parsedErrors: FieldErrors = {},
path = '',
) => {
return errors.reduce((acc, error) => {
const _path = path ? `${path}.${error.property}` : error.property;
if (error.constraints) {
const key = Object.keys(error.constraints)[0];
acc[_path] = {
type: key,
message: error.constraints[key],
};
const _e = acc[_path];
if (validateAllFieldCriteria && _e) {
Object.assign(_e, { types: error.constraints });
}
}
if (error.children && error.children.length) {
parseErrors(error.children, validateAllFieldCriteria, acc, _path);
}
return acc;
}, parsedErrors);
};
export const classValidatorResolver: Resolver =
(schema, schemaOptions = {}, resolverOptions = {}) =>
async (values, _, options) => {
const { transformer, validator } = schemaOptions;
const data = plainToClass(schema, values, transformer);
const rawErrors = await (resolverOptions.mode === 'sync'
? validateSync
: validate)(data, validator);
if (rawErrors.length) {
return {
values: {},
errors: toNestErrors(
parseErrors(
rawErrors,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
}
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
values: resolverOptions.rawValues ? values : data,
errors: {},
};
};

View File

@@ -0,0 +1,2 @@
export * from './class-validator';
export * from './types';

View File

@@ -0,0 +1,16 @@
import { ClassConstructor, ClassTransformOptions } from 'class-transformer';
import { ValidatorOptions } from 'class-validator';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T extends { [_: string]: any }>(
schema: ClassConstructor<T>,
schemaOptions?: {
validator?: ValidatorOptions;
transformer?: ClassTransformOptions;
},
resolverOptions?: { mode?: 'async' | 'sync'; rawValues?: boolean },
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;

View File

@@ -0,0 +1,2 @@
import type { Resolver } from './types';
export declare const computedTypesResolver: Resolver;

View File

@@ -0,0 +1,2 @@
var r=require("@hookform/resolvers");exports.computedTypesResolver=function(e){return function(t,o,n){try{return Promise.resolve(function(o,s){try{var u=Promise.resolve(e(t)).then(function(e){return n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{errors:{},values:e}})}catch(r){return s(r)}return u&&u.then?u.then(void 0,s):u}(0,function(e){if(function(r){return null!=r.errors}(e))return{values:{},errors:r.toNestErrors((t=e,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),n)};var t;throw e}))}catch(r){return Promise.reject(r)}}};
//# sourceMappingURL=computed-types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"computed-types.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { ValidationError } from 'computed-types';\nimport type { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nconst parseErrorSchema = (computedTypesError: ValidationError) => {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n};\n\nexport const computedTypesResolver: Resolver =\n (schema) => async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n"],"names":["schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"mEAqBE,SAACA,GAAkBC,OAAAA,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCACnCD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAAA,uBAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAE,EACVT,OAAQM,EACR,4DATmCI,CAAA,EAU9BC,SAAAA,GACP,GA3BoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA0BZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAA,EACRS,OAAQI,EAAAA,cA3BQC,EA2BsBH,GAzBtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAA,IA0BoBd,IA3B/B,IAACY,EA+BpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EAAA,CAAA,CAAA"}

View File

@@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";var t=function(t){return function(n,o,u){try{return Promise.resolve(function(e,o){try{var s=Promise.resolve(t(n)).then(function(e){return u.shouldUseNativeValidation&&r({},u),{errors:{},values:e}})}catch(r){return o(r)}return s&&s.then?s.then(void 0,o):s}(0,function(r){if(function(r){return null!=r.errors}(r))return{values:{},errors:e((t=r,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),u)};var t;throw r}))}catch(r){return Promise.reject(r)}}};export{t as computedTypesResolver};
//# sourceMappingURL=computed-types.module.js.map

View File

@@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";const o=o=>async(s,a,t)=>{try{const e=await o(s);return t.shouldUseNativeValidation&&r({},t),{errors:{},values:e}}catch(r){if((r=>null!=r.errors)(r))return{values:{},errors:e((n=r,(n.errors||[]).reduce((r,e)=>(r[e.path.join(".")]={type:e.error.name,message:e.error.message},r),{})),t)};throw r}var n};export{o as computedTypesResolver};
//# sourceMappingURL=computed-types.modern.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"computed-types.modern.mjs","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { ValidationError } from 'computed-types';\nimport type { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nconst parseErrorSchema = (computedTypesError: ValidationError) => {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n};\n\nexport const computedTypesResolver: Resolver =\n (schema) => async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n"],"names":["computedTypesResolver","schema","async","values","_","options","data","shouldUseNativeValidation","validateFieldsNatively","errors","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message"],"mappings":"+EAKA,MAeaA,EACVC,GAAWC,MAAOC,EAAQC,EAAGC,KAC5B,IACE,MAAMC,QAAaL,EAAOE,GAI1B,OAFAE,EAAQE,2BAA6BC,EAAuB,CAAE,EAAEH,GAEzD,CACLI,OAAQ,CAAA,EACRN,OAAQG,EAEZ,CAAE,MAAOI,GACP,GA3BqBA,IACT,MAAhBA,EAAMD,OA0BEE,CAAkBD,GACpB,MAAO,CACLP,OAAQ,CAAA,EACRM,OAAQG,GA3BQC,EA2BsBH,GAzBtCG,EAAmBJ,QAAU,IAAIK,OAAO,CAACC,EAAKL,KACpDK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,GAPyB,KA0BoBV,IAIlD,MAAMK,CACR,CAhCsBG,KAgCtB"}

View File

@@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";var t=function(t){return function(n,o,u){try{return Promise.resolve(function(e,o){try{var s=Promise.resolve(t(n)).then(function(e){return u.shouldUseNativeValidation&&r({},u),{errors:{},values:e}})}catch(r){return o(r)}return s&&s.then?s.then(void 0,o):s}(0,function(r){if(function(r){return null!=r.errors}(r))return{values:{},errors:e((t=r,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),u)};var t;throw r}))}catch(r){return Promise.reject(r)}}};export{t as computedTypesResolver};
//# sourceMappingURL=computed-types.module.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"computed-types.module.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { ValidationError } from 'computed-types';\nimport type { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nconst parseErrorSchema = (computedTypesError: ValidationError) => {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n};\n\nexport const computedTypesResolver: Resolver =\n (schema) => async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n"],"names":["computedTypesResolver","schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"+EAKA,IAeaA,EACX,SAACC,GAAkBC,OAAAA,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCACnCD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAE,EACVT,OAAQM,EACR,4DATmCI,CAAA,EAU9BC,SAAAA,GACP,GA3BoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA0BZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAA,EACRS,OAAQI,GA3BQC,EA2BsBH,GAzBtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAA,IA0BoBd,IA3B/B,IAACY,EA+BpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EAAA,CAAA,CAAA"}

View File

@@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],r):r((e||self).hookformResolversComputedTypes={},e.hookformResolvers)}(this,function(e,r){e.computedTypesResolver=function(e){return function(o,t,n){try{return Promise.resolve(function(t,s){try{var i=Promise.resolve(e(o)).then(function(e){return n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{errors:{},values:e}})}catch(e){return s(e)}return i&&i.then?i.then(void 0,s):i}(0,function(e){if(function(e){return null!=e.errors}(e))return{values:{},errors:r.toNestErrors((o=e,(o.errors||[]).reduce(function(e,r){return e[r.path.join(".")]={type:r.error.name,message:r.error.message},e},{})),n)};var o;throw e}))}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=computed-types.umd.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"computed-types.umd.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport type { ValidationError } from 'computed-types';\nimport type { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nconst parseErrorSchema = (computedTypesError: ValidationError) => {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n};\n\nexport const computedTypesResolver: Resolver =\n (schema) => async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n"],"names":["schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"2VAqBE,SAACA,GAAkBC,OAAAA,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCACnCD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAAA,uBAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAE,EACVT,OAAQM,EACR,4DATmCI,CAAA,EAU9BC,SAAAA,GACP,GA3BoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA0BZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAA,EACRS,OAAQI,EAAAA,cA3BQC,EA2BsBH,GAzBtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAA,IA0BoBd,IA3B/B,IAACY,EA+BpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EAAA,CAAA,CAAA"}

View File

@@ -0,0 +1,2 @@
export * from './computed-types';
export * from './types';

View File

@@ -0,0 +1,2 @@
import type { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = (schema: any) => <TFieldValues extends FieldValues, TContext>(values: TFieldValues, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;

View File

@@ -0,0 +1,17 @@
{
"name": "@hookform/resolvers/computed-types",
"amdName": "hookformResolversComputedTypes",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: computed-types",
"main": "dist/computed-types.js",
"module": "dist/computed-types.module.js",
"umd:main": "dist/computed-types.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.0.0",
"@hookform/resolvers": "^2.0.0"
}
}

View File

@@ -0,0 +1,81 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import Schema, { Type, string } from 'computed-types';
import React from 'react';
import { useForm } from 'react-hook-form';
import { computedTypesResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = Schema({
username: string.min(2).error(USERNAME_REQUIRED_MESSAGE),
password: string.min(2).error(PASSWORD_REQUIRED_MESSAGE),
});
type FormData = Type<typeof schema> & { unusedProperty: string };
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: computedTypesResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with computed-types", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View File

@@ -0,0 +1,61 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import Schema, { Type, string } from 'computed-types';
import React from 'react';
import { useForm } from 'react-hook-form';
import { computedTypesResolver } from '..';
const schema = Schema({
username: string.min(2).error('username field is required'),
password: string.min(2).error('password field is required'),
address: Schema({
zipCode: string.min(5).max(5).error('zipCode field is required'),
}),
});
type FormData = Type<typeof schema> & { unusedProperty: string };
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: computedTypesResolver(schema), // Useful to check TypeScript regressions
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<input {...register('address.zipCode')} />
{errors.address?.zipCode && (
<span role="alert">{errors.address.zipCode.message}</span>
)}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with computed-types and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(screen.getByText(/username field is required/i)).toBeInTheDocument();
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(screen.getByText(/zipCode field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,86 @@
import Schema, { Type, string, number, array, boolean } from 'computed-types';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = Schema({
username: string.regexp(/^\w+$/).min(3).max(30),
password: string
.regexp(new RegExp('.*[A-Z].*'), 'One uppercase character')
.regexp(new RegExp('.*[a-z].*'), 'One lowercase character')
.regexp(new RegExp('.*\\d.*'), 'One number')
.regexp(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
)
.min(8, 'Must be at least 8 characters in length'),
repeatPassword: string,
accessToken: Schema.either(string, number).optional(),
birthYear: number.min(1900).max(2013).optional(),
email: string
.regexp(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)
.error('Incorrect email'),
tags: array.of(string),
enabled: boolean,
like: array
.of({
id: number,
name: string.min(4).max(4),
})
.optional(),
address: Schema({
city: string.min(3, 'Is required'),
zipCode: string
.min(5, 'Must be 5 characters long')
.max(5, 'Must be 5 characters long'),
}),
});
export const validData: Type<typeof schema> = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
accessToken: 'accessToken',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
like: [
{
id: 1,
name: 'name',
},
],
address: {
city: 'Awesome city',
zipCode: '12345',
},
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
address: {
city: '',
zipCode: '123',
},
};
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View File

@@ -0,0 +1,74 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`computedTypesResolver > should return a single error from computedTypesResolver when validation fails 1`] = `
{
"errors": {
"address": {
"city": {
"message": "Is required",
"ref": undefined,
"type": "ValidationError",
},
"zipCode": {
"message": "Must be 5 characters long",
"ref": undefined,
"type": "ValidationError",
},
},
"birthYear": {
"message": "Expect value to be "number"",
"ref": undefined,
"type": "ValidationError",
},
"email": {
"message": "Incorrect email",
"ref": {
"name": "email",
},
"type": "ValidationError",
},
"enabled": {
"message": "Expect value to be "boolean"",
"ref": undefined,
"type": "ValidationError",
},
"like": {
"id": {
"message": "Expect value to be "number"",
"ref": undefined,
"type": "ValidationError",
},
"name": {
"message": "Expect value to be "string"",
"ref": undefined,
"type": "ValidationError",
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "ValidationError",
},
"repeatPassword": {
"message": "Expect value to be "string"",
"ref": undefined,
"type": "ValidationError",
},
"tags": {
"message": "Expecting value to be an array",
"ref": undefined,
"type": "ValidationError",
},
"username": {
"message": "Expect value to be "string"",
"ref": {
"name": "username",
},
"type": "ValidationError",
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,40 @@
import { computedTypesResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('computedTypesResolver', () => {
it('should return values from computedTypesResolver when validation pass', async () => {
const result = await computedTypesResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from computedTypesResolver when validation fails', async () => {
const result = await computedTypesResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should throw any error unrelated to computed-types', async () => {
const schemaWithCustomError = schema.transform(() => {
throw Error('custom error');
});
const promise = computedTypesResolver(schemaWithCustomError)(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
await expect(promise).rejects.toThrow('custom error');
});
});

View File

@@ -0,0 +1,42 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import type { ValidationError } from 'computed-types';
import type { FieldErrors } from 'react-hook-form';
import type { Resolver } from './types';
const isValidationError = (error: any): error is ValidationError =>
error.errors != null;
const parseErrorSchema = (computedTypesError: ValidationError) => {
const parsedErrors: FieldErrors = {};
return (computedTypesError.errors || []).reduce((acc, error) => {
acc[error.path.join('.')] = {
type: error.error.name,
message: error.error.message,
};
return acc;
}, parsedErrors);
};
export const computedTypesResolver: Resolver =
(schema) => async (values, _, options) => {
try {
const data = await schema(values);
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
errors: {},
values: data,
};
} catch (error: any) {
if (isValidationError(error)) {
return {
values: {},
errors: toNestErrors(parseErrorSchema(error), options),
};
}
throw error;
}
};

View File

@@ -0,0 +1,2 @@
export * from './computed-types';
export * from './types';

View File

@@ -0,0 +1,13 @@
import type {
FieldValues,
ResolverOptions,
ResolverResult,
} from 'react-hook-form';
export type Resolver = (
schema: any,
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;

2
node_modules/@hookform/resolvers/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export * from './toNestErrors';
export * from './validateFieldsNatively';

2
node_modules/@hookform/resolvers/dist/resolvers.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
var e=require("react-hook-form"),r=function(r,t,i){if(r&&"reportValidity"in r){var s=e.get(i,t);r.setCustomValidity(s&&s.message||""),r.reportValidity()}},t=function(e,t){var i=function(i){var s=t.fields[i];s&&s.ref&&"reportValidity"in s.ref?r(s.ref,i,e):s.refs&&s.refs.forEach(function(t){return r(t,i,e)})};for(var s in t.fields)i(s)},i=function(e,r){return e.some(function(e){return e.startsWith(r+".")})};exports.toNestErrors=function(r,s){s.shouldUseNativeValidation&&t(r,s);var a={};for(var n in r){var o=e.get(s.fields,n),f=Object.assign(r[n]||{},{ref:o&&o.ref});if(i(s.names||Object.keys(r),n)){var u=Object.assign({},e.get(a,n));e.set(u,"root",f),e.set(a,n,u)}else e.set(a,n,f)}return a},exports.validateFieldsNatively=t;
//# sourceMappingURL=resolvers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"resolvers.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => names.some((n) => n.startsWith(name + '.'));\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","isNameInFieldArray","names","name","some","n","startsWith","shouldUseNativeValidation","fieldErrors","path","Object","assign","keys","fieldArrayErrors","set"],"mappings":"iCASMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,MAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQ,IAAAC,EAAAA,SAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,EAAME,MACfF,EAAME,KAAKC,QAAQ,SAACb,GAAqB,OACvCD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,ECAMa,EAAqB,SACzBC,EACAC,GAAuB,OACpBD,EAAME,KAAK,SAACC,GAAM,OAAAA,EAAEC,WAAWH,EAAO,IAAI,EAAC,uBA7BpB,SAC1Bd,EACAM,GAEAA,EAAQY,2BAA6Bb,EAAuBL,EAAQM,GAEpE,IAAMa,EAAc,GACpB,IAAK,IAAMC,KAAQpB,EAAQ,CACzB,IAAMQ,EAAQN,EAAGA,IAACI,EAAQG,OAAQW,GAC5BnB,EAAQoB,OAAOC,OAAOtB,EAAOoB,IAAS,CAAE,EAAE,CAC9CtB,IAAKU,GAASA,EAAMV,MAGtB,GAAIc,EAAmBN,EAAQO,OAASQ,OAAOE,KAAKvB,GAASoB,GAAO,CAClE,IAAMI,EAAmBH,OAAOC,OAAO,CAAA,EAAIpB,EAAGA,IAACiB,EAAaC,IAE5DK,EAAGA,IAACD,EAAkB,OAAQvB,GAC9BwB,EAAGA,IAACN,EAAaC,EAAMI,EACzB,MACEC,EAAGA,IAACN,EAAaC,EAAMnB,EAE3B,CAEA,OAAOkB,CACT"}

2
node_modules/@hookform/resolvers/dist/resolvers.mjs generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import{get as t,set as e}from"react-hook-form";const s=(e,s,o)=>{if(e&&"reportValidity"in e){const r=t(o,s);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},o=(t,e)=>{for(const o in e.fields){const r=e.fields[o];r&&r.ref&&"reportValidity"in r.ref?s(r.ref,o,t):r.refs&&r.refs.forEach(e=>s(e,o,t))}},r=(s,r)=>{r.shouldUseNativeValidation&&o(s,r);const f={};for(const o in s){const n=t(r.fields,o),a=Object.assign(s[o]||{},{ref:n&&n.ref});if(i(r.names||Object.keys(s),o)){const s=Object.assign({},t(f,o));e(s,"root",a),e(f,o,s)}else e(f,o,a)}return f},i=(t,e)=>t.some(t=>t.startsWith(e+"."));export{r as toNestErrors,o as validateFieldsNatively};
//# sourceMappingURL=resolvers.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"resolvers.mjs","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => names.some((n) => n.startsWith(name + '.'));\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","fields","field","refs","forEach","toNestErrors","shouldUseNativeValidation","fieldErrors","path","Object","assign","isNameInFieldArray","names","keys","fieldArrayErrors","set","name","some","n","startsWith"],"mappings":"+CASA,MAAMA,EAAoBA,CACxBC,EACAC,EACAC,KAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,MAAMG,EAAQC,EAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,GAIWC,EAAyBA,CACpCL,EACAM,KAEA,IAAK,MAAMP,KAAaO,EAAQC,OAAQ,CACtC,MAAMC,EAAQF,EAAQC,OAAOR,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,EAAMC,MACfD,EAAMC,KAAKC,QAASZ,GAClBD,EAAkBC,EAAKC,EAAWC,GAGxC,GCzBWW,EAAeA,CAC1BX,EACAM,KAEAA,EAAQM,2BAA6BP,EAAuBL,EAAQM,GAEpE,MAAMO,EAAc,CAAA,EACpB,IAAK,MAAMC,KAAQd,EAAQ,CACzB,MAAMQ,EAAQN,EAAII,EAAQC,OAAQO,GAC5Bb,EAAQc,OAAOC,OAAOhB,EAAOc,IAAS,GAAI,CAC9ChB,IAAKU,GAASA,EAAMV,MAGtB,GAAImB,EAAmBX,EAAQY,OAASH,OAAOI,KAAKnB,GAASc,GAAO,CAClE,MAAMM,EAAmBL,OAAOC,OAAO,CAAA,EAAId,EAAIW,EAAaC,IAE5DO,EAAID,EAAkB,OAAQnB,GAC9BoB,EAAIR,EAAaC,EAAMM,EACzB,MACEC,EAAIR,EAAaC,EAAMb,EAE3B,CAEA,OAAOY,GAGHI,EAAqBA,CACzBC,EACAI,IACGJ,EAAMK,KAAMC,GAAMA,EAAEC,WAAWH,EAAO"}

View File

@@ -0,0 +1,2 @@
import{get as r,set as e}from"react-hook-form";var t=function(e,t,i){if(e&&"reportValidity"in e){var n=r(i,t);e.setCustomValidity(n&&n.message||""),e.reportValidity()}},i=function(r,e){var i=function(i){var n=e.fields[i];n&&n.ref&&"reportValidity"in n.ref?t(n.ref,i,r):n.refs&&n.refs.forEach(function(e){return t(e,i,r)})};for(var n in e.fields)i(n)},n=function(t,n){n.shouldUseNativeValidation&&i(t,n);var f={};for(var a in t){var s=r(n.fields,a),u=Object.assign(t[a]||{},{ref:s&&s.ref});if(o(n.names||Object.keys(t),a)){var c=Object.assign({},r(f,a));e(c,"root",u),e(f,a,c)}else e(f,a,u)}return f},o=function(r,e){return r.some(function(r){return r.startsWith(e+".")})};export{n as toNestErrors,i as validateFieldsNatively};
//# sourceMappingURL=resolvers.module.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"resolvers.module.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => names.some((n) => n.startsWith(name + '.'));\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","toNestErrors","shouldUseNativeValidation","fieldErrors","path","Object","assign","isNameInFieldArray","names","keys","fieldArrayErrors","set","name","some","n","startsWith"],"mappings":"+CASA,IAAMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,EAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQ,IAAAC,EAAAA,SAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,EAAME,MACfF,EAAME,KAAKC,QAAQ,SAACb,GAAqB,OACvCD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,EC1Baa,EAAe,SAC1BZ,EACAM,GAEAA,EAAQO,2BAA6BR,EAAuBL,EAAQM,GAEpE,IAAMQ,EAAc,GACpB,IAAK,IAAMC,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAII,EAAQG,OAAQM,GAC5Bd,EAAQe,OAAOC,OAAOjB,EAAOe,IAAS,CAAE,EAAE,CAC9CjB,IAAKU,GAASA,EAAMV,MAGtB,GAAIoB,EAAmBZ,EAAQa,OAASH,OAAOI,KAAKpB,GAASe,GAAO,CAClE,IAAMM,EAAmBL,OAAOC,OAAO,CAAA,EAAIf,EAAIY,EAAaC,IAE5DO,EAAID,EAAkB,OAAQpB,GAC9BqB,EAAIR,EAAaC,EAAMM,EACzB,MACEC,EAAIR,EAAaC,EAAMd,EAE3B,CAEA,OAAOa,CACT,EAEMI,EAAqB,SACzBC,EACAI,GAAuB,OACpBJ,EAAMK,KAAK,SAACC,GAAM,OAAAA,EAAEC,WAAWH,EAAO,IAAI,EAAC"}

View File

@@ -0,0 +1,2 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","react-hook-form"],t):t((e||self).hookformResolvers={},e.ReactHookForm)}(this,function(e,t){var r=function(e,r,o){if(e&&"reportValidity"in e){var i=t.get(o,r);e.setCustomValidity(i&&i.message||""),e.reportValidity()}},o=function(e,t){var o=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?r(i.ref,o,e):i.refs&&i.refs.forEach(function(t){return r(t,o,e)})};for(var i in t.fields)o(i)},i=function(e,t){return e.some(function(e){return e.startsWith(t+".")})};e.toNestErrors=function(e,r){r.shouldUseNativeValidation&&o(e,r);var n={};for(var f in e){var s=t.get(r.fields,f),a=Object.assign(e[f]||{},{ref:s&&s.ref});if(i(r.names||Object.keys(e),f)){var d=Object.assign({},t.get(n,f));t.set(d,"root",a),t.set(n,f,d)}else t.set(n,f,a)}return n},e.validateFieldsNatively=o});
//# sourceMappingURL=resolvers.umd.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"resolvers.umd.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => names.some((n) => n.startsWith(name + '.'));\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","isNameInFieldArray","names","name","some","n","startsWith","shouldUseNativeValidation","fieldErrors","path","Object","assign","keys","fieldArrayErrors","set"],"mappings":"0SASA,IAAMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,MAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQ,IAAAC,EAAAA,SAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,EAAME,MACfF,EAAME,KAAKC,QAAQ,SAACb,GAAqB,OACvCD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,ECAMa,EAAqB,SACzBC,EACAC,GAAuB,OACpBD,EAAME,KAAK,SAACC,GAAM,OAAAA,EAAEC,WAAWH,EAAO,IAAI,EAAC,iBA7BpB,SAC1Bd,EACAM,GAEAA,EAAQY,2BAA6Bb,EAAuBL,EAAQM,GAEpE,IAAMa,EAAc,GACpB,IAAK,IAAMC,KAAQpB,EAAQ,CACzB,IAAMQ,EAAQN,EAAGA,IAACI,EAAQG,OAAQW,GAC5BnB,EAAQoB,OAAOC,OAAOtB,EAAOoB,IAAS,CAAE,EAAE,CAC9CtB,IAAKU,GAASA,EAAMV,MAGtB,GAAIc,EAAmBN,EAAQO,OAASQ,OAAOE,KAAKvB,GAASoB,GAAO,CAClE,IAAMI,EAAmBH,OAAOC,OAAO,CAAA,EAAIpB,EAAGA,IAACiB,EAAaC,IAE5DK,EAAGA,IAACD,EAAkB,OAAQvB,GAC9BwB,EAAGA,IAACN,EAAaC,EAAMI,EACzB,MACEC,EAAGA,IAACN,EAAaC,EAAMnB,EAE3B,CAEA,OAAOkB,CACT"}

View File

@@ -0,0 +1,2 @@
import { FieldErrors, FieldValues, ResolverOptions } from 'react-hook-form';
export declare const toNestErrors: <TFieldValues extends FieldValues>(errors: FieldErrors, options: ResolverOptions<TFieldValues>) => FieldErrors<TFieldValues>;

View File

@@ -0,0 +1,2 @@
import { FieldErrors, FieldValues, ResolverOptions } from 'react-hook-form';
export declare const validateFieldsNatively: <TFieldValues extends FieldValues>(errors: FieldErrors, options: ResolverOptions<TFieldValues>) => void;

View File

@@ -0,0 +1,2 @@
import type { Resolver } from './types';
export declare const effectTsResolver: Resolver;

View File

@@ -0,0 +1,2 @@
var e=require("@effect/schema/ArrayFormatter"),r=require("@effect/schema/ParseResult"),t=require("@hookform/resolvers");function n(e){if(e&&e.__esModule)return e;var r=Object.create(null);return e&&Object.keys(e).forEach(function(t){if("default"!==t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}}),r.default=e,r}var o=/*#__PURE__*/n(require("effect/Effect"));exports.effectTsResolver=function(n,u){return void 0===u&&(u={errors:"all",onExcessProperty:"ignore"}),function(c,a,s){return r.decodeUnknown(n,u)(c).pipe(o.catchAll(function(r){return o.flip(e.formatIssue(r))}),o.mapError(function(e){var r=e.reduce(function(e,r){return e[r.path.join(".")]={message:r.message,type:r._tag},e},{});return t.toNestErrors(r,s)}),o.tap(function(){return o.sync(function(){return s.shouldUseNativeValidation&&t.validateFieldsNatively({},s)})}),o.match({onFailure:function(e){return{errors:e,values:{}}},onSuccess:function(e){return{errors:{},values:e}}}),o.runPromise)}};
//# sourceMappingURL=effect-ts.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"effect-ts.js","sources":["../src/effect-ts.ts"],"sourcesContent":["import { formatIssue } from '@effect/schema/ArrayFormatter';\nimport { decodeUnknown } from '@effect/schema/ParseResult';\nimport { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport * as Effect from 'effect/Effect';\nimport type { FieldErrors } from 'react-hook-form';\nimport type { Resolver } from './types';\n\nexport const effectTsResolver: Resolver =\n (schema, config = { errors: 'all', onExcessProperty: 'ignore' }) =>\n (values, _, options) => {\n return decodeUnknown(\n schema,\n config,\n )(values).pipe(\n Effect.catchAll((parseIssue) => Effect.flip(formatIssue(parseIssue))),\n Effect.mapError((issues) => {\n const errors = issues.reduce((acc, current) => {\n const key = current.path.join('.');\n acc[key] = { message: current.message, type: current._tag };\n return acc;\n }, {} as FieldErrors);\n\n return toNestErrors(errors, options);\n }),\n Effect.tap(() =>\n Effect.sync(\n () =>\n options.shouldUseNativeValidation &&\n validateFieldsNatively({}, options),\n ),\n ),\n Effect.match({\n onFailure: (errors) => ({ errors, values: {} }),\n onSuccess: (result) => ({ errors: {}, values: result }),\n }),\n Effect.runPromise,\n );\n };\n"],"names":["schema","config","errors","onExcessProperty","values","_","options","decodeUnknown","pipe","Effect","catchAll","parseIssue","flip","formatIssue","mapError","issues","reduce","acc","current","path","join","message","type","_tag","toNestErrors","tap","sync","shouldUseNativeValidation","validateFieldsNatively","match","onFailure","onSuccess","result","runPromise"],"mappings":"8cAQE,SAACA,EAAQC,GAAsD,YAAtDA,IAAAA,IAAAA,EAAS,CAAEC,OAAQ,MAAOC,iBAAkB,WACpDC,SAAAA,EAAQC,EAAGC,GACV,OAAOC,EAAAA,cACLP,EACAC,EAFKM,CAGLH,GAAQI,KACRC,EAAOC,SAAS,SAACC,GAAe,OAAAF,EAAOG,KAAKC,EAAWA,YAACF,GAAY,GACpEF,EAAOK,SAAS,SAACC,GACf,IAAMb,EAASa,EAAOC,OAAO,SAACC,EAAKC,GAGjC,OADAD,EADYC,EAAQC,KAAKC,KAAK,MACnB,CAAEC,QAASH,EAAQG,QAASC,KAAMJ,EAAQK,MAC9CN,CACT,EAAG,CAAA,GAEH,OAAOO,EAAYA,aAACtB,EAAQI,EAC9B,GACAG,EAAOgB,IAAI,WACT,OAAAhB,EAAOiB,KACL,WACE,OAAApB,EAAQqB,2BACRC,yBAAuB,CAAA,EAAItB,EAAQ,EACtC,GAEHG,EAAOoB,MAAM,CACXC,UAAW,SAAC5B,GAAY,MAAA,CAAEA,OAAAA,EAAQE,OAAQ,CAAA,EAAI,EAC9C2B,UAAW,SAACC,GAAM,MAAM,CAAE9B,OAAQ,CAAA,EAAIE,OAAQ4B,EAAQ,IAExDvB,EAAOwB,WAEX,CAAC"}

Some files were not shown because too many files have changed in this diff Show More