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 './vine';

11
node_modules/@hookform/resolvers/vine/dist/vine.d.ts generated vendored Normal file
View file

@ -0,0 +1,11 @@
import { VineValidator } from '@vinejs/vine';
import { ConstructableSchema, ValidationOptions } from '@vinejs/vine/build/src/types';
import { FieldValues, Resolver } from 'react-hook-form';
export declare function vineResolver<Input extends FieldValues, Context, Output>(schema: VineValidator<ConstructableSchema<Input, Output, Output>, any>, schemaOptions?: ValidationOptions<any>, resolverOptions?: {
mode?: 'async' | 'sync';
raw?: false;
}): Resolver<Input, Context, Output>;
export declare function vineResolver<Input extends FieldValues, Context, Output>(schema: VineValidator<ConstructableSchema<Input, Output, Output>, any>, schemaOptions: ValidationOptions<any> | undefined, resolverOptions: {
mode?: 'async' | 'sync';
raw: true;
}): Resolver<Input, Context, Input>;

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

@ -0,0 +1,2 @@
var e=require("@hookform/resolvers"),r=require("@vinejs/vine"),t=require("react-hook-form");function s(e,r){for(var s={};e.length;){var o=e[0],i=o.field;if(i in s||(s[i]={message:o.message,type:o.rule}),r){var n=s[i].types,a=n&&n[o.rule];s[i]=t.appendErrors(i,r,s,o.rule,a?[].concat(a,[o.message]):o.message)}e.shift()}return s}exports.vineResolver=function(t,o,i){return void 0===i&&(i={}),function(n,a,u){try{return Promise.resolve(function(r,s){try{var a=Promise.resolve(t.validate(n,o)).then(function(r){return u.shouldUseNativeValidation&&e.validateFieldsNatively({},u),{errors:{},values:i.raw?Object.assign({},n):r}})}catch(e){return s(e)}return a&&a.then?a.then(void 0,s):a}(0,function(t){if(t instanceof r.errors.E_VALIDATION_ERROR)return{values:{},errors:e.toNestErrors(s(t.messages,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)};throw t}))}catch(e){return Promise.reject(e)}}};
//# sourceMappingURL=vine.js.map

File diff suppressed because one or more lines are too long

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

@ -0,0 +1,2 @@
import{validateFieldsNatively as e,toNestErrors as r}from"@hookform/resolvers";import{errors as t}from"@vinejs/vine";import{appendErrors as o}from"react-hook-form";function n(e,r){for(var t={};e.length;){var n=e[0],i=n.field;if(i in t||(t[i]={message:n.message,type:n.rule}),r){var s=t[i].types,a=s&&s[n.rule];t[i]=o(i,r,t,n.rule,a?[].concat(a,[n.message]):n.message)}e.shift()}return t}function i(o,i,s){return void 0===s&&(s={}),function(a,u,c){try{return Promise.resolve(function(r,t){try{var n=Promise.resolve(o.validate(a,i)).then(function(r){return c.shouldUseNativeValidation&&e({},c),{errors:{},values:s.raw?Object.assign({},a):r}})}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(0,function(e){if(e instanceof t.E_VALIDATION_ERROR)return{values:{},errors:r(n(e.messages,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw e}))}catch(e){return Promise.reject(e)}}}export{i as vineResolver};
//# sourceMappingURL=vine.module.js.map

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as e,toNestErrors as r}from"@hookform/resolvers";import{errors as s}from"@vinejs/vine";import{appendErrors as t}from"react-hook-form";function o(e,r){const s={};for(;e.length;){const o=e[0],a=o.field;if(a in s||(s[a]={message:o.message,type:o.rule}),r){const{types:e}=s[a],i=e&&e[o.rule];s[a]=t(a,r,s,o.rule,i?[...i,o.message]:o.message)}e.shift()}return s}function a(t,a,i={}){return async(n,l,c)=>{try{const r=await t.validate(n,a);return c.shouldUseNativeValidation&&e({},c),{errors:{},values:i.raw?Object.assign({},n):r}}catch(e){if(e instanceof s.E_VALIDATION_ERROR)return{values:{},errors:r(o(e.messages,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw e}}}export{a as vineResolver};
//# sourceMappingURL=vine.modern.mjs.map

View file

@ -0,0 +1 @@
{"version":3,"file":"vine.modern.mjs","sources":["../src/vine.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { SimpleErrorReporter, VineValidator, errors } from '@vinejs/vine';\nimport {\n ConstructableSchema,\n ValidationOptions,\n} from '@vinejs/vine/build/src/types';\nimport {\n FieldError,\n FieldErrors,\n FieldValues,\n Resolver,\n appendErrors,\n} from 'react-hook-form';\n\nfunction parseErrorSchema(\n vineErrors: SimpleErrorReporter['errors'],\n validateAllFieldCriteria: boolean,\n) {\n const schemaErrors: Record<string, FieldError> = {};\n\n for (; vineErrors.length; ) {\n const error = vineErrors[0];\n const path = error.field;\n\n if (!(path in schemaErrors)) {\n schemaErrors[path] = { message: error.message, type: error.rule };\n }\n\n if (validateAllFieldCriteria) {\n const { types } = schemaErrors[path];\n const messages = types && types[error.rule];\n\n schemaErrors[path] = appendErrors(\n path,\n validateAllFieldCriteria,\n schemaErrors,\n error.rule,\n messages ? [...(messages as string[]), error.message] : error.message,\n ) as FieldError;\n }\n\n vineErrors.shift();\n }\n\n return schemaErrors;\n}\n\nexport function vineResolver<Input extends FieldValues, Context, Output>(\n schema: VineValidator<ConstructableSchema<Input, Output, Output>, any>,\n schemaOptions?: ValidationOptions<any>,\n resolverOptions?: {\n mode?: 'async' | 'sync';\n raw?: false;\n },\n): Resolver<Input, Context, Output>;\n\nexport function vineResolver<Input extends FieldValues, Context, Output>(\n schema: VineValidator<ConstructableSchema<Input, Output, Output>, any>,\n schemaOptions: ValidationOptions<any> | undefined,\n resolverOptions: {\n mode?: 'async' | 'sync';\n raw: true;\n },\n): Resolver<Input, Context, Input>;\n\n/**\n * Creates a resolver for react-hook-form using VineJS schema validation\n * @param {T} schema - The VineJS schema to validate against\n * @param {ValidationOptions<any>} [schemaOptions] - Optional VineJS validation options\n * @param {Object} [resolverOptions] - Optional resolver configuration\n * @param {boolean} [resolverOptions.raw=false] - If true, returns raw values instead of validated results\n * @returns {Resolver<Infer<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = vine.compile(\n * vine.object({\n * name: vine.string().minLength(2),\n * age: vine.number().min(18)\n * })\n * );\n *\n * useForm({\n * resolver: vineResolver(schema)\n * });\n */\nexport function vineResolver<Input extends FieldValues, Context, Output>(\n schema: VineValidator<ConstructableSchema<Input, Output, Output>, any>,\n schemaOptions?: ValidationOptions<any>,\n resolverOptions: { raw?: boolean } = {},\n): Resolver<Input, Context, Output | Input> {\n return async (values, _, options) => {\n try {\n const data = await schema.validate(values, schemaOptions);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {} as FieldErrors,\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n };\n } catch (error: any) {\n if (error instanceof errors.E_VALIDATION_ERROR) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n error.messages,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["parseErrorSchema","vineErrors","validateAllFieldCriteria","schemaErrors","length","error","path","field","message","type","rule","types","messages","appendErrors","shift","vineResolver","schema","schemaOptions","resolverOptions","values","_","options","data","validate","shouldUseNativeValidation","validateFieldsNatively","errors","raw","Object","assign","E_VALIDATION_ERROR","toNestErrors","criteriaMode"],"mappings":"oKAcA,SAASA,EACPC,EACAC,GAEA,MAAMC,EAA2C,CAAA,EAEjD,KAAOF,EAAWG,QAAU,CAC1B,MAAMC,EAAQJ,EAAW,GACnBK,EAAOD,EAAME,MAMnB,GAJMD,KAAQH,IACZA,EAAaG,GAAQ,CAAEE,QAASH,EAAMG,QAASC,KAAMJ,EAAMK,OAGzDR,EAA0B,CAC5B,MAAMS,MAAEA,GAAUR,EAAaG,GACzBM,EAAWD,GAASA,EAAMN,EAAMK,MAEtCP,EAAaG,GAAQO,EACnBP,EACAJ,EACAC,EACAE,EAAMK,KACNE,EAAW,IAAKA,EAAuBP,EAAMG,SAAWH,EAAMG,QAElE,CAEAP,EAAWa,OACb,CAEA,OAAOX,CACT,CAuCM,SAAUY,EACdC,EACAC,EACAC,EAAqC,CAAA,GAErC,OAAcC,MAAAA,EAAQC,EAAGC,KACvB,IACE,MAAMC,QAAaN,EAAOO,SAASJ,EAAQF,GAI3C,OAFAI,EAAQG,2BAA6BC,EAAuB,CAAA,EAAIJ,GAEzD,CACLK,OAAQ,CAAiB,EACzBP,OAAQD,EAAgBS,IAAMC,OAAOC,OAAO,CAAA,EAAIV,GAAUG,EAE9D,CAAE,MAAOjB,GACP,GAAIA,aAAiBqB,EAAOI,mBAC1B,MAAO,CACLX,OAAQ,CAAA,EACRO,OAAQK,EACN/B,EACEK,EAAMO,UACLS,EAAQG,2BACkB,QAAzBH,EAAQW,cAEZX,IAKN,MAAMhB,CACR,EAEJ"}

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as e,toNestErrors as r}from"@hookform/resolvers";import{errors as t}from"@vinejs/vine";import{appendErrors as o}from"react-hook-form";function n(e,r){for(var t={};e.length;){var n=e[0],i=n.field;if(i in t||(t[i]={message:n.message,type:n.rule}),r){var s=t[i].types,a=s&&s[n.rule];t[i]=o(i,r,t,n.rule,a?[].concat(a,[n.message]):n.message)}e.shift()}return t}function i(o,i,s){return void 0===s&&(s={}),function(a,u,c){try{return Promise.resolve(function(r,t){try{var n=Promise.resolve(o.validate(a,i)).then(function(r){return c.shouldUseNativeValidation&&e({},c),{errors:{},values:s.raw?Object.assign({},a):r}})}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}(0,function(e){if(e instanceof t.E_VALIDATION_ERROR)return{values:{},errors:r(n(e.messages,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw e}))}catch(e){return Promise.reject(e)}}}export{i as vineResolver};
//# sourceMappingURL=vine.module.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("@vinejs/vine"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","@vinejs/vine","react-hook-form"],r):r((e||self).hookformResolversVine={},e.hookformResolvers,e.vine,e.ReactHookForm)}(this,function(e,r,o,t){function n(e,r){for(var o={};e.length;){var n=e[0],s=n.field;if(s in o||(o[s]={message:n.message,type:n.rule}),r){var i=o[s].types,a=i&&i[n.rule];o[s]=t.appendErrors(s,r,o,n.rule,a?[].concat(a,[n.message]):n.message)}e.shift()}return o}e.vineResolver=function(e,t,s){return void 0===s&&(s={}),function(i,a,f){try{return Promise.resolve(function(o,n){try{var a=Promise.resolve(e.validate(i,t)).then(function(e){return f.shouldUseNativeValidation&&r.validateFieldsNatively({},f),{errors:{},values:s.raw?Object.assign({},i):e}})}catch(e){return n(e)}return a&&a.then?a.then(void 0,n):a}(0,function(e){if(e instanceof o.errors.E_VALIDATION_ERROR)return{values:{},errors:r.toNestErrors(n(e.messages,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)};throw e}))}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=vine.umd.js.map

File diff suppressed because one or more lines are too long

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

@ -0,0 +1,18 @@
{
"name": "@hookform/resolvers/vine",
"amdName": "hookformResolversVine",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: vine",
"main": "dist/vine.js",
"module": "dist/vine.module.js",
"umd:main": "dist/vine.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",
"@vinejs/vine": "^2.0.0"
}
}

View file

@ -0,0 +1,83 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import vine from '@vinejs/vine';
import { Infer } from '@vinejs/vine/build/src/types';
import React from 'react';
import { useForm } from 'react-hook-form';
import { vineResolver } from '..';
const schema = vine.compile(
vine.object({
username: vine.string().minLength(1),
password: vine.string().minLength(1),
}),
);
interface Props {
onSubmit: (data: Infer<typeof schema>) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm({
resolver: vineResolver(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(
'The username field must have at least 1 characters',
);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
'The password field must have at least 1 characters',
);
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,55 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import vine from '@vinejs/vine';
import { Infer } from '@vinejs/vine/build/src/types';
import React from 'react';
import { useForm } from 'react-hook-form';
import { vineResolver } from '..';
const schema = vine.compile(
vine.object({
username: vine.string().minLength(1),
password: vine.string().minLength(1),
}),
);
function TestComponent({
onSubmit,
}: { onSubmit: (data: Infer<typeof schema>) => void }) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: vineResolver(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 Vine 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(/The username field must have at least 1 characters/i),
).toBeInTheDocument();
expect(
screen.getByText(/The password field must have at least 1 characters/i),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View file

@ -0,0 +1,76 @@
import vine from '@vinejs/vine';
import { InferInput } from '@vinejs/vine/build/src/types';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = vine.compile(
vine.object({
username: vine.string().regex(/^\w+$/).minLength(3).maxLength(30),
password: vine
.string()
.regex(new RegExp('.*[A-Z].*'))
.regex(new RegExp('.*[a-z].*'))
.regex(new RegExp('.*\\d.*'))
.regex(new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'))
.minLength(8)
.confirmed({ confirmationField: 'repeatPassword' }),
repeatPassword: vine.string().sameAs('password'),
accessToken: vine.unionOfTypes([vine.string(), vine.number()]),
birthYear: vine.number().min(1900).max(2013),
email: vine.string().email().optional(),
tags: vine.array(vine.string()),
enabled: vine.boolean(),
like: vine.array(
vine.object({
id: vine.number(),
name: vine.string().fixedLength(4),
}),
),
dateStr: vine
.string()
.transform((value: string) => new Date(value).toISOString()),
}),
);
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',
},
],
dateStr: '2020-01-01T00:00:00.000Z',
} satisfies InferInput<typeof schema>;
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
} as unknown as InferInput<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,180 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`vineResolver > should return a single error from vineResolver when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "Invalid value provided for accessToken field",
"ref": undefined,
"type": "unionOfTypes",
},
"birthYear": {
"message": "The birthYear field must be a number",
"ref": undefined,
"type": "number",
},
"dateStr": {
"message": "The dateStr field must be defined",
"ref": undefined,
"type": "required",
},
"email": {
"message": "The email field must be a valid email address",
"ref": {
"name": "email",
},
"type": "email",
},
"enabled": {
"message": "The enabled field must be defined",
"ref": undefined,
"type": "required",
},
"like": [
{
"id": {
"message": "The id field must be a number",
"ref": undefined,
"type": "number",
},
"name": {
"message": "The name field must be defined",
"ref": undefined,
"type": "required",
},
},
],
"password": {
"message": "The password field format is invalid",
"ref": {
"name": "password",
},
"type": "regex",
},
"repeatPassword": {
"message": "The repeatPassword field must be defined",
"ref": undefined,
"type": "required",
},
"tags": {
"message": "The tags field must be defined",
"ref": undefined,
"type": "required",
},
"username": {
"message": "The username field must be defined",
"ref": {
"name": "username",
},
"type": "required",
},
},
"values": {},
}
`;
exports[`vineResolver > should return all the errors from vineResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"accessToken": {
"message": "Invalid value provided for accessToken field",
"ref": undefined,
"type": "unionOfTypes",
"types": {
"unionOfTypes": "Invalid value provided for accessToken field",
},
},
"birthYear": {
"message": "The birthYear field must be a number",
"ref": undefined,
"type": "number",
"types": {
"number": "The birthYear field must be a number",
},
},
"dateStr": {
"message": "The dateStr field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The dateStr field must be defined",
},
},
"email": {
"message": "The email field must be a valid email address",
"ref": {
"name": "email",
},
"type": "email",
"types": {
"email": "The email field must be a valid email address",
},
},
"enabled": {
"message": "The enabled field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The enabled field must be defined",
},
},
"like": [
{
"id": {
"message": "The id field must be a number",
"ref": undefined,
"type": "number",
"types": {
"number": "The id field must be a number",
},
},
"name": {
"message": "The name field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The name field must be defined",
},
},
},
],
"password": {
"message": "The password field format is invalid",
"ref": {
"name": "password",
},
"type": "regex",
"types": {
"regex": "The password field format is invalid",
},
},
"repeatPassword": {
"message": "The repeatPassword field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The repeatPassword field must be defined",
},
},
"tags": {
"message": "The tags field must be defined",
"ref": undefined,
"type": "required",
"types": {
"required": "The tags field must be defined",
},
},
"username": {
"message": "The username field must be defined",
"ref": {
"name": "username",
},
"type": "required",
"types": {
"required": "The username field must be defined",
},
},
},
"values": {},
}
`;

View file

@ -0,0 +1,122 @@
import vine from '@vinejs/vine';
import { Resolver, useForm } from 'react-hook-form';
import { SubmitHandler } from 'react-hook-form';
import { vineResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('vineResolver', () => {
it('should return values from vineResolver when validation pass', async () => {
const schemaSpy = vi.spyOn(schema, 'validate');
const result = await vineResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from vineResolver when validation fails', async () => {
const result = await vineResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return all the errors from vineResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await vineResolver(schema)(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return values from vineResolver when validation pass & raw=true', async () => {
const schemaSpy = vi.spyOn(schema, 'validate');
const result = await vineResolver(schema, undefined, { raw: true })(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a vine schema', () => {
const resolver = vineResolver(
vine.compile(vine.object({ id: vine.number() })),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number | string }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a vine schema using a transform', () => {
const resolver = vineResolver(
vine.compile(
vine.object({
id: vine
.number()
.decimal([2, 4])
.transform<string>((val: unknown) => String(val)),
}),
),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number | string }, unknown, { id: string }>
>();
});
it('should correctly infer the output type from a vine schema for the handleSubmit function in useForm', () => {
const schema = vine.compile(vine.object({ id: vine.number() }));
const form = useForm({
resolver: vineResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number | string>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: number;
}>
>();
});
it('should correctly infer the output type from a vine schema with a transform for the handleSubmit function in useForm', () => {
const schema = vine.compile(
vine.object({
id: vine.number().transform<string>((val: unknown) => String(val)),
}),
);
const form = useForm({
resolver: vineResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<string | number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: string;
}>
>();
});
});

1
node_modules/@hookform/resolvers/vine/src/index.ts generated vendored Normal file
View file

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

118
node_modules/@hookform/resolvers/vine/src/vine.ts generated vendored Normal file
View file

@ -0,0 +1,118 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { SimpleErrorReporter, VineValidator, errors } from '@vinejs/vine';
import {
ConstructableSchema,
ValidationOptions,
} from '@vinejs/vine/build/src/types';
import {
FieldError,
FieldErrors,
FieldValues,
Resolver,
appendErrors,
} from 'react-hook-form';
function parseErrorSchema(
vineErrors: SimpleErrorReporter['errors'],
validateAllFieldCriteria: boolean,
) {
const schemaErrors: Record<string, FieldError> = {};
for (; vineErrors.length; ) {
const error = vineErrors[0];
const path = error.field;
if (!(path in schemaErrors)) {
schemaErrors[path] = { message: error.message, type: error.rule };
}
if (validateAllFieldCriteria) {
const { types } = schemaErrors[path];
const messages = types && types[error.rule];
schemaErrors[path] = appendErrors(
path,
validateAllFieldCriteria,
schemaErrors,
error.rule,
messages ? [...(messages as string[]), error.message] : error.message,
) as FieldError;
}
vineErrors.shift();
}
return schemaErrors;
}
export function vineResolver<Input extends FieldValues, Context, Output>(
schema: VineValidator<ConstructableSchema<Input, Output, Output>, any>,
schemaOptions?: ValidationOptions<any>,
resolverOptions?: {
mode?: 'async' | 'sync';
raw?: false;
},
): Resolver<Input, Context, Output>;
export function vineResolver<Input extends FieldValues, Context, Output>(
schema: VineValidator<ConstructableSchema<Input, Output, Output>, any>,
schemaOptions: ValidationOptions<any> | undefined,
resolverOptions: {
mode?: 'async' | 'sync';
raw: true;
},
): Resolver<Input, Context, Input>;
/**
* Creates a resolver for react-hook-form using VineJS schema validation
* @param {T} schema - The VineJS schema to validate against
* @param {ValidationOptions<any>} [schemaOptions] - Optional VineJS validation options
* @param {Object} [resolverOptions] - Optional resolver configuration
* @param {boolean} [resolverOptions.raw=false] - If true, returns raw values instead of validated results
* @returns {Resolver<Infer<typeof schema>>} A resolver function compatible with react-hook-form
* @example
* const schema = vine.compile(
* vine.object({
* name: vine.string().minLength(2),
* age: vine.number().min(18)
* })
* );
*
* useForm({
* resolver: vineResolver(schema)
* });
*/
export function vineResolver<Input extends FieldValues, Context, Output>(
schema: VineValidator<ConstructableSchema<Input, Output, Output>, any>,
schemaOptions?: ValidationOptions<any>,
resolverOptions: { raw?: boolean } = {},
): Resolver<Input, Context, Output | Input> {
return async (values, _, options) => {
try {
const data = await schema.validate(values, schemaOptions);
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
errors: {} as FieldErrors,
values: resolverOptions.raw ? Object.assign({}, values) : data,
};
} catch (error: any) {
if (error instanceof errors.E_VALIDATION_ERROR) {
return {
values: {},
errors: toNestErrors(
parseErrorSchema(
error.messages,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
}
throw error;
}
};
}