build revisions and layout updates for toast

This commit is contained in:
makearmy 2025-09-26 14:31:18 -04:00
parent b341a3675e
commit 39235193e6
1116 changed files with 130517 additions and 12 deletions

View file

@ -0,0 +1 @@
export * from './valibot';

View file

@ -0,0 +1,10 @@
import { FieldValues, Resolver } from 'react-hook-form';
import { BaseSchema, BaseSchemaAsync, Config, InferIssue } from 'valibot';
export declare function valibotResolver<Input extends FieldValues, Context, Output>(schema: BaseSchema<Input, Output, any> | BaseSchemaAsync<Input, Output, any>, schemaOptions?: Partial<Omit<Config<InferIssue<typeof schema>>, 'abortPipeEarly' | 'skipPipe'>>, resolverOptions?: {
mode?: 'async' | 'sync';
raw?: false;
}): Resolver<Input, Context, Output>;
export declare function valibotResolver<Input extends FieldValues, Context, Output>(schema: BaseSchema<Input, Output, any> | BaseSchemaAsync<Input, Output, any>, schemaOptions: Partial<Omit<Config<InferIssue<typeof schema>>, 'abortPipeEarly' | 'skipPipe'>> | undefined, resolverOptions: {
mode?: 'async' | 'sync';
raw: true;
}): Resolver<Input, Context, Input>;

View file

@ -0,0 +1,2 @@
var e=require("@hookform/resolvers"),r=require("react-hook-form"),s=require("valibot");exports.valibotResolver=function(t,o,a){return void 0===a&&(a={}),function(i,u,n){try{var v=!n.shouldUseNativeValidation&&"all"===n.criteriaMode;return Promise.resolve(s.safeParseAsync(t,i,Object.assign({},o,{abortPipeEarly:!v}))).then(function(t){if(t.issues){for(var o={};t.issues.length;){var u=t.issues[0],c=s.getDotPath(u);if(c&&(o[c]||(o[c]={message:u.message,type:u.type}),v)){var l=o[c].types,f=l&&l[u.type];o[c]=r.appendErrors(c,v,o,u.type,f?[].concat(f,u.message):u.message)}t.issues.shift()}return{values:{},errors:e.toNestErrors(o,n)}}return{values:a.raw?Object.assign({},i):t.output,errors:{}}})}catch(e){return Promise.reject(e)}}};
//# sourceMappingURL=valibot.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
import{toNestErrors as e}from"@hookform/resolvers";import{appendErrors as r}from"react-hook-form";import{safeParseAsync as s,getDotPath as t}from"valibot";function o(o,i,a){return void 0===a&&(a={}),function(n,u,m){try{var c=!m.shouldUseNativeValidation&&"all"===m.criteriaMode;return Promise.resolve(s(o,n,Object.assign({},i,{abortPipeEarly:!c}))).then(function(s){if(s.issues){for(var o={};s.issues.length;){var i=s.issues[0],u=t(i);if(u&&(o[u]||(o[u]={message:i.message,type:i.type}),c)){var f=o[u].types,l=f&&f[i.type];o[u]=r(u,c,o,i.type,l?[].concat(l,i.message):i.message)}s.issues.shift()}return{values:{},errors:e(o,m)}}return{values:a.raw?Object.assign({},n):s.output,errors:{}}})}catch(e){return Promise.reject(e)}}}export{o as valibotResolver};
//# sourceMappingURL=valibot.module.js.map

View file

@ -0,0 +1,2 @@
import{toNestErrors as s}from"@hookform/resolvers";import{appendErrors as e}from"react-hook-form";import{safeParseAsync as t,getDotPath as r}from"valibot";function o(o,a,i={}){return async(n,u,c)=>{const m=!c.shouldUseNativeValidation&&"all"===c.criteriaMode,p=await t(o,n,Object.assign({},a,{abortPipeEarly:!m}));if(p.issues){const t={};for(;p.issues.length;){const s=p.issues[0],o=r(s);if(o&&(t[o]||(t[o]={message:s.message,type:s.type}),m)){const r=t[o].types,a=r&&r[s.type];t[o]=e(o,m,t,s.type,a?[].concat(a,s.message):s.message)}p.issues.shift()}return{values:{},errors:s(t,c)}}return{values:i.raw?Object.assign({},n):p.output,errors:{}}}}export{o as valibotResolver};
//# sourceMappingURL=valibot.modern.mjs.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
import{toNestErrors as e}from"@hookform/resolvers";import{appendErrors as r}from"react-hook-form";import{safeParseAsync as s,getDotPath as t}from"valibot";function o(o,i,a){return void 0===a&&(a={}),function(n,u,m){try{var c=!m.shouldUseNativeValidation&&"all"===m.criteriaMode;return Promise.resolve(s(o,n,Object.assign({},i,{abortPipeEarly:!c}))).then(function(s){if(s.issues){for(var o={};s.issues.length;){var i=s.issues[0],u=t(i);if(u&&(o[u]||(o[u]={message:i.message,type:i.type}),c)){var f=o[u].types,l=f&&f[i.type];o[u]=r(u,c,o,i.type,l?[].concat(l,i.message):i.message)}s.issues.shift()}return{values:{},errors:e(o,m)}}return{values:a.raw?Object.assign({},n):s.output,errors:{}}})}catch(e){return Promise.reject(e)}}}export{o as valibotResolver};
//# sourceMappingURL=valibot.module.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("@hookform/resolvers"),require("react-hook-form"),require("valibot")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","react-hook-form","valibot"],o):o((e||self).hookformResolversValibot={},e.hookformResolvers,e.ReactHookForm,e.valibot)}(this,function(e,o,r,s){e.valibotResolver=function(e,t,i){return void 0===i&&(i={}),function(a,n,f){try{var u=!f.shouldUseNativeValidation&&"all"===f.criteriaMode;return Promise.resolve(s.safeParseAsync(e,a,Object.assign({},t,{abortPipeEarly:!u}))).then(function(e){if(e.issues){for(var t={};e.issues.length;){var n=e.issues[0],l=s.getDotPath(n);if(l&&(t[l]||(t[l]={message:n.message,type:n.type}),u)){var c=t[l].types,v=c&&c[n.type];t[l]=r.appendErrors(l,u,t,n.type,v?[].concat(v,n.message):n.message)}e.issues.shift()}return{values:{},errors:o.toNestErrors(t,f)}}return{values:i.raw?Object.assign({},a):e.output,errors:{}}})}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=valibot.umd.js.map

File diff suppressed because one or more lines are too long

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

@ -0,0 +1,18 @@
{
"name": "@hookform/resolvers/valibot",
"amdName": "hookformResolversValibot",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: valibot",
"main": "dist/valibot.js",
"module": "dist/valibot.module.js",
"umd:main": "dist/valibot.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"@hookform/resolvers": "^2.0.0",
"react-hook-form": "^7.55.0",
"valibot": "^1.0.0 || ^1.0.0-beta.4 || ^1.0.0-rc"
}
}

View file

@ -0,0 +1,81 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import React from 'react';
import { useForm } from 'react-hook-form';
import * as v from 'valibot';
import { valibotResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is v.required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is v.required';
const schema = v.object({
username: v.pipe(
v.string(USERNAME_REQUIRED_MESSAGE),
v.minLength(2, USERNAME_REQUIRED_MESSAGE),
),
password: v.pipe(
v.string(PASSWORD_REQUIRED_MESSAGE),
v.minLength(2, PASSWORD_REQUIRED_MESSAGE),
),
});
type FormData = { username: string; password: string };
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: valibotResolver(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 Valibot", 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(/password/i), 'password');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View file

@ -0,0 +1,87 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import React from 'react';
import { useForm } from 'react-hook-form';
import * as v from 'valibot';
import { valibotResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = v.object({
username: v.pipe(
v.string(USERNAME_REQUIRED_MESSAGE),
v.minLength(2, USERNAME_REQUIRED_MESSAGE),
),
password: v.pipe(
v.string(PASSWORD_REQUIRED_MESSAGE),
v.minLength(2, PASSWORD_REQUIRED_MESSAGE),
),
});
type FormData = { username: string; password: string };
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>({
resolver: valibotResolver(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 Valibot 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();
});
export function TestComponentManualType({
onSubmit,
}: {
onSubmit: (data: FormData) => void;
}) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<v.InferInput<typeof schema>, undefined, FormData>({
resolver: valibotResolver(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>
);
}

View file

@ -0,0 +1,99 @@
import { Field, InternalFieldName } from 'react-hook-form';
import * as v from 'valibot';
export const schema = v.object({
username: v.pipe(
v.string(),
v.minLength(2),
v.maxLength(30),
v.regex(/^\w+$/),
),
password: v.pipe(
v.string('New Password is required'),
v.regex(new RegExp('.*[A-Z].*'), 'One uppercase character'),
v.regex(new RegExp('.*[a-z].*'), 'One lowercase character'),
v.regex(new RegExp('.*\\d.*'), 'One number'),
v.regex(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
),
v.minLength(8, 'Must be at least 8 characters in length'),
),
repeatPassword: v.string('Repeat Password is required'),
accessToken: v.union(
[
v.string('Access token should be a string'),
v.number('Access token should be a number'),
],
'access token is required',
),
birthYear: v.pipe(
v.number('Please enter your birth year'),
v.minValue(1900),
v.maxValue(2013),
),
email: v.pipe(v.string(), v.email('Invalid email address')),
tags: v.array(v.string('Tags should be strings')),
enabled: v.boolean(),
like: v.object({
id: v.number('Like id is required'),
name: v.pipe(
v.string('Like name is required'),
v.minLength(4, 'Too short'),
),
}),
});
export const schemaError = v.variant('type', [
v.object({ type: v.literal('a') }),
v.object({ type: v.literal('b') }),
]);
export const validSchemaErrorData = { type: 'a' } as v.InferOutput<
typeof schemaError
>;
export const invalidSchemaErrorData = { type: 'c' } as any as v.InferOutput<
typeof schemaError
>;
export const validData = {
username: 'Doe',
password: 'Password123_',
repeatPassword: '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' },
tags: [1, 2, 3],
} as any as v.InferOutput<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',
},
};

View file

@ -0,0 +1,418 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`valibotResolver > should return a single error from valibotResolver when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "access token is required",
"ref": undefined,
"type": "union",
},
"birthYear": {
"message": "Please enter your birth year",
"ref": undefined,
"type": "number",
},
"email": {
"message": "Invalid email address",
"ref": {
"name": "email",
},
"type": "email",
},
"enabled": {
"message": "Invalid type: Expected boolean but received undefined",
"ref": undefined,
"type": "boolean",
},
"like": {
"id": {
"message": "Like id is required",
"ref": undefined,
"type": "number",
},
"name": {
"message": "Like name is required",
"ref": undefined,
"type": "string",
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "regex",
},
"repeatPassword": {
"message": "Repeat Password is required",
"ref": undefined,
"type": "string",
},
"tags": [
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
},
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
},
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
},
],
"username": {
"message": "Invalid type: Expected string but received undefined",
"ref": {
"name": "username",
},
"type": "string",
},
},
"values": {},
}
`;
exports[`valibotResolver > should return a single error from valibotResolver with \`mode: sync\` when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "access token is required",
"ref": undefined,
"type": "union",
},
"birthYear": {
"message": "Please enter your birth year",
"ref": undefined,
"type": "number",
},
"email": {
"message": "Invalid email address",
"ref": {
"name": "email",
},
"type": "email",
},
"enabled": {
"message": "Invalid type: Expected boolean but received undefined",
"ref": undefined,
"type": "boolean",
},
"like": {
"id": {
"message": "Like id is required",
"ref": undefined,
"type": "number",
},
"name": {
"message": "Like name is required",
"ref": undefined,
"type": "string",
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "regex",
},
"repeatPassword": {
"message": "Repeat Password is required",
"ref": undefined,
"type": "string",
},
"tags": [
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
},
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
},
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
},
],
"username": {
"message": "Invalid type: Expected string but received undefined",
"ref": {
"name": "username",
},
"type": "string",
},
},
"values": {},
}
`;
exports[`valibotResolver > should return all the errors from valibotResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"accessToken": {
"message": "access token is required",
"ref": undefined,
"type": "union",
"types": {
"union": "access token is required",
},
},
"birthYear": {
"message": "Please enter your birth year",
"ref": undefined,
"type": "number",
"types": {
"number": "Please enter your birth year",
},
},
"email": {
"message": "Invalid email address",
"ref": {
"name": "email",
},
"type": "email",
"types": {
"email": "Invalid email address",
},
},
"enabled": {
"message": "Invalid type: Expected boolean but received undefined",
"ref": undefined,
"type": "boolean",
"types": {
"boolean": "Invalid type: Expected boolean but received undefined",
},
},
"like": {
"id": {
"message": "Like id is required",
"ref": undefined,
"type": "number",
"types": {
"number": "Like id is required",
},
},
"name": {
"message": "Like name is required",
"ref": undefined,
"type": "string",
"types": {
"string": "Like name is required",
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "regex",
"types": {
"min_length": "Must be at least 8 characters in length",
"regex": [
"One uppercase character",
"One lowercase character",
"One number",
],
},
},
"repeatPassword": {
"message": "Repeat Password is required",
"ref": undefined,
"type": "string",
"types": {
"string": "Repeat Password is required",
},
},
"tags": [
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
"types": {
"string": "Tags should be strings",
},
},
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
"types": {
"string": "Tags should be strings",
},
},
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
"types": {
"string": "Tags should be strings",
},
},
],
"username": {
"message": "Invalid type: Expected string but received undefined",
"ref": {
"name": "username",
},
"type": "string",
"types": {
"string": "Invalid type: Expected string but received undefined",
},
},
},
"values": {},
}
`;
exports[`valibotResolver > should return all the errors from valibotResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
{
"errors": {
"accessToken": {
"message": "access token is required",
"ref": undefined,
"type": "union",
"types": {
"union": "access token is required",
},
},
"birthYear": {
"message": "Please enter your birth year",
"ref": undefined,
"type": "number",
"types": {
"number": "Please enter your birth year",
},
},
"email": {
"message": "Invalid email address",
"ref": {
"name": "email",
},
"type": "email",
"types": {
"email": "Invalid email address",
},
},
"enabled": {
"message": "Invalid type: Expected boolean but received undefined",
"ref": undefined,
"type": "boolean",
"types": {
"boolean": "Invalid type: Expected boolean but received undefined",
},
},
"like": {
"id": {
"message": "Like id is required",
"ref": undefined,
"type": "number",
"types": {
"number": "Like id is required",
},
},
"name": {
"message": "Like name is required",
"ref": undefined,
"type": "string",
"types": {
"string": "Like name is required",
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "regex",
"types": {
"min_length": "Must be at least 8 characters in length",
"regex": [
"One uppercase character",
"One lowercase character",
"One number",
],
},
},
"repeatPassword": {
"message": "Repeat Password is required",
"ref": undefined,
"type": "string",
"types": {
"string": "Repeat Password is required",
},
},
"tags": [
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
"types": {
"string": "Tags should be strings",
},
},
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
"types": {
"string": "Tags should be strings",
},
},
{
"message": "Tags should be strings",
"ref": undefined,
"type": "string",
"types": {
"string": "Tags should be strings",
},
},
],
"username": {
"message": "Invalid type: Expected string but received undefined",
"ref": {
"name": "username",
},
"type": "string",
"types": {
"string": "Invalid type: Expected string but received undefined",
},
},
},
"values": {},
}
`;
exports[`valibotResolver > should return parsed values from valibotResolver with \`mode: sync\` when validation pass 1`] = `
{
"errors": {},
"values": {
"accessToken": "accessToken",
"birthYear": 2000,
"email": "john@doe.com",
"enabled": true,
"like": {
"id": 1,
"name": "name",
},
"password": "Password123_",
"repeatPassword": "Password123_",
"tags": [
"tag1",
"tag2",
],
"username": "Doe",
},
}
`;

View file

@ -0,0 +1,207 @@
import { SubmitHandler } from 'react-hook-form';
import { useForm } from 'react-hook-form';
import { Resolver } from 'react-hook-form';
import * as v from 'valibot';
/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */
import { valibotResolver } from '..';
import {
fields,
invalidData,
invalidSchemaErrorData,
schema,
schemaError,
validData,
validSchemaErrorData,
} from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('valibotResolver', () => {
it('should return parsed values from valibotResolver with `mode: sync` when validation pass', async () => {
vi.mock('valibot', async () => {
const a = await vi.importActual<any>('valibot');
return {
__esModule: true,
...a,
};
});
const funcSpy = vi.spyOn(v, 'safeParseAsync');
const result = await valibotResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation });
expect(funcSpy).toHaveBeenCalledTimes(1);
expect(result.errors).toEqual({});
expect(result).toMatchSnapshot();
});
it('should return a single error from valibotResolver with `mode: sync` when validation fails', async () => {
vi.mock('valibot', async () => {
const a = await vi.importActual<any>('valibot');
return {
__esModule: true,
...a,
};
});
const funcSpy = vi.spyOn(v, 'safeParseAsync');
const result = await valibotResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation });
expect(funcSpy).toHaveBeenCalledTimes(1);
expect(result).toMatchSnapshot();
});
it('should return values from valibotResolver when validation pass', async () => {
const result = await valibotResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from valibotResolver when validation fails', async () => {
const result = await valibotResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return values from valibotResolver when validation pass & raw=true', async () => {
const result = await valibotResolver(schema, undefined, {
raw: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return all the errors from valibotResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await valibotResolver(schema)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return all the errors from valibotResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await valibotResolver(schema, undefined, { mode: 'sync' })(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should be able to validate variants without errors', async () => {
const result = await valibotResolver(schemaError, undefined, {
mode: 'sync',
})(validSchemaErrorData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({
errors: {},
values: {
type: 'a',
},
});
});
it('should be able to validate variants with errors', async () => {
const result = await valibotResolver(schemaError, undefined, {
mode: 'sync',
})(invalidSchemaErrorData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({
errors: {
type: {
message: 'Invalid type: Expected ("a" | "b") but received "c"',
ref: undefined,
type: 'variant',
},
},
values: {},
});
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a valibot schema', () => {
const resolver = valibotResolver(v.object({ id: v.number() }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a valibot schema using a transform', () => {
const resolver = valibotResolver(
v.object({
id: v.pipe(
v.number(),
v.transform((val) => String(val)),
),
}),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: string }>
>();
});
it('should correctly infer the output type from a valibot schema for the handleSubmit function in useForm', () => {
const schema = v.object({ id: v.number() });
const form = useForm({
resolver: valibotResolver(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 valibot schema with a transform for the handleSubmit function in useForm', () => {
const schema = v.object({
id: v.pipe(
v.number(),
v.transform((val) => String(val)),
),
});
const form = useForm({
resolver: valibotResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: string;
}>
>();
});
});

View file

@ -0,0 +1 @@
export * from './valibot';

138
node_modules/@hookform/resolvers/valibot/src/valibot.ts generated vendored Normal file
View file

@ -0,0 +1,138 @@
import { toNestErrors } from '@hookform/resolvers';
import {
FieldError,
FieldValues,
Resolver,
appendErrors,
} from 'react-hook-form';
import { getDotPath, safeParseAsync } from 'valibot';
import { BaseSchema, BaseSchemaAsync, Config, InferIssue } from 'valibot';
export function valibotResolver<Input extends FieldValues, Context, Output>(
schema: BaseSchema<Input, Output, any> | BaseSchemaAsync<Input, Output, any>,
schemaOptions?: Partial<
Omit<Config<InferIssue<typeof schema>>, 'abortPipeEarly' | 'skipPipe'>
>,
resolverOptions?: {
mode?: 'async' | 'sync';
raw?: false;
},
): Resolver<Input, Context, Output>;
export function valibotResolver<Input extends FieldValues, Context, Output>(
schema: BaseSchema<Input, Output, any> | BaseSchemaAsync<Input, Output, any>,
schemaOptions:
| Partial<
Omit<Config<InferIssue<typeof schema>>, 'abortPipeEarly' | 'skipPipe'>
>
| undefined,
resolverOptions: {
mode?: 'async' | 'sync';
raw: true;
},
): Resolver<Input, Context, Input>;
/**
* Creates a resolver for react-hook-form using Valibot schema validation
* @param {BaseSchema<TFieldValues, TFieldValues, any> | BaseSchemaAsync<TFieldValues, TFieldValues, any>} schema - The Valibot schema to validate against
* @param {Partial<Omit<Config<InferIssue<typeof schema>>, 'abortPipeEarly' | 'skipPipe'>>} [schemaOptions] - Optional Valibot validation options
* @param {Object} resolverOptions - Additional resolver configuration
* @param {('sync' | 'async')} [resolverOptions.mode] - Validation mode
* @param {boolean} [resolverOptions.raw] - If true, returns raw values rather than validated results
* @returns {Resolver<InferOutput<typeof schema>>} A resolver function compatible with react-hook-form
* @example
* const schema = valibot.object({
* name: valibot.string().minLength(2),
* age: valibot.number().min(18)
* });
*
* useForm({
* resolver: valibotResolver(schema)
* });
*/
export function valibotResolver<Input extends FieldValues, Context, Output>(
schema: BaseSchema<Input, Output, any> | BaseSchemaAsync<Input, Output, any>,
schemaOptions?: Partial<
Omit<Config<InferIssue<typeof schema>>, 'abortPipeEarly' | 'skipPipe'>
>,
resolverOptions: {
/**
* @default async
*/
mode?: 'sync' | 'async';
/**
* Return the raw input values rather than the parsed values.
* @default false
*/
raw?: boolean;
} = {},
): Resolver<Input, Context, Output | Input> {
return async (values: Input, _, options) => {
// Check if we should validate all field criteria
const validateAllFieldCriteria =
!options.shouldUseNativeValidation && options.criteriaMode === 'all';
// Parse values with Valibot schema
const result = await safeParseAsync(
schema,
values,
Object.assign({}, schemaOptions, {
abortPipeEarly: !validateAllFieldCriteria,
}),
);
// If there are issues, return them as errors
if (result.issues) {
// Create errors object
const errors: Record<string, FieldError> = {};
// Iterate over issues to add them to errors object
for (; result.issues.length; ) {
const issue = result.issues[0];
// Create dot path from issue
const path = getDotPath(issue);
if (path) {
// Add first error of path to errors object
if (!errors[path]) {
errors[path] = { message: issue.message, type: issue.type };
}
// If configured, add all errors of path to errors object
if (validateAllFieldCriteria) {
const types = errors[path].types;
const messages = types && types[issue.type];
errors[path] = appendErrors(
path,
validateAllFieldCriteria,
errors,
issue.type,
messages
? ([] as string[]).concat(
messages as string | string[],
issue.message,
)
: issue.message,
) as FieldError;
}
}
result.issues.shift();
}
// Return resolver result with errors
return {
values: {},
errors: toNestErrors(errors, options),
} as const;
}
// Otherwise, return resolver result with values
return {
values: resolverOptions.raw
? Object.assign({}, values)
: (result.output as FieldValues),
errors: {},
};
};
}