Save current BZZZ config-ui state before CHORUS branding update

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
anthonyrawlins
2025-08-19 00:19:00 +10:00
parent 6a6a49b7b1
commit c177363a19
16410 changed files with 1789161 additions and 230 deletions

View File

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

View File

@@ -0,0 +1,88 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { Schema } from 'effect';
import React from 'react';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmptyString({ message: () => USERNAME_REQUIRED_MESSAGE }),
),
password: Schema.String.pipe(
Schema.nonEmptyString({ message: () => PASSWORD_REQUIRED_MESSAGE }),
),
});
interface FormData {
username: string;
password: string;
}
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: effectTsResolver(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 effect-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('');
});

View File

@@ -0,0 +1,59 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { Schema } from 'effect';
import React from 'react';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmptyString({ message: () => USERNAME_REQUIRED_MESSAGE }),
),
password: Schema.String.pipe(
Schema.nonEmptyString({ message: () => PASSWORD_REQUIRED_MESSAGE }),
),
});
type FormData = Schema.Schema.Type<typeof schema>;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: effectTsResolver(schema),
});
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 Zod 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();
});

View File

@@ -0,0 +1,124 @@
import { Schema } from 'effect';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmptyString({ message: () => 'A username is required' }),
),
password: Schema.String.pipe(
Schema.pattern(new RegExp('.*[A-Z].*'), {
message: () => 'At least 1 uppercase letter.',
}),
Schema.pattern(new RegExp('.*[a-z].*'), {
message: () => 'At least 1 lowercase letter.',
}),
Schema.pattern(new RegExp('.*\\d.*'), {
message: () => 'At least 1 number.',
}),
Schema.pattern(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
{
message: () => 'At least 1 special character.',
},
),
Schema.minLength(8, { message: () => 'Must be at least 8 characters.' }),
),
accessToken: Schema.Union(Schema.String, Schema.Number),
birthYear: Schema.Number.pipe(
Schema.greaterThan(1900, {
message: () => 'Must be greater than the year 1900',
}),
Schema.filter((value) => value < new Date().getFullYear(), {
message: () => 'Must be before the current year.',
}),
),
email: Schema.String.pipe(
Schema.pattern(
new RegExp(
/^(?!\.)(?!.*\.\.)([A-Z0-9_+-.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i,
),
{
message: () => 'A valid email address is required.',
},
),
),
tags: Schema.Array(
Schema.Struct({
name: Schema.String,
}),
),
luckyNumbers: Schema.Array(Schema.Number),
enabled: Schema.Boolean,
animal: Schema.Union(Schema.String, Schema.Literal('bird', 'snake')),
vehicles: Schema.Array(
Schema.Union(
Schema.Struct({
type: Schema.Literal('car'),
brand: Schema.String,
horsepower: Schema.Number,
}),
Schema.Struct({
type: Schema.Literal('bike'),
speed: Schema.Number,
}),
),
),
});
export const validData: Schema.Schema.Type<typeof schema> = {
accessToken: 'abcd1234',
animal: 'dog',
birthYear: 2000,
email: 'johnDoe@here.there',
enabled: true,
luckyNumbers: [1, 2, 3, 4, 5],
password: 'Super#Secret123',
tags: [{ name: 'move' }, { name: 'over' }, { name: 'zod' }, { name: ';)' }],
username: 'johnDoe',
vehicles: [
{ type: 'bike', speed: 5 },
{ type: 'car', brand: 'BMW', horsepower: 150 },
],
};
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' },
],
};
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,40 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`effectTsResolver > should return a single error from effectTsResolver when validation fails 1`] = `
{
"errors": {
"animal": {
"message": "Expected "snake", actual ["dog"]",
"ref": undefined,
"type": "Type",
},
"luckyNumbers": [
,
,
{
"message": "Expected number, actual "3"",
"ref": undefined,
"type": "Type",
},
],
"password": {
"message": "At least 1 special character.",
"ref": {
"name": "password",
},
"type": "Refinement",
},
"vehicles": [
,
{
"horsepower": {
"message": "is missing",
"ref": undefined,
"type": "Missing",
},
},
],
},
"values": {},
}
`;

View File

@@ -0,0 +1,24 @@
import { effectTsResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('effectTsResolver', () => {
it('should return values from effectTsResolver when validation pass', async () => {
const result = await effectTsResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from effectTsResolver when validation fails', async () => {
const result = await effectTsResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
});

View File

@@ -0,0 +1,40 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { Effect } from 'effect';
import { ArrayFormatter, decodeUnknown } from 'effect/ParseResult';
import type { FieldErrors } from 'react-hook-form';
import type { Resolver } from './types';
export const effectTsResolver: Resolver =
(schema, config = { errors: 'all', onExcessProperty: 'ignore' }) =>
(values, _, options) => {
return decodeUnknown(
schema,
config,
)(values).pipe(
Effect.catchAll((parseIssue) =>
Effect.flip(ArrayFormatter.formatIssue(parseIssue)),
),
Effect.mapError((issues) => {
const errors = issues.reduce((acc, current) => {
const key = current.path.join('.');
acc[key] = { message: current.message, type: current._tag };
return acc;
}, {} as FieldErrors);
return toNestErrors(errors, options);
}),
Effect.tap(() =>
Effect.sync(
() =>
options.shouldUseNativeValidation &&
validateFieldsNatively({}, options),
),
),
Effect.match({
onFailure: (errors) => ({ errors, values: {} }),
onSuccess: (result) => ({ errors: {}, values: result }),
}),
Effect.runPromise,
);
};

View File

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

View File

@@ -0,0 +1,12 @@
import { Schema } from 'effect';
import { ParseOptions } from 'effect/SchemaAST';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <A extends FieldValues, I, TContext>(
schema: Schema.Schema<A, I>,
config?: ParseOptions,
) => (
values: FieldValues,
_context: TContext | undefined,
options: ResolverOptions<A>,
) => Promise<ResolverResult<A>>;