The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): extract shared zod number input helpers (#50102)
Danny White4a5db160be9e
diff --git a/apps/studio/components/interfaces/Auth/AuthProvidersFormValidation.tsx b/apps/studio/components/interfaces/Auth/AuthProvidersFormValidation.tsxindex c2e44a7f672..8622512cc6e 100644--- a/apps/studio/components/interfaces/Auth/AuthProvidersFormValidation.tsx+++ b/apps/studio/components/interfaces/Auth/AuthProvidersFormValidation.tsx@@ -3,6 +3,7 @@ import * as z from 'zod'import { NO_REQUIRED_CHARACTERS, urlRegex } from '@/components/interfaces/Auth/Auth.constants'import { ProjectAuthConfigData } from '@/data/auth/auth-config-query'import { DOCS_URL } from '@/lib/constants'+import { preprocessEmptyNumberInput } from '@/lib/forms/zod-number-input'const parseBase64URL = (b64url: string) => {return atob(b64url.replace(/[-]/g, '+').replace(/[_]/g, '/'))@@ -96,22 +97,19 @@ const PROVIDER_EMAIL = {SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION: z.boolean(),SECURITY_UPDATE_PASSWORD_REQUIRE_CURRENT_PASSWORD: z.boolean(),PASSWORD_HIBP_ENABLED: z.boolean(),- MAILER_OTP_EXP: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ MAILER_OTP_EXP: preprocessEmptyNumberInput(z.coerce.number({ required_error: 'This is required', invalid_type_error: 'This is required' }).min(0, 'Must be greater or equal to 0').max(86400, 'Must be no more than 86400')),- MAILER_OTP_LENGTH: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ MAILER_OTP_LENGTH: preprocessEmptyNumberInput(z.coerce.number({ required_error: 'This is required', invalid_type_error: 'This is required' }).min(6, 'Must be greater or equal to 6').max(10, 'Must be no more than 10')),- PASSWORD_MIN_LENGTH: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ PASSWORD_MIN_LENGTH: preprocessEmptyNumberInput(z.coerce.number({ required_error: 'This is required', invalid_type_error: 'This is required' }).min(6, 'Must be greater or equal to 6')@@ -124,18 +122,9 @@ const PROVIDER_EMAIL = {SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION: z.boolean().optional(),PASSWORD_HIBP_ENABLED: z.boolean().optional(),SECURITY_UPDATE_PASSWORD_REQUIRE_CURRENT_PASSWORD: z.boolean().optional(),- MAILER_OTP_EXP: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),- z.coerce.number().optional()- ),- MAILER_OTP_LENGTH: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),- z.coerce.number().optional()- ),- PASSWORD_MIN_LENGTH: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),- z.coerce.number().optional()- ),+ MAILER_OTP_EXP: preprocessEmptyNumberInput(z.coerce.number().optional()),+ MAILER_OTP_LENGTH: preprocessEmptyNumberInput(z.coerce.number().optional()),+ PASSWORD_MIN_LENGTH: preprocessEmptyNumberInput(z.coerce.number().optional()),PASSWORD_REQUIRED_CHARACTERS: z.string().optional(),}),]),@@ -169,14 +158,12 @@ const smsProviderBaseSchema = z.object({const getSmsOtpPhoneProviderSchema = (optional = false) =>z.object({- SMS_OTP_EXP: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ SMS_OTP_EXP: preprocessEmptyNumberInput(z.coerce.number({ required_error: 'This is required', invalid_type_error: 'This is required' }).min(0, 'Must be 0 or larger')),- SMS_OTP_LENGTH: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ SMS_OTP_LENGTH: preprocessEmptyNumberInput(z.coerce.number({ required_error: 'This is required', invalid_type_error: 'This is required' }).min(6, 'Must be 6 or larger')diff --git a/apps/studio/components/interfaces/Auth/MfaAuthSettingsForm/MfaAuthSettingsForm.tsx b/apps/studio/components/interfaces/Auth/MfaAuthSettingsForm/MfaAuthSettingsForm.tsxindex 6b052ea6d88..c4cf9697141 100644--- a/apps/studio/components/interfaces/Auth/MfaAuthSettingsForm/MfaAuthSettingsForm.tsx+++ b/apps/studio/components/interfaces/Auth/MfaAuthSettingsForm/MfaAuthSettingsForm.tsx@@ -48,6 +48,7 @@ import { useAuthConfigUpdateMutation } from '@/data/auth/auth-config-update-mutaimport { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { IS_PLATFORM } from '@/lib/constants'+import { preprocessEmptyNumberInput } from '@/lib/forms/zod-number-input'function determineMFAStatus(verifyEnabled: boolean, enrollEnabled: boolean) {return verifyEnabled ? (enrollEnabled ? 'Enabled' : 'Verify Enabled') : 'Disabled'@@ -78,8 +79,7 @@ const MfaStatusToState = (status: (typeof MFAFactorSelectionOptions)[number]['vaconst totpSchema = z.object({MFA_TOTP: z.string().min(1, 'Required'),- MFA_MAX_ENROLLED_FACTORS: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ MFA_MAX_ENROLLED_FACTORS: preprocessEmptyNumberInput(z.coerce.number({ required_error: 'Required', invalid_type_error: 'Required' }).min(0, 'Must be a value 0 or larger')@@ -91,8 +91,7 @@ type TotpFormValues = z.infer<typeof totpSchema>const phoneSchema = z.object({MFA_PHONE: z.string().min(1, 'Required'),- MFA_PHONE_OTP_LENGTH: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ MFA_PHONE_OTP_LENGTH: preprocessEmptyNumberInput(z.coerce.number({ required_error: 'Required', invalid_type_error: 'Required' }).min(6, 'Must be a value 6 or larger')diff --git a/apps/studio/components/interfaces/Auth/ProtectionAuthSettingsForm/ProtectionAuthSettingsForm.tsx b/apps/studio/components/interfaces/Auth/ProtectionAuthSettingsForm/ProtectionAuthSettingsForm.tsxindex d2f5606bf60..e7f87c98a56 100644--- a/apps/studio/components/interfaces/Auth/ProtectionAuthSettingsForm/ProtectionAuthSettingsForm.tsx+++ b/apps/studio/components/interfaces/Auth/ProtectionAuthSettingsForm/ProtectionAuthSettingsForm.tsx@@ -3,7 +3,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import Link from 'next/link'import { useEffect } from 'react'-import { useForm, useWatch } from 'react-hook-form'+import { SubmitHandler, useForm, useWatch } from 'react-hook-form'import { toast } from 'sonner'import {Badge,@@ -33,7 +33,6 @@ import {import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'import * as z from 'zod'-import { NO_REQUIRED_CHARACTERS } from '../Auth.constants'import { AlertError } from '@/components/ui/AlertError'import { InlineLink } from '@/components/ui/InlineLink'import { NoPermission } from '@/components/ui/NoPermission'@@ -50,22 +49,6 @@ const CAPTCHA_PROVIDERS = [type CaptchaProviders = 'hcaptcha' | 'turnstile'const baseSchema = z.object({- DISABLE_SIGNUP: z.boolean(),- EXTERNAL_ANONYMOUS_USERS_ENABLED: z.boolean(),- SECURITY_MANUAL_LINKING_ENABLED: z.boolean(),- SITE_URL: z.string().min(1, 'Must have a Site URL'),- PASSWORD_MIN_LENGTH: z- .preprocess(- (val) => (val === '' || val == null ? undefined : val),- z.coerce- .number({- required_error: 'Must have a password min length',- invalid_type_error: 'Must have a password min length',- })- .min(6, 'Must be greater or equal to 6.')- )- .optional(),- PASSWORD_REQUIRED_CHARACTERS: z.string().optional(),PASSWORD_HIBP_ENABLED: z.boolean().optional(),})@@ -83,7 +66,7 @@ const captchaDisabledSchema = z.object({SECURITY_CAPTCHA_ENABLED: z.literal(false),SECURITY_CAPTCHA_SECRET: z.string().optional(),- SECURITY_CAPTCHA_PROVIDER: z.string().optional(),+ SECURITY_CAPTCHA_PROVIDER: z.enum(['hcaptcha', 'turnstile']).optional(),}).merge(baseSchema)@@ -122,15 +105,9 @@ export const ProtectionAuthSettingsForm = () => {const protectionForm = useForm<FormSchema>({resolver: zodResolver(formSchema),defaultValues: {- DISABLE_SIGNUP: true,- EXTERNAL_ANONYMOUS_USERS_ENABLED: false,- SECURITY_MANUAL_LINKING_ENABLED: false,- SITE_URL: '',SECURITY_CAPTCHA_ENABLED: false,SECURITY_CAPTCHA_SECRET: '',SECURITY_CAPTCHA_PROVIDER: 'hcaptcha',- PASSWORD_MIN_LENGTH: 6,- PASSWORD_REQUIRED_CHARACTERS: NO_REQUIRED_CHARACTERS,PASSWORD_HIBP_ENABLED: false,},})@@ -142,47 +119,17 @@ export const ProtectionAuthSettingsForm = () => {const SECURITY_CAPTCHA_PROVIDER = (authConfig.SECURITY_CAPTCHA_PROVIDER ||'hcaptcha') as CaptchaProviders- if (authConfig.SECURITY_CAPTCHA_ENABLED) {- protectionForm.reset({- DISABLE_SIGNUP: !authConfig.DISABLE_SIGNUP,- EXTERNAL_ANONYMOUS_USERS_ENABLED: authConfig.EXTERNAL_ANONYMOUS_USERS_ENABLED || false,- SECURITY_MANUAL_LINKING_ENABLED: authConfig.SECURITY_MANUAL_LINKING_ENABLED || false,- SITE_URL: authConfig.SITE_URL || '',- SECURITY_CAPTCHA_ENABLED: authConfig.SECURITY_CAPTCHA_ENABLED,- SECURITY_CAPTCHA_SECRET: authConfig.SECURITY_CAPTCHA_SECRET || '',- SECURITY_CAPTCHA_PROVIDER,- PASSWORD_MIN_LENGTH: authConfig.PASSWORD_MIN_LENGTH || 6,- PASSWORD_REQUIRED_CHARACTERS:- authConfig.PASSWORD_REQUIRED_CHARACTERS || NO_REQUIRED_CHARACTERS,- PASSWORD_HIBP_ENABLED: authConfig.PASSWORD_HIBP_ENABLED || false,- })- } else {- protectionForm.reset({- DISABLE_SIGNUP: !authConfig.DISABLE_SIGNUP,- EXTERNAL_ANONYMOUS_USERS_ENABLED: authConfig.EXTERNAL_ANONYMOUS_USERS_ENABLED || false,- SECURITY_MANUAL_LINKING_ENABLED: authConfig.SECURITY_MANUAL_LINKING_ENABLED || false,- SITE_URL: authConfig.SITE_URL || '',- SECURITY_CAPTCHA_ENABLED: authConfig.SECURITY_CAPTCHA_ENABLED,- SECURITY_CAPTCHA_SECRET: authConfig.SECURITY_CAPTCHA_SECRET || '',- SECURITY_CAPTCHA_PROVIDER,- PASSWORD_MIN_LENGTH: authConfig.PASSWORD_MIN_LENGTH || 6,- PASSWORD_REQUIRED_CHARACTERS:- authConfig.PASSWORD_REQUIRED_CHARACTERS || NO_REQUIRED_CHARACTERS,- PASSWORD_HIBP_ENABLED: authConfig.PASSWORD_HIBP_ENABLED || false,- })- }+ protectionForm.reset({+ SECURITY_CAPTCHA_ENABLED: authConfig.SECURITY_CAPTCHA_ENABLED,+ SECURITY_CAPTCHA_SECRET: authConfig.SECURITY_CAPTCHA_SECRET || '',+ SECURITY_CAPTCHA_PROVIDER,+ PASSWORD_HIBP_ENABLED: authConfig.PASSWORD_HIBP_ENABLED || false,+ })}}, [authConfig, isUpdatingConfig])- const onSubmitProtection = (values: any) => {- const payload = { ...values }- payload.DISABLE_SIGNUP = !values.DISABLE_SIGNUP- // The backend uses empty string to represent no required characters in the password- if (payload.PASSWORD_REQUIRED_CHARACTERS === NO_REQUIRED_CHARACTERS) {- payload.PASSWORD_REQUIRED_CHARACTERS = ''- }-- updateAuthConfig({ projectRef: projectRef!, config: payload })+ const onSubmitProtection: SubmitHandler<z.infer<typeof formSchema>> = (values) => {+ updateAuthConfig({ projectRef: projectRef!, config: values })}const SECURITY_CAPTCHA_ENABLED = useWatch({@@ -243,6 +190,7 @@ export const ProtectionAuthSettingsForm = () => {><FormControl><Switch+ aria-label="Toggle Captcha protection"checked={field.value}onCheckedChange={field.onChange}disabled={!canUpdateConfig}diff --git a/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx b/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsxindex b3827866156..bf02a2f7d03 100644--- a/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx+++ b/apps/studio/components/interfaces/Auth/SmtpForm/SmtpForm.tsx@@ -39,6 +39,7 @@ import { useAuthConfigUpdateMutation } from '@/data/auth/auth-config-update-mutaimport { useAuthTemplateResetMutation } from '@/data/auth/auth-template-reset-mutation'import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'+import { preprocessEmptyNumberInput } from '@/lib/forms/zod-number-input'const smtpEnabledSchema = z.object({ENABLE_SMTP: z.literal(true),@@ -53,8 +54,7 @@ const smtpEnabledSchema = z.object({.trim().min(1, 'Host URL is required').regex(urlRegex({ excludeSimpleDomains: false }), 'Must be a valid URL or IP address'),- SMTP_PORT: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ SMTP_PORT: preprocessEmptyNumberInput(z.coerce.number({required_error: 'Port number is required',@@ -63,8 +63,7 @@ const smtpEnabledSchema = z.object({.min(1, 'Must be a valid port number more than 0').max(65535, 'Must be a valid port number no more than 65535')),- SMTP_MAX_FREQUENCY: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),+ SMTP_MAX_FREQUENCY: preprocessEmptyNumberInput(z.coerce.number({required_error: 'Rate limit is required',@@ -82,14 +81,8 @@ const smtpDisabledSchema = z.object({SMTP_ADMIN_EMAIL: z.string().optional(),SMTP_SENDER_NAME: z.string().optional(),SMTP_HOST: z.string().optional(),- SMTP_PORT: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),- z.coerce.number().optional()- ),- SMTP_MAX_FREQUENCY: z.preprocess(- (val) => (val === '' || val == null ? undefined : val),- z.coerce.number().optional()- ),+ SMTP_PORT: preprocessEmptyNumberInput(z.coerce.number().optional()),+ SMTP_MAX_FREQUENCY: preprocessEmptyNumberInput(z.coerce.number().optional()),SMTP_USER: z.string().optional(),SMTP_PASS: z.string().optional(),})diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/BigQuery.schema.ts b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/BigQuery.schema.tsindex 1777eac3546..e7dcc7a3570 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/BigQuery.schema.ts+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/BigQuery/BigQuery.schema.ts@@ -1,9 +1,6 @@import * as z from 'zod'-import {- optionalNumberInputSchema,- requiredNumberInputSchema,-} from '../DestinationForm.schema.utils'+import { optionalNumberInputSchema, requiredNumberInputSchema } from '@/lib/forms/zod-number-input'const CONNECTION_POOL_SIZE_MIN_ERROR = 'Connection pool size must be greater than 0.'diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.tsindex 0ecadb896d0..e942e05dcb3 100644--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts+++ b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.ts@@ -3,9 +3,9 @@ import * as z from 'zod'import { AnalyticsBucketFormSchema } from './AnalyticsBucket/AnalyticsBucket.schema'import { BigQueryFormSchema } from './BigQuery/BigQuery.schema'import { ClickHouseFormSchema } from './ClickHouse/ClickHouse.schema'-import { requiredNumberInputSchema } from './DestinationForm.schema.utils'import { DuckLakeFormSchema } from './DuckLake/DuckLake.schema'import { SnowflakeFormSchema } from './Snowflake/Snowflake.schema'+import { requiredNumberInputSchema } from '@/lib/forms/zod-number-input'const BATCH_WAIT_TIME_MIN_ERROR = 'Batch wait time must be 0 or greater.'const MAX_TABLE_SYNC_WORKERS_MIN_ERROR = 'Max table sync workers must be greater than 0.'diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.utils.ts b/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.utils.tsdeleted file mode 100644index 68bc432320a..00000000000--- a/apps/studio/components/interfaces/Database/Replication/DestinationPanel/DestinationForm/DestinationForm.schema.utils.ts+++ /dev/null@@ -1,7 +0,0 @@-import * as z from 'zod'--export const requiredNumberInputSchema = (schema: z.ZodNumber) =>- z.preprocess((value) => (value === '' ? Number.NaN : value), schema)--export const optionalNumberInputSchema = (schema: z.ZodNumber) =>- z.preprocess((value) => (value === '' ? undefined : value), schema.optional())diff --git a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsxindex d6d3a31638b..d45a87d62f5 100644--- a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx+++ b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx@@ -50,6 +50,7 @@ import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'import { useHighAvailability } from '@/hooks/misc/useHighAvailability'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { DOCS_URL } from '@/lib/constants'+import { preprocessEmptyNumberInput } from '@/lib/forms/zod-number-input'const formId = 'pooling-configuration-form'const HIGH_AVAILABILITY_MAX_CLIENT_CONNECTIONS = 100_000@@ -57,14 +58,8 @@ const HA_DISABLED_TITLE ='Connection pooling settings are managed automatically on High Availability projects'const PoolingConfigurationFormSchema = z.object({- default_pool_size: z.preprocess(- (val) => (val === '' || val === null || val === undefined ? undefined : val),- z.coerce.number().optional()- ),- max_client_conn: z.preprocess(- (val) => (val === '' || val === null || val === undefined ? undefined : val),- z.coerce.number().optional()- ),+ default_pool_size: preprocessEmptyNumberInput(z.coerce.number().optional()),+ max_client_conn: preprocessEmptyNumberInput(z.coerce.number().optional()),})/**diff --git a/apps/studio/lib/forms/zod-number-input.test.ts b/apps/studio/lib/forms/zod-number-input.test.tsnew file mode 100644index 00000000000..309b6e0a6fe--- /dev/null+++ b/apps/studio/lib/forms/zod-number-input.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from 'vitest'+import * as z from 'zod'++import {+ optionalNumberInputSchema,+ preprocessEmptyNumberInput,+ requiredNumberInputSchema,+} from './zod-number-input'++const REQUIRED_ERROR = 'Value is required'++describe('requiredNumberInputSchema', () => {+ const schema = requiredNumberInputSchema(+ z+ .number({+ required_error: REQUIRED_ERROR,+ invalid_type_error: REQUIRED_ERROR,+ })+ .min(1, 'Must be greater than 0')+ )++ it('rejects an empty string with the schema error message', () => {+ const result = schema.safeParse('')++ expect(result.success).toBe(false)+ if (!result.success) expect(result.error.issues[0]?.message).toBe(REQUIRED_ERROR)+ })++ it('leaves undefined to the inner schema', () => {+ const result = schema.safeParse(undefined)++ expect(result.success).toBe(false)+ if (!result.success) expect(result.error.issues[0]?.message).toBe(REQUIRED_ERROR)+ })++ it('accepts a valid number', () => {+ expect(schema.safeParse(2).success).toBe(true)+ })+})++describe('optionalNumberInputSchema', () => {+ const schema = optionalNumberInputSchema(+ z.number().int('Must be a whole number').min(0, 'Must be 0 or greater')+ )++ it.each(['', null, undefined])('normalizes %s to undefined', (value) => {+ const result = schema.safeParse(value)++ expect(result.success).toBe(true)+ if (result.success) expect(result.data).toBeUndefined()+ })++ it('accepts a valid number', () => {+ const result = schema.safeParse(5)++ expect(result.success).toBe(true)+ if (result.success) expect(result.data).toBe(5)+ })+})++describe('preprocessEmptyNumberInput', () => {+ const schema = preprocessEmptyNumberInput(+ z.coerce+ .number({ required_error: REQUIRED_ERROR, invalid_type_error: REQUIRED_ERROR })+ .min(0, 'Must be 0 or larger')+ )++ it('rejects an empty string with the schema error message', () => {+ const result = schema.safeParse('')++ expect(result.success).toBe(false)+ if (!result.success) expect(result.error.issues[0]?.message).toBe(REQUIRED_ERROR)+ })++ it('coerces a numeric string', () => {+ const result = schema.safeParse('12')++ expect(result.success).toBe(true)+ if (result.success) expect(result.data).toBe(12)+ })++ it('accepts an empty string when the inner schema is optional', () => {+ const optionalSchema = preprocessEmptyNumberInput(+ z.coerce+ .number({ required_error: REQUIRED_ERROR, invalid_type_error: REQUIRED_ERROR })+ .min(0, 'Must be 0 or larger')+ .optional()+ )++ const result = optionalSchema.safeParse('')++ expect(result.success).toBe(true)+ if (result.success) expect(result.data).toBeUndefined()+ })+})diff --git a/apps/studio/lib/forms/zod-number-input.ts b/apps/studio/lib/forms/zod-number-input.tsnew file mode 100644index 00000000000..68580a99b1a--- /dev/null+++ b/apps/studio/lib/forms/zod-number-input.ts@@ -0,0 +1,24 @@+import * as z from 'zod'++export const isEmptyNumberInput = (value: unknown) => value === '' || value == null++/**+ * Wraps a zod number schema so an empty controlled input (`''`) fails validation with the+ * schema's `invalid_type_error` instead of snapping back to the previous value.+ */+export const requiredNumberInputSchema = (schema: z.ZodNumber) =>+ z.preprocess((value) => (value === '' ? Number.NaN : value), schema)++/**+ * Wraps a zod number schema so an empty controlled input (`''` or `null`) normalizes to+ * `undefined` before validation.+ */+export const optionalNumberInputSchema = (schema: z.ZodNumber) =>+ z.preprocess((value) => (isEmptyNumberInput(value) ? undefined : value), schema.optional())++/**+ * Normalizes empty controlled number inputs (`''` or `null`) to `undefined` before running+ * the inner schema. Useful with `z.coerce.number()` in auth and settings forms.+ */+export const preprocessEmptyNumberInput = <T extends z.ZodTypeAny>(schema: T) =>+ z.preprocess((value) => (isEmptyNumberInput(value) ? undefined : value), schema)