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/fluentvalidation-ts",
"amdName": "hookformResolversfluentvalidation-ts",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: fluentvalidation-ts",
"main": "dist/fluentvalidation-ts.js",
"module": "dist/fluentvalidation-ts.module.js",
"umd:main": "dist/fluentvalidation-ts.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.0.0",
"@hookform/resolvers": "^2.0.0",
"fluentvalidation-ts": "^3.0.0"
}
}

View File

@@ -0,0 +1,88 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { Validator } from 'fluentvalidation-ts';
import React from 'react';
import { useForm } from 'react-hook-form';
import { fluentValidationResolver } from '../fluentvalidation-ts';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
type FormData = {
username: string;
password: string;
};
class FormDataValidator extends Validator<FormData> {
constructor() {
super();
this.ruleFor('username').notEmpty().withMessage(USERNAME_REQUIRED_MESSAGE);
this.ruleFor('password').notEmpty().withMessage(PASSWORD_REQUIRED_MESSAGE);
}
}
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: fluentValidationResolver(new FormDataValidator()),
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 fluentvalidation-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,63 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { Validator } from 'fluentvalidation-ts';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { fluentValidationResolver } from '../fluentvalidation-ts';
type FormData = {
username: string;
password: string;
};
class FormDataValidator extends Validator<FormData> {
constructor() {
super();
this.ruleFor('username')
.notEmpty()
.withMessage('username is a required field');
this.ruleFor('password')
.notEmpty()
.withMessage('password is a required field');
}
}
interface Props {
onSubmit: SubmitHandler<FormData>;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm({
resolver: fluentValidationResolver(new FormDataValidator()), // 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 Yup 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 is a required field/i)).toBeInTheDocument();
expect(screen.getByText(/password is a required field/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View File

@@ -0,0 +1,121 @@
import { Validator } from 'fluentvalidation-ts';
import { Field, InternalFieldName } from 'react-hook-form';
const beNumeric = (value: string | number | undefined) => !isNaN(Number(value));
export type Schema = {
username: string;
password: string;
repeatPassword: string;
accessToken?: string;
birthYear?: number;
email?: string;
tags?: string[];
enabled?: boolean;
like?: {
id: number;
name: string;
}[];
};
export type SchemaWithWhen = {
name: string;
value: string;
};
export class SchemaValidator extends Validator<Schema> {
constructor() {
super();
this.ruleFor('username')
.notEmpty()
.matches(/^\w+$/)
.minLength(3)
.maxLength(30);
this.ruleFor('password')
.notEmpty()
.matches(/.*[A-Z].*/)
.withMessage('One uppercase character')
.matches(/.*[a-z].*/)
.withMessage('One lowercase character')
.matches(/.*\d.*/)
.withMessage('One number')
.matches(new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'))
.withMessage('One special character')
.minLength(8)
.withMessage('Must be at least 8 characters in length');
this.ruleFor('repeatPassword')
.notEmpty()
.must((repeatPassword, data) => repeatPassword === data.password);
this.ruleFor('accessToken');
this.ruleFor('birthYear')
.must(beNumeric)
.inclusiveBetween(1900, 2013)
.when((birthYear) => birthYear != undefined);
this.ruleFor('email').emailAddress();
this.ruleFor('tags');
this.ruleFor('enabled');
this.ruleForEach('like').setValidator(() => new LikeValidator());
}
}
export class LikeValidator extends Validator<{
id: number;
name: string;
}> {
constructor() {
super();
this.ruleFor('id').notNull();
this.ruleFor('name').notEmpty().length(4, 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',
},
],
} as Schema;
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
// Must be set to "unknown", otherwise typescript knows that it is invalid
} as unknown as Required<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,129 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`fluentValidationResolver > should return a single error from fluentValidationResolver when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "Value is not valid",
"ref": undefined,
"type": "validation",
},
"email": {
"message": "Not a valid email address",
"ref": {
"name": "email",
},
"type": "validation",
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "validation",
},
"repeatPassword": {
"message": "Value is not valid",
"ref": undefined,
"type": "validation",
},
},
"values": {},
}
`;
exports[`fluentValidationResolver > should return a single error from fluentValidationResolver with \`mode: sync\` when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "Value is not valid",
"ref": undefined,
"type": "validation",
},
"email": {
"message": "Not a valid email address",
"ref": {
"name": "email",
},
"type": "validation",
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "validation",
},
"repeatPassword": {
"message": "Value is not valid",
"ref": undefined,
"type": "validation",
},
},
"values": {},
}
`;
exports[`fluentValidationResolver > should return all the errors from fluentValidationResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"birthYear": {
"message": "Value is not valid",
"ref": undefined,
"type": "validation",
},
"email": {
"message": "Not a valid email address",
"ref": {
"name": "email",
},
"type": "validation",
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "validation",
},
"repeatPassword": {
"message": "Value is not valid",
"ref": undefined,
"type": "validation",
},
},
"values": {},
}
`;
exports[`fluentValidationResolver > should return all the errors from fluentValidationResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
{
"errors": {
"birthYear": {
"message": "Value is not valid",
"ref": undefined,
"type": "validation",
},
"email": {
"message": "Not a valid email address",
"ref": {
"name": "email",
},
"type": "validation",
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "validation",
},
"repeatPassword": {
"message": "Value is not valid",
"ref": undefined,
"type": "validation",
},
},
"values": {},
}
`;

View File

@@ -0,0 +1,113 @@
/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */
import { fluentValidationResolver } from '..';
import {
SchemaValidator,
fields,
invalidData,
validData,
} from './__fixtures__/data';
const shouldUseNativeValidation = false;
const validator = new SchemaValidator();
describe('fluentValidationResolver', () => {
it('should return values from fluentValidationResolver when validation pass', async () => {
const validatorSpy = vi.spyOn(validator, 'validate');
const result = await fluentValidationResolver(validator)(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(validatorSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return values from fluentValidationResolver with `mode: sync` when validation pass', async () => {
const validatorSpy = vi.spyOn(validator, 'validate');
const result = await fluentValidationResolver(validator)(
validData,
undefined,
{ fields, shouldUseNativeValidation },
);
expect(validatorSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from fluentValidationResolver when validation fails', async () => {
const result = await fluentValidationResolver(validator)(
invalidData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return a single error from fluentValidationResolver with `mode: sync` when validation fails', async () => {
const validateSpy = vi.spyOn(validator, 'validate');
const result = await fluentValidationResolver(validator)(
invalidData,
undefined,
{ fields, shouldUseNativeValidation },
);
expect(validateSpy).toHaveBeenCalledTimes(1);
expect(result).toMatchSnapshot();
});
it('should return all the errors from fluentValidationResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await fluentValidationResolver(validator)(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return all the errors from fluentValidationResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await fluentValidationResolver(validator)(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return values from fluentValidationResolver when validation pass & raw=true', async () => {
const schemaSpy = vi.spyOn(validator, 'validate');
const result = await fluentValidationResolver(validator)(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ errors: {}, values: validData });
});
});

View File

@@ -0,0 +1,102 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import {
AsyncValidator,
ValidationErrors,
Validator,
} from 'fluentvalidation-ts';
import { FieldError, FieldValues, Resolver } from 'react-hook-form';
function traverseObject<T>(
object: ValidationErrors<T>,
errors: Record<string, FieldError>,
parentIndices: (string | number)[] = [],
) {
for (const key in object) {
const currentIndex = [...parentIndices, key];
const currentValue = object[key];
if (Array.isArray(currentValue)) {
currentValue.forEach((item: any, index: number) => {
traverseObject(item, errors, [...currentIndex, index]);
});
} else if (typeof currentValue === 'object' && currentValue !== null) {
traverseObject(currentValue, errors, currentIndex);
} else if (typeof currentValue === 'string') {
errors[currentIndex.join('.')] = {
type: 'validation',
message: currentValue,
};
}
}
}
const parseErrorSchema = <T>(
validationErrors: ValidationErrors<T>,
validateAllFieldCriteria: boolean,
) => {
if (validateAllFieldCriteria) {
// TODO: check this but i think its always one validation error
}
const errors: Record<string, FieldError> = {};
traverseObject(validationErrors, errors);
return errors;
};
export function fluentValidationResolver<TFieldValues extends FieldValues>(
validator: Validator<TFieldValues>,
): Resolver<TFieldValues> {
return async (values, _context, options) => {
const validationResult = validator.validate(values);
const isValid = Object.keys(validationResult).length === 0;
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return isValid
? {
values: values,
errors: {},
}
: {
values: {},
errors: toNestErrors(
parseErrorSchema(
validationResult,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
};
}
export function fluentAsyncValidationResolver<
TFieldValues extends FieldValues,
TValidator extends AsyncValidator<TFieldValues>,
>(validator: TValidator): Resolver<TFieldValues> {
return async (values, _context, options) => {
const validationResult = await validator.validateAsync(values);
const isValid = Object.keys(validationResult).length === 0;
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return isValid
? {
values: values,
errors: {},
}
: {
values: {},
errors: toNestErrors(
parseErrorSchema(
validationResult,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
};
}

View File

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