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

View File

@@ -0,0 +1,85 @@
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 t from 'typanion';
import { typanionResolver } from '..';
const ERROR_MESSAGE =
'Expected to have a length of at least 1 elements (got 0)';
const schema = t.isObject({
username: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
password: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
});
interface FormData {
unusedProperty: string;
username: string;
password: string;
}
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: typanionResolver(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 Typanion", 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(ERROR_MESSAGE);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(ERROR_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,59 @@
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 t from 'typanion';
import { typanionResolver } from '..';
const schema = t.isObject({
username: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
password: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
});
interface FormData {
unusedProperty: string;
username: string;
password: string;
}
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<FormData>({
resolver: typanionResolver(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 Typanion 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.getAllByText(
'Expected to have a length of at least 1 elements (got 0)',
),
).toHaveLength(2);
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,82 @@
import { Field, InternalFieldName } from 'react-hook-form';
import * as t from 'typanion';
export const isSchema = t.isObject({
username: t.applyCascade(t.isString(), [
t.matchesRegExp(/^\w+$/),
t.hasMinLength(2),
t.hasMaxLength(30),
]),
password: t.applyCascade(t.isString(), [
t.matchesRegExp(new RegExp('.*[A-Z].*')), // one uppercase character
t.matchesRegExp(new RegExp('.*[a-z].*')), // one lowercase character
t.matchesRegExp(new RegExp('.*\\d.*')), // one number
t.matchesRegExp(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
), // one special character
t.hasMinLength(8), // Must be at least 8 characters in length
]),
repeatPassword: t.applyCascade(t.isString(), [
t.matchesRegExp(new RegExp('.*[A-Z].*')), // one uppercase character
t.matchesRegExp(new RegExp('.*[a-z].*')), // one lowercase character
t.matchesRegExp(new RegExp('.*\\d.*')), // one number
t.matchesRegExp(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
), // one special character
t.hasMinLength(8), // Must be at least 8 characters in length
]),
accessToken: t.isString(),
birthYear: t.applyCascade(t.isNumber(), [
t.isInteger(),
t.isInInclusiveRange(1900, 2013),
]),
email: t.applyCascade(t.isString(), [t.matchesRegExp(/^\S+@\S+$/)]),
tags: t.isArray(t.isString()),
enabled: t.isBoolean(),
like: t.isObject({
id: t.applyCascade(t.isNumber(), [t.isInteger(), t.isPositive()]),
name: t.applyCascade(t.isString(), [t.hasMinLength(4)]),
}),
});
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],
};
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,67 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`typanionResolver > should return a single error from typanionResolver when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "Expected a string (got undefined)",
"ref": undefined,
},
"birthYear": {
"message": "Expected a number (got "birthYear")",
"ref": undefined,
},
"email": {
"message": "Expected to match the pattern /^\\S+@\\S+$/ (got an empty string)",
"ref": {
"name": "email",
},
},
"enabled": {
"message": "Expected a boolean (got undefined)",
"ref": undefined,
},
"like": {
"id": {
"message": "Expected a number (got "z")",
"ref": undefined,
},
"name": {
"message": "Expected a string (got undefined)",
"ref": undefined,
},
},
"password": {
"message": "Expected to match the pattern /.*[A-Z].*/ (got "___")",
"ref": {
"name": "password",
},
},
"repeatPassword": {
"message": "Expected a string (got undefined)",
"ref": undefined,
},
"tags": [
{
"message": "Expected a string (got 1)",
"ref": undefined,
},
{
"message": "Expected a string (got 2)",
"ref": undefined,
},
{
"message": "Expected a string (got 3)",
"ref": undefined,
},
],
"username": {
"message": "Expected a string (got undefined)",
"ref": {
"name": "username",
},
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,35 @@
import { typanionResolver } from '..';
import { fields, invalidData, isSchema, validData } from './__fixtures__/data';
const tmpObj = {
validate: isSchema,
};
const shouldUseNativeValidation = false;
describe('typanionResolver', () => {
it('should return values from typanionResolver when validation pass', async () => {
const schemaSpy = vi.spyOn(tmpObj, 'validate');
const result = await typanionResolver(schemaSpy as any)(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from typanionResolver when validation fails', async () => {
const result = await typanionResolver(isSchema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
});

View File

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

View File

@@ -0,0 +1,44 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import type { FieldError, FieldErrors } from 'react-hook-form';
import type { Resolver } from './types';
const parseErrors = (errors: string[], parsedErrors: FieldErrors = {}) => {
return errors.reduce((acc, error) => {
const fieldIndex = error.indexOf(':');
const field = error.slice(1, fieldIndex);
const message = error.slice(fieldIndex + 1).trim();
acc[field] = {
message,
} as FieldError;
return acc;
}, parsedErrors);
};
export const typanionResolver: Resolver =
(validator, validatorOptions = {}) =>
(values, _, options) => {
const rawErrors: string[] = [];
const isValid = validator(
values,
Object.assign(
{},
{
errors: rawErrors,
},
validatorOptions,
),
);
const parsedErrors = parseErrors(rawErrors);
if (isValid) {
options.shouldUseNativeValidation &&
validateFieldsNatively(parsedErrors, options);
return { values, errors: {} };
}
return { values: {}, errors: toNestErrors(parsedErrors, options) };
};

20
node_modules/@hookform/resolvers/typanion/src/types.ts generated vendored Normal file
View File

@@ -0,0 +1,20 @@
import type {
FieldValues,
ResolverOptions,
ResolverResult,
} from 'react-hook-form';
import { AnyStrictValidator, ValidationState } from 'typanion';
type ValidateOptions = Pick<ValidationState, 'coercions' | 'coercion'>;
type RHFResolver = <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => ResolverResult<TFieldValues>;
export type Resolver = <UnknownValidator extends AnyStrictValidator>(
validator: UnknownValidator,
validatorOptions?: ValidateOptions,
resolverOptions?: { mode?: 'async' | 'sync'; rawValues?: boolean },
) => RHFResolver;