added apps

This commit is contained in:
2025-04-10 20:11:36 +03:00
parent 3613f9030e
commit c3b7556e7e
346 changed files with 265054 additions and 159 deletions

View File

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

View File

@@ -0,0 +1,82 @@
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 { Infer, object, size, string } from 'superstruct';
import { superstructResolver } from '..';
const schema = object({
username: size(string(), 2),
password: size(string(), 6),
});
type FormData = Infer<typeof schema>;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: superstructResolver(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 Superstruct", 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(
'Expected a string with a length of `2` but received one with a length of `0`',
);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
'Expected a string with a length of `6` but received one with a length of `0`',
);
await user.type(screen.getByPlaceholderText(/username/i), 'jo');
await user.type(screen.getByPlaceholderText(/password/i), 'passwo');
// 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,86 @@
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 { Infer, object, size, string } from 'superstruct';
import { superstructResolver } from '..';
const schema = object({
username: size(string(), 2),
password: size(string(), 6),
});
type FormData = Infer<typeof schema>;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<FormData>({
resolver: superstructResolver(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 Superstruct 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(
/Expected a string with a length of `2` but received one with a length of `0`/i,
),
).toBeInTheDocument();
expect(
screen.getByText(
/Expected a string with a length of `6` but received one with a length of `0`/i,
),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});
export function TestComponentManualType({
onSubmit,
}: {
onSubmit: (data: FormData) => void;
}) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<Infer<typeof schema>, undefined, FormData>({
resolver: superstructResolver(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,75 @@
import { Field, InternalFieldName } from 'react-hook-form';
import {
Infer,
array,
boolean,
define,
max,
min,
number,
object,
optional,
pattern,
size,
string,
union,
} from 'superstruct';
const Password = define(
'Password',
(value, ctx) => value === ctx.branch[0].password,
);
export const schema = object({
username: size(pattern(string(), /^\w+$/), 3, 30),
password: pattern(string(), /^[a-zA-Z0-9]{3,30}/),
repeatPassword: Password,
accessToken: optional(union([string(), number()])),
birthYear: optional(max(min(number(), 1900), 2013)),
email: optional(pattern(string(), /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)),
tags: array(string()),
enabled: boolean(),
like: optional(array(object({ id: number(), name: size(string(), 4) }))),
});
export const validData: Infer<typeof schema> = {
username: 'Doe',
password: 'Password123',
repeatPassword: 'Password123',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
like: [
{
id: 1,
name: 'name',
},
],
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
} as any as Infer<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,64 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`superstructResolver > should return a single error from superstructResolver when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "Expected a number, but received: "birthYear"",
"ref": undefined,
"type": "number",
},
"email": {
"message": "Expected a string matching \`/^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/\` but received """,
"ref": {
"name": "email",
},
"type": "string",
},
"enabled": {
"message": "Expected a value of type \`boolean\`, but received: \`undefined\`",
"ref": undefined,
"type": "boolean",
},
"like": [
{
"id": {
"message": "Expected a number, but received: "z"",
"ref": undefined,
"type": "number",
},
"name": {
"message": "Expected a string, but received: undefined",
"ref": undefined,
"type": "string",
},
},
],
"password": {
"message": "Expected a string matching \`/^[a-zA-Z0-9]{3,30}/\` but received "___"",
"ref": {
"name": "password",
},
"type": "string",
},
"repeatPassword": {
"message": "Expected a value of type \`Password\`, but received: \`undefined\`",
"ref": undefined,
"type": "Password",
},
"tags": {
"message": "Expected an array value, but received: undefined",
"ref": undefined,
"type": "array",
},
"username": {
"message": "Expected a string, but received: undefined",
"ref": {
"name": "username",
},
"type": "string",
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,97 @@
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
import * as s from 'superstruct';
import { superstructResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('superstructResolver', () => {
it('should return values from superstructResolver when validation pass', async () => {
const result = await superstructResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return values from superstructResolver with coerced values', async () => {
const result = await superstructResolver(
s.object({
id: s.coerce(s.number(), s.string(), (val) => String(val)),
}),
)({ id: 1 }, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: { id: '1' } });
});
it('should return a single error from superstructResolver when validation fails', async () => {
const result = await superstructResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should return values from superstructResolver when validation pass & raw=true', async () => {
const result = await superstructResolver(schema, undefined, { raw: true })(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(result).toEqual({ errors: {}, values: validData });
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a superstruct schema', () => {
const resolver = superstructResolver(s.object({ id: s.number() }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a superstruct schema for the handleSubmit function in useForm', () => {
const schema = s.object({ id: s.number() });
const form = useForm({
resolver: superstructResolver(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 superstruct schema with a transform for the handleSubmit function in useForm', () => {
const schema = s.object({
id: s.coerce(s.string(), s.number(), (val) => String(val)),
});
const form = useForm({
resolver: superstructResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<string>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: string;
}>
>();
});
});

View File

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

View File

@@ -0,0 +1,73 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { FieldError, FieldValues, Resolver } from 'react-hook-form';
import { Infer, Struct, StructError, validate } from 'superstruct';
function parseErrorSchema(error: StructError) {
return error.failures().reduce<Record<string, FieldError>>(
(previous, error) =>
(previous[error.path.join('.')] = {
message: error.message,
type: error.type,
}) && previous,
{},
);
}
export function superstructResolver<Input extends FieldValues, Context, Output>(
schema: Struct<Input, any>,
schemaOptions?: Parameters<typeof validate>[2],
resolverOptions?: {
raw?: false;
},
): Resolver<Input, Context, Infer<typeof schema>>;
export function superstructResolver<Input extends FieldValues, Context, Output>(
schema: Struct<Input, any>,
schemaOptions: Parameters<typeof validate>[2] | undefined,
resolverOptions: {
raw: true;
},
): Resolver<Input, Context, Input>;
/**
* Creates a resolver for react-hook-form using Superstruct schema validation
* @param {Struct<TFieldValues, any>} schema - The Superstruct schema to validate against
* @param {Parameters<typeof validate>[2]} [schemaOptions] - Optional Superstruct validation options
* @param {Object} resolverOptions - Additional resolver configuration
* @param {boolean} [resolverOptions.raw=false] - If true, returns raw values rather than validated results
* @returns {Resolver<Infer<typeof schema>>} A resolver function compatible with react-hook-form
* @example
* const schema = struct({
* name: string(),
* age: number()
* });
*
* useForm({
* resolver: superstructResolver(schema)
* });
*/
export function superstructResolver<Input extends FieldValues, Context, Output>(
schema: Struct<Input, any>,
schemaOptions?: Parameters<typeof validate>[2],
resolverOptions: {
raw?: boolean;
} = {},
): Resolver<Input, Context, Input | Output> {
return (values: Input, _, options) => {
const result = validate(values, schema, schemaOptions);
if (result[0]) {
return {
values: {},
errors: toNestErrors(parseErrorSchema(result[0]), options),
};
}
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
values: resolverOptions.raw ? Object.assign({}, values) : result[1],
errors: {},
};
};
}