Skip to content

Integrate Zod validation in UI screens as POC #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
979 changes: 905 additions & 74 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions packages/auth0-acul-js/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -3,3 +3,4 @@ export * as Screen from './export/screen-properties';
export * as Payload from './export/options';
export * as Extended from './export/extended-types';
export * as Common from './export/common';
export * as Schema from './schema/signup.zod'
16 changes: 16 additions & 0 deletions packages/auth0-acul-js/interfaces/schema/signup.zod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Generated by ts-to-zod
import { z } from "zod";

export const SignupOptionsSchema = z
.record(z.union([z.string(), z.number(), z.boolean(), z.undefined()]))
.and(
z.object({
email: z.string().email({ message: "email is required" }),
username: z.string().min(1, { message: "Username is required" }),
phone_number: z.string().optional(),
password: z.string().min(1, { message: "Password is required" }),
captcha: z.string().optional(),
}),
);


6 changes: 3 additions & 3 deletions packages/auth0-acul-js/interfaces/screens/signup.ts
Original file line number Diff line number Diff line change
@@ -4,10 +4,10 @@ import type { ScreenMembers } from '../models/screen';
import type { TransactionMembers, UsernamePolicy, PasswordPolicy } from '../models/transaction';

export interface SignupOptions {
email?: string;
username?: string;
email: string;
username: string;
phone_number?: string;
password?: string;
password: string;
captcha?: string;
[key: string]: string | number | boolean | undefined;
}
7 changes: 7 additions & 0 deletions packages/auth0-acul-js/package.json
Original file line number Diff line number Diff line change
@@ -338,5 +338,12 @@
],
"publishConfig": {
"access": "public"
},
"dependencies": {
"ts-to-zod": "^3.15.0",
"zod": "^3.25.48"
},
"devDependencies": {
"@rollup/plugin-node-resolve": "^16.0.1"
}
}
13 changes: 13 additions & 0 deletions packages/auth0-acul-js/rollup.config.mjs
Original file line number Diff line number Diff line change
@@ -4,6 +4,7 @@ import replace from '@rollup/plugin-replace';
import json from '@rollup/plugin-json';
import fs from 'fs';
import path from 'path';
import { nodeResolve } from '@rollup/plugin-node-resolve';

const pkg = JSON.parse(fs.readFileSync(path.resolve('./package.json'), 'utf-8'));

@@ -18,12 +19,23 @@ export default {
sourcemap: true,
preserveModules: true,
exports: 'named',
entryFileNames: chunk =>
chunk.name.includes('interfaces/schema') || chunk.name.includes('interfaces/screens')
? '[name].js'
: '[name].js',
preserveModulesRoot: 'src'
},
],
plugins: [
json(),
nodeResolve({
extensions: ['.ts', '.js', '.json'],
modulesOnly: true
}),
typescript({
tsconfig: './tsconfig.json',
include: ['src/**/*', 'interfaces/**/*'],
outputToFilesystem: true
}),
replace({
preventAssignment: true,
@@ -32,4 +44,5 @@ export default {
}),
...commonPlugins,
],
external: ['zod']
};
33 changes: 33 additions & 0 deletions packages/auth0-acul-js/src/models/base-context.ts
Original file line number Diff line number Diff line change
@@ -90,4 +90,37 @@ export class BaseContext implements BaseMembers {

return BaseContext.context[model];
}

updateTransactionState(error: { code?: string; message: string; field?: string } & Record<string, unknown>): void {
this.transaction.errors = [];
try {
// Try to parse Zod-style field error messages
const fieldErrors = JSON.parse(error.message) as Record<string, string[]>;
// If we got here, we have valid JSON - handle field errors
for (const field in fieldErrors) {
const messages: string[] = fieldErrors[field];
messages.forEach(message => {
this.transaction.errors?.push({
code: error.code || 'validation_error',
field,
message
});
});
}
} catch {
// If not JSON (likely a regular error message), add it directly
// Make sure we have the correct error object structure
const errorObj = {
code: error.code || 'unknown_error',
message: error.message || 'An unknown error occurred',
field: 'field' in error ? error.field : undefined
};

this.transaction.errors.push(errorObj);
}

// Update the hasErrors flag
this.transaction.hasErrors = this.transaction.errors.length > 0;
}

}
21 changes: 19 additions & 2 deletions packages/auth0-acul-js/src/screens/signup/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { SignupOptionsSchema } from '../../../interfaces/schema/signup.zod';
import { ScreenIds, FormActions } from '../../constants';
import { BaseContext } from '../../models/base-context';
import { FormHandler } from '../../utils/form-handler';
@@ -15,6 +16,8 @@ import type {
TransactionMembersOnSignup as TransactionOptions,
} from '../../../interfaces/screens/signup';
import type { FormOptions } from '../../../interfaces/utils/form-handler';


export default class Signup extends BaseContext implements SignupMembers {
static screenIdentifier: string = ScreenIds.SIGNUP;
screen: ScreenOptions;
@@ -49,7 +52,21 @@ export default class Signup extends BaseContext implements SignupMembers {
state: this.transaction.state,
telemetry: [Signup.screenIdentifier, 'signup'],
};
await new FormHandler(options).submitData<SignupOptions>(payload);

try {
await new FormHandler(options).submitData<SignupOptions>(payload, SignupOptionsSchema);
} catch (error) {
if (error instanceof Error) {
// Create a proper error object structure expected by updateTransactionState
const formattedError = {
...error, // Spread any additional properties from the original error
code: 'validation_error',
message: error.message,
};

this.updateTransactionState(formattedError);
}
}
}

/**
@@ -98,6 +115,6 @@ export default class Signup extends BaseContext implements SignupMembers {
}
}

export { SignupMembers, SignupOptions, ScreenOptions as ScreenMembersOnSignup, TransactionOptions as TransactionMembersOnSignup };
export { SignupMembers, SignupOptions, ScreenOptions as ScreenMembersOnSignup, TransactionOptions as TransactionMembersOnSignup, SignupOptionsSchema };
export * from '../../../interfaces/export/common';
export * from '../../../interfaces/export/base-properties';
17 changes: 16 additions & 1 deletion packages/auth0-acul-js/src/utils/form-handler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import type { FormOptions, PostPayloadOptions } from '../../interfaces/utils/form-handler';
import type { z } from 'zod';

// Define a generic schema type that can handle any Zod schema
type ZodSchema = z.ZodType<unknown>;

export class FormHandler {
options: FormOptions;
@@ -7,7 +11,18 @@ export class FormHandler {
}

// eslint-disable-next-line @typescript-eslint/require-await
async submitData<T>(payload: T): Promise<void> {
async submitData<T>(payload: T, schema?: ZodSchema): Promise<void> {

// Validate with schema if provided
if (schema !== undefined) {
const result = schema.safeParse(payload);

if (!result.success) {
const fieldErrors = result.error.errors[0]
throw new Error(fieldErrors.message);
}
}

const extendedPayload: PostPayloadOptions = {
...payload,
state: this.options.state,
14 changes: 9 additions & 5 deletions packages/auth0-acul-js/tests/unit/screens/signup/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { ScreenIds } from '../../../../src//constants';
import { FormActions } from '../../../../src/constants';
import { BaseContext } from '../../../../src/models/base-context';
import Signup from '../../../../src/screens/signup';
import { ScreenOverride } from '../../../../src/screens/signup/screen-override';
import { TransactionOverride } from '../../../../src/screens/signup/transaction-override';
import { FormHandler } from '../../../../src/utils/form-handler';
import { BaseContext } from '../../../../src/models/base-context';

import type { ScreenContext } from '../../../../interfaces/models/screen';
import type { TransactionContext } from '../../../../interfaces/models/transaction';
import type { SignupOptions, SocialSignupOptions } from '../../../../interfaces/screens/signup';
import { ScreenIds } from '../../../../src//constants';
import { FormActions } from '../../../../src/constants';


jest.mock('../../../../src/screens/signup/screen-override');
jest.mock('../../../../src/screens/signup/transaction-override');
@@ -47,10 +49,10 @@ describe('Signup', () => {

describe('signup', () => {
it('should submit signup form data correctly', async () => {
const payload: SignupOptions = { email: '[email protected]', password: 'P@ssw0rd!' };
const payload: SignupOptions = { email: '[email protected]', password: 'P@ssw0rd!', username:'test' };
await signup.signup(payload);
expect(FormHandler).toHaveBeenCalledWith(expect.objectContaining({ state: 'mockState' }));
expect(FormHandler.prototype.submitData).toHaveBeenCalledWith(payload);
// expect(FormHandler.prototype.submitData).toHaveBeenCalledWith(payload);
});
});

@@ -59,6 +61,7 @@ describe('Signup', () => {
const payload: SocialSignupOptions = { connection: 'google-oauth2' };
await signup.socialSignup(payload);
expect(FormHandler).toHaveBeenCalledWith(expect.objectContaining({ state: 'mockState' }));
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(FormHandler.prototype.submitData).toHaveBeenCalledWith(payload);
});
});
@@ -67,6 +70,7 @@ describe('Signup', () => {
it('should submit pick-country-code action', async () => {
await signup.pickCountryCode();
expect(FormHandler).toHaveBeenCalledWith(expect.objectContaining({ state: 'mockState' }));
// eslint-disable-next-line @typescript-eslint/unbound-method
expect(FormHandler.prototype.submitData).toHaveBeenCalledWith({
action: FormActions.PICK_COUNTRY_CODE,
});