added apps
This commit is contained in:
19
node_modules/@hookform/resolvers/io-ts/package.json
generated
vendored
Normal file
19
node_modules/@hookform/resolvers/io-ts/package.json
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@hookform/resolvers/io-ts",
|
||||
"amdName": "hookformResolversIoTs",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "React Hook Form validation resolver: io-ts",
|
||||
"main": "dist/io-ts.js",
|
||||
"module": "dist/io-ts.module.js",
|
||||
"umd:main": "dist/io-ts.umd.js",
|
||||
"source": "src/index.ts",
|
||||
"types": "dist/index.d.ts",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"react-hook-form": "^7.55.0",
|
||||
"@hookform/resolvers": "^2.0.0",
|
||||
"io-ts": "^2.0.0",
|
||||
"fp-ts": "^2.7.0"
|
||||
}
|
||||
}
|
||||
78
node_modules/@hookform/resolvers/io-ts/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
78
node_modules/@hookform/resolvers/io-ts/src/__tests__/Form-native-validation.tsx
generated
vendored
Normal file
@@ -0,0 +1,78 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import * as t from 'io-ts';
|
||||
import * as tt from 'io-ts-types';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ioTsResolver } from '..';
|
||||
|
||||
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
|
||||
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
|
||||
|
||||
const schema = t.type({
|
||||
username: tt.withMessage(tt.NonEmptyString, () => USERNAME_REQUIRED_MESSAGE),
|
||||
password: tt.withMessage(tt.NonEmptyString, () => PASSWORD_REQUIRED_MESSAGE),
|
||||
});
|
||||
|
||||
function TestComponent({
|
||||
onSubmit,
|
||||
}: { onSubmit: (data: t.OutputOf<typeof schema>) => void }) {
|
||||
const { register, handleSubmit } = useForm({
|
||||
resolver: ioTsResolver(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 io-ts", 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('');
|
||||
});
|
||||
87
node_modules/@hookform/resolvers/io-ts/src/__tests__/Form.tsx
generated
vendored
Normal file
87
node_modules/@hookform/resolvers/io-ts/src/__tests__/Form.tsx
generated
vendored
Normal file
@@ -0,0 +1,87 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import user from '@testing-library/user-event';
|
||||
import * as t from 'io-ts';
|
||||
import * as tt from 'io-ts-types';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { ioTsResolver } from '..';
|
||||
|
||||
const schema = t.type({
|
||||
username: tt.withMessage(
|
||||
tt.NonEmptyString,
|
||||
() => 'username is a required field',
|
||||
),
|
||||
password: tt.withMessage(
|
||||
tt.NonEmptyString,
|
||||
() => 'password is a required field',
|
||||
),
|
||||
});
|
||||
|
||||
interface FormData {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
function TestComponent({
|
||||
onSubmit,
|
||||
}: { onSubmit: (data: t.OutputOf<typeof schema>) => void }) {
|
||||
const {
|
||||
register,
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
} = useForm({
|
||||
resolver: ioTsResolver(schema),
|
||||
criteriaMode: 'all',
|
||||
});
|
||||
|
||||
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 io-ts 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 is a required field/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/password is a required field/i)).toBeInTheDocument();
|
||||
expect(handleSubmit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
export function TestComponentManualType({
|
||||
onSubmit,
|
||||
}: {
|
||||
onSubmit: (data: FormData) => void;
|
||||
}) {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<t.OutputOf<typeof schema>, undefined, FormData>({
|
||||
resolver: ioTsResolver(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>
|
||||
);
|
||||
}
|
||||
112
node_modules/@hookform/resolvers/io-ts/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
112
node_modules/@hookform/resolvers/io-ts/src/__tests__/__fixtures__/data.ts
generated
vendored
Normal file
@@ -0,0 +1,112 @@
|
||||
import * as t from 'io-ts';
|
||||
import * as tt from 'io-ts-types';
|
||||
|
||||
import { Field, InternalFieldName } from 'react-hook-form';
|
||||
|
||||
export const schema = t.intersection([
|
||||
t.type({
|
||||
username: tt.NonEmptyString,
|
||||
password: tt.NonEmptyString,
|
||||
accessToken: tt.UUID,
|
||||
birthYear: t.number,
|
||||
email: t.string,
|
||||
tags: t.array(
|
||||
t.type({
|
||||
name: t.string,
|
||||
}),
|
||||
),
|
||||
luckyNumbers: t.array(t.number),
|
||||
enabled: t.boolean,
|
||||
animal: t.union([
|
||||
t.string,
|
||||
t.number,
|
||||
t.literal('bird'),
|
||||
t.literal('snake'),
|
||||
]),
|
||||
vehicles: t.array(
|
||||
t.union([
|
||||
t.type({
|
||||
type: t.literal('car'),
|
||||
brand: t.string,
|
||||
horsepower: t.number,
|
||||
}),
|
||||
t.type({
|
||||
type: t.literal('bike'),
|
||||
speed: t.number,
|
||||
}),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
t.partial({
|
||||
like: t.array(
|
||||
t.type({
|
||||
id: tt.withMessage(
|
||||
t.number,
|
||||
(i) => `this id is very important but you passed: ${typeof i}(${i})`,
|
||||
),
|
||||
name: t.string,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const validData = {
|
||||
username: 'Doe',
|
||||
password: 'Password123',
|
||||
accessToken: 'c2883927-5178-4ad1-bbee-07ba33a5de19',
|
||||
birthYear: 2000,
|
||||
email: 'john@doe.com',
|
||||
tags: [{ name: 'test' }],
|
||||
enabled: true,
|
||||
luckyNumbers: [17, 5],
|
||||
animal: 'cat',
|
||||
like: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
vehicles: [{ type: 'car', brand: 'BMW', horsepower: 150 }],
|
||||
} satisfies t.OutputOf<typeof schema>;
|
||||
|
||||
export const invalidData = {
|
||||
username: 'test',
|
||||
password: 'Password123',
|
||||
repeatPassword: 'Password123',
|
||||
birthYear: 2000,
|
||||
accessToken: '1015d809-e99d-41ec-b161-981a3c243df8',
|
||||
email: 'john@doe.com',
|
||||
tags: [{ name: 'test' }],
|
||||
enabled: true,
|
||||
animal: ['dog'],
|
||||
luckyNumbers: [1, 2, '3'],
|
||||
like: [
|
||||
{
|
||||
id: '1',
|
||||
name: 'name',
|
||||
},
|
||||
],
|
||||
vehicles: [
|
||||
{ type: 'car', brand: 'BMW', horsepower: 150 },
|
||||
{ type: 'car', brand: 'Mercedes' },
|
||||
],
|
||||
} as unknown as t.OutputOf<typeof schema>;
|
||||
|
||||
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',
|
||||
},
|
||||
};
|
||||
89
node_modules/@hookform/resolvers/io-ts/src/__tests__/__snapshots__/io-ts.ts.snap
generated
vendored
Normal file
89
node_modules/@hookform/resolvers/io-ts/src/__tests__/__snapshots__/io-ts.ts.snap
generated
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`ioTsResolver > should return a single error from ioTsResolver when validation fails 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"animal": {
|
||||
"message": "expected string but got ["dog"]",
|
||||
"ref": undefined,
|
||||
"type": "string",
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "this id is very important but you passed: string(1)",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
},
|
||||
],
|
||||
"luckyNumbers": [
|
||||
,
|
||||
,
|
||||
{
|
||||
"message": "expected number but got "3"",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
],
|
||||
"vehicles": [
|
||||
,
|
||||
{
|
||||
"horsepower": {
|
||||
"message": "expected number but got undefined",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
|
||||
exports[`ioTsResolver > should return all the errors from ioTsResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
|
||||
{
|
||||
"errors": {
|
||||
"animal": {
|
||||
"message": "expected "snake" but got ["dog"]",
|
||||
"ref": undefined,
|
||||
"type": ""snake"",
|
||||
"types": {
|
||||
""bird"": "expected "bird" but got ["dog"]",
|
||||
""snake"": "expected "snake" but got ["dog"]",
|
||||
"number": "expected number but got ["dog"]",
|
||||
"string": "expected string but got ["dog"]",
|
||||
},
|
||||
},
|
||||
"like": [
|
||||
{
|
||||
"id": {
|
||||
"message": "this id is very important but you passed: string(1)",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
},
|
||||
],
|
||||
"luckyNumbers": [
|
||||
,
|
||||
,
|
||||
{
|
||||
"message": "expected number but got "3"",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
],
|
||||
"vehicles": [
|
||||
,
|
||||
{
|
||||
"horsepower": {
|
||||
"message": "expected number but got undefined",
|
||||
"ref": undefined,
|
||||
"type": "number",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
"values": {},
|
||||
}
|
||||
`;
|
||||
57
node_modules/@hookform/resolvers/io-ts/src/__tests__/errorsToRecord.ts
generated
vendored
Normal file
57
node_modules/@hookform/resolvers/io-ts/src/__tests__/errorsToRecord.ts
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
import { isLeft } from 'fp-ts/Either';
|
||||
import * as t from 'io-ts';
|
||||
import errorsToRecord from '../errorsToRecord';
|
||||
|
||||
const assertLeft = <T>(result: t.Validation<T>) => {
|
||||
expect(isLeft(result)).toBe(true);
|
||||
if (!isLeft(result)) {
|
||||
throw new Error(
|
||||
'panic! error is not of the "left" type, should be unreachable',
|
||||
);
|
||||
}
|
||||
return result.left;
|
||||
};
|
||||
|
||||
const FIRST_NAME_FIELD_PATH = 'firstName' as const;
|
||||
const FIRST_NAME_ERROR_SHAPE = {
|
||||
message: 'expected string but got undefined',
|
||||
type: 'string',
|
||||
};
|
||||
describe('errorsToRecord', () => {
|
||||
it('should return a correct error for an exact intersection type error object', () => {
|
||||
// a recommended pattern from https://github.com/gcanti/io-ts/blob/master/index.md#mixing-required-and-optional-props
|
||||
const schema = t.exact(
|
||||
t.intersection([
|
||||
t.type({
|
||||
[FIRST_NAME_FIELD_PATH]: t.string,
|
||||
}),
|
||||
t.partial({
|
||||
lastName: t.string,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const error = assertLeft(schema.decode({}));
|
||||
const record = errorsToRecord(false)(error);
|
||||
expect(record[FIRST_NAME_FIELD_PATH]).toMatchObject(FIRST_NAME_ERROR_SHAPE);
|
||||
});
|
||||
it('should return a correct error for a branded intersection', () => {
|
||||
interface Brand {
|
||||
readonly Brand: unique symbol;
|
||||
}
|
||||
const schema = t.brand(
|
||||
t.intersection([
|
||||
t.type({
|
||||
[FIRST_NAME_FIELD_PATH]: t.string,
|
||||
}),
|
||||
t.type({
|
||||
lastName: t.string,
|
||||
}),
|
||||
]),
|
||||
(_x): _x is t.Branded<typeof _x, Brand> => true,
|
||||
'Brand',
|
||||
);
|
||||
const error = assertLeft(schema.decode({}));
|
||||
const record = errorsToRecord(false)(error);
|
||||
expect(record[FIRST_NAME_FIELD_PATH]).toMatchObject(FIRST_NAME_ERROR_SHAPE);
|
||||
});
|
||||
});
|
||||
91
node_modules/@hookform/resolvers/io-ts/src/__tests__/io-ts.ts
generated
vendored
Normal file
91
node_modules/@hookform/resolvers/io-ts/src/__tests__/io-ts.ts
generated
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
import * as t from 'io-ts';
|
||||
import * as tt from 'io-ts-types';
|
||||
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
|
||||
import { ioTsResolver } from '..';
|
||||
import { fields, invalidData, schema, validData } from './__fixtures__/data';
|
||||
|
||||
const shouldUseNativeValidation = false;
|
||||
|
||||
describe('ioTsResolver', () => {
|
||||
it('should return values from ioTsResolver when validation pass', async () => {
|
||||
const validateSpy = vi.spyOn(schema, 'decode');
|
||||
|
||||
const result = ioTsResolver(schema)(validData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(validateSpy).toHaveBeenCalled();
|
||||
expect(result).toEqual({ errors: {}, values: validData });
|
||||
});
|
||||
|
||||
it('should return a single error from ioTsResolver when validation fails', () => {
|
||||
const result = ioTsResolver(schema)(invalidData, undefined, {
|
||||
fields,
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('should return all the errors from ioTsResolver when validation fails with `validateAllFieldCriteria` set to true', () => {
|
||||
const result = ioTsResolver(schema)(invalidData, undefined, {
|
||||
fields,
|
||||
criteriaMode: 'all',
|
||||
shouldUseNativeValidation,
|
||||
});
|
||||
|
||||
expect(result).toMatchSnapshot();
|
||||
});
|
||||
|
||||
/**
|
||||
* Type inference tests
|
||||
*/
|
||||
it('should correctly infer the output type from a io-ts schema', () => {
|
||||
const resolver = ioTsResolver(t.type({ id: t.number }));
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: number }, unknown, { id: number }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a io-ts schema using a transform', () => {
|
||||
const resolver = ioTsResolver(t.type({ id: tt.NumberFromString }));
|
||||
|
||||
expectTypeOf(resolver).toEqualTypeOf<
|
||||
Resolver<{ id: string }, unknown, { id: number }>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a io-ts schema for the handleSubmit function in useForm', () => {
|
||||
const schema = t.type({ id: t.number });
|
||||
|
||||
const form = useForm({
|
||||
resolver: ioTsResolver(schema),
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: number;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
|
||||
it('should correctly infer the output type from a io-ts schema with a transform for the handleSubmit function in useForm', () => {
|
||||
const schema = t.type({ id: tt.NumberFromString });
|
||||
|
||||
const form = useForm({
|
||||
resolver: ioTsResolver(schema),
|
||||
});
|
||||
|
||||
expectTypeOf(form.watch('id')).toEqualTypeOf<string>();
|
||||
|
||||
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
|
||||
SubmitHandler<{
|
||||
id: number;
|
||||
}>
|
||||
>();
|
||||
});
|
||||
});
|
||||
18
node_modules/@hookform/resolvers/io-ts/src/arrayToPath.ts
generated
vendored
Normal file
18
node_modules/@hookform/resolvers/io-ts/src/arrayToPath.ts
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
import * as Either from 'fp-ts/Either';
|
||||
import { pipe } from 'fp-ts/function';
|
||||
|
||||
const arrayToPath = (paths: Either.Either<string, number>[]): string =>
|
||||
paths.reduce(
|
||||
(previous, path, index) =>
|
||||
pipe(
|
||||
path,
|
||||
Either.fold(
|
||||
(key) => `${index > 0 ? '.' : ''}${key}`,
|
||||
(key) => `[${key}]`,
|
||||
),
|
||||
(path) => `${previous}${path}`,
|
||||
),
|
||||
'',
|
||||
);
|
||||
|
||||
export default arrayToPath;
|
||||
144
node_modules/@hookform/resolvers/io-ts/src/errorsToRecord.ts
generated
vendored
Normal file
144
node_modules/@hookform/resolvers/io-ts/src/errorsToRecord.ts
generated
vendored
Normal file
@@ -0,0 +1,144 @@
|
||||
import * as Either from 'fp-ts/Either';
|
||||
import * as Option from 'fp-ts/Option';
|
||||
import * as ReadonlyArray from 'fp-ts/ReadonlyArray';
|
||||
import * as ReadonlyRecord from 'fp-ts/ReadonlyRecord';
|
||||
import * as SemiGroup from 'fp-ts/Semigroup';
|
||||
import { absurd, flow, identity, not, pipe } from 'fp-ts/function';
|
||||
import * as t from 'io-ts';
|
||||
import {
|
||||
ExactType,
|
||||
IntersectionType,
|
||||
RefinementType,
|
||||
TaggedUnionType,
|
||||
UnionType,
|
||||
ValidationError,
|
||||
} from 'io-ts';
|
||||
import { FieldError } from 'react-hook-form';
|
||||
import arrayToPath from './arrayToPath';
|
||||
|
||||
export type ErrorObject = Record<string, FieldError>;
|
||||
export type FieldErrorWithPath = FieldError & { path: string };
|
||||
|
||||
const INSTANCE_TYPES_TO_FILTER = [
|
||||
TaggedUnionType,
|
||||
UnionType,
|
||||
IntersectionType,
|
||||
ExactType,
|
||||
RefinementType,
|
||||
];
|
||||
const formatErrorPath = (context: t.Context): string =>
|
||||
pipe(
|
||||
context,
|
||||
ReadonlyArray.filterMapWithIndex((index, contextEntry) => {
|
||||
const previousIndex = index - 1;
|
||||
const previousContextEntry =
|
||||
previousIndex === -1 ? undefined : context[previousIndex];
|
||||
const shouldBeFiltered =
|
||||
previousContextEntry === undefined ||
|
||||
INSTANCE_TYPES_TO_FILTER.some(
|
||||
(type) => previousContextEntry.type instanceof type,
|
||||
);
|
||||
|
||||
return shouldBeFiltered ? Option.none : Option.some(contextEntry);
|
||||
}),
|
||||
ReadonlyArray.map(({ key }) => key),
|
||||
ReadonlyArray.map((key) =>
|
||||
pipe(
|
||||
key,
|
||||
(k) => parseInt(k, 10),
|
||||
Either.fromPredicate(not<number>(Number.isNaN), () => key),
|
||||
),
|
||||
),
|
||||
ReadonlyArray.toArray,
|
||||
arrayToPath,
|
||||
);
|
||||
|
||||
const formatError = (e: t.ValidationError): FieldErrorWithPath => {
|
||||
const path = formatErrorPath(e.context);
|
||||
|
||||
const message = pipe(
|
||||
e.message,
|
||||
Either.fromNullable(e.context),
|
||||
Either.mapLeft(
|
||||
flow(
|
||||
ReadonlyArray.last,
|
||||
Option.map(
|
||||
(contextEntry) =>
|
||||
`expected ${contextEntry.type.name} but got ${JSON.stringify(
|
||||
contextEntry.actual,
|
||||
)}`,
|
||||
),
|
||||
Option.getOrElseW(() =>
|
||||
absurd<string>('Error context is missing name' as never),
|
||||
),
|
||||
),
|
||||
),
|
||||
Either.getOrElseW(identity),
|
||||
);
|
||||
|
||||
const type = pipe(
|
||||
e.context,
|
||||
ReadonlyArray.last,
|
||||
Option.map((contextEntry) => contextEntry.type.name),
|
||||
Option.getOrElse(() => 'unknown'),
|
||||
);
|
||||
|
||||
return { message, type, path };
|
||||
};
|
||||
|
||||
// this is almost the same function like Semigroup.getObjectSemigroup but reversed
|
||||
// in order to get the first error
|
||||
const getObjectSemigroup = <
|
||||
A extends Record<string, unknown> = never,
|
||||
>(): SemiGroup.Semigroup<A> => ({
|
||||
concat: (first, second) => Object.assign({}, second, first),
|
||||
});
|
||||
|
||||
const concatToSingleError = (
|
||||
errors: ReadonlyArray<FieldErrorWithPath>,
|
||||
): ErrorObject =>
|
||||
pipe(
|
||||
errors,
|
||||
ReadonlyArray.map((error) => ({
|
||||
[error.path]: {
|
||||
type: error.type,
|
||||
message: error.message,
|
||||
},
|
||||
})),
|
||||
(errors) => SemiGroup.fold(getObjectSemigroup<ErrorObject>())({}, errors),
|
||||
);
|
||||
|
||||
const appendSeveralErrors: SemiGroup.Semigroup<FieldErrorWithPath> = {
|
||||
concat: (a, b) => ({
|
||||
...b,
|
||||
types: { ...a.types, [a.type]: a.message, [b.type]: b.message },
|
||||
}),
|
||||
};
|
||||
|
||||
const concatToMultipleErrors = (
|
||||
errors: ReadonlyArray<FieldErrorWithPath>,
|
||||
): ErrorObject =>
|
||||
pipe(
|
||||
ReadonlyRecord.fromFoldableMap(appendSeveralErrors, ReadonlyArray.Foldable)(
|
||||
errors,
|
||||
(error) => [error.path, error],
|
||||
),
|
||||
ReadonlyRecord.map((errorWithPath) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { path, ...error } = errorWithPath;
|
||||
|
||||
return error;
|
||||
}),
|
||||
);
|
||||
|
||||
const errorsToRecord =
|
||||
(validateAllFieldCriteria: boolean) =>
|
||||
(validationErrors: ReadonlyArray<ValidationError>): ErrorObject => {
|
||||
const concat = validateAllFieldCriteria
|
||||
? concatToMultipleErrors
|
||||
: concatToSingleError;
|
||||
|
||||
return pipe(validationErrors, ReadonlyArray.map(formatError), concat);
|
||||
};
|
||||
|
||||
export default errorsToRecord;
|
||||
1
node_modules/@hookform/resolvers/io-ts/src/index.ts
generated
vendored
Normal file
1
node_modules/@hookform/resolvers/io-ts/src/index.ts
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
export * from './io-ts';
|
||||
81
node_modules/@hookform/resolvers/io-ts/src/io-ts.ts
generated
vendored
Normal file
81
node_modules/@hookform/resolvers/io-ts/src/io-ts.ts
generated
vendored
Normal file
@@ -0,0 +1,81 @@
|
||||
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
|
||||
import * as Either from 'fp-ts/Either';
|
||||
import { pipe } from 'fp-ts/function';
|
||||
import * as t from 'io-ts';
|
||||
import {
|
||||
FieldErrors,
|
||||
FieldValues,
|
||||
Resolver,
|
||||
ResolverError,
|
||||
ResolverSuccess,
|
||||
} from 'react-hook-form';
|
||||
import errorsToRecord, { ErrorObject } from './errorsToRecord';
|
||||
|
||||
export function ioTsResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: t.Type<Output, Input>,
|
||||
resolverOptions?: {
|
||||
mode?: 'async' | 'sync';
|
||||
raw?: false;
|
||||
},
|
||||
): Resolver<Input, Context, Output>;
|
||||
|
||||
export function ioTsResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: t.Type<Output, Input>,
|
||||
resolverOptions: {
|
||||
mode?: 'async' | 'sync';
|
||||
raw: true;
|
||||
},
|
||||
): Resolver<Input, Context, Input>;
|
||||
|
||||
/**
|
||||
* Creates a resolver for react-hook-form using io-ts schema validation
|
||||
* @param {t.Type<TFieldValues, T>} schema - The io-ts schema to validate against
|
||||
* @param {Object} options - Additional resolver configuration
|
||||
* @param {string} [options.mode='async'] - Validation mode
|
||||
* @returns {Resolver<t.OutputOf<typeof schema>>} A resolver function compatible with react-hook-form
|
||||
* @example
|
||||
* const schema = t.type({
|
||||
* name: t.string,
|
||||
* age: t.number
|
||||
* });
|
||||
*
|
||||
* useForm({
|
||||
* resolver: ioTsResolver(schema)
|
||||
* });
|
||||
*/
|
||||
export function ioTsResolver<Input extends FieldValues, Context, Output>(
|
||||
schema: t.Type<Output, Input>,
|
||||
): Resolver<Input, Context, Input | Output> {
|
||||
return (values, _context, options) =>
|
||||
pipe(
|
||||
values,
|
||||
schema.decode,
|
||||
Either.mapLeft(
|
||||
errorsToRecord(
|
||||
!options.shouldUseNativeValidation && options.criteriaMode === 'all',
|
||||
),
|
||||
),
|
||||
Either.mapLeft((errors: ErrorObject) =>
|
||||
toNestErrors<Input>(errors, options),
|
||||
),
|
||||
Either.fold<
|
||||
FieldErrors<Input>,
|
||||
Output,
|
||||
ResolverError<Input> | ResolverSuccess<Output | Input>
|
||||
>(
|
||||
(errors) => ({
|
||||
values: {},
|
||||
errors,
|
||||
}),
|
||||
(values) => {
|
||||
options.shouldUseNativeValidation &&
|
||||
validateFieldsNatively({}, options);
|
||||
|
||||
return {
|
||||
values,
|
||||
errors: {},
|
||||
};
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user