migrated from zod v3 to zod v4

This commit is contained in:
2025-10-20 15:02:53 +02:00
parent 8b1e9d1cf6
commit 4d1c06c5be
16 changed files with 229 additions and 328 deletions

View File

@@ -21,9 +21,9 @@ export const defaultConfig = {
* Schema for the PocketBase credentials.
*/
export const Credentials = z.object({
adminEmail: z.string().email(),
adminEmail: z.email(),
adminPassword: z.string(),
url: z.string().url(),
url: z.url(),
})
export type Credentials = z.infer<typeof Credentials>
@@ -34,31 +34,52 @@ export const Config = z.object({
...Credentials.partial().shape,
ignore: z.string().array().default(defaultConfig.ignore),
nameEnum: z
.function(z.tuple([z.string()]), z.string())
.function({
input: [z.string()],
output: z.string(),
})
.optional()
.transform((f) => f ?? defaultConfig.nameEnum),
nameEnumField: z
.function(z.tuple([z.string(), z.string()]), z.string())
.function({
input: [z.string(), z.string()],
output: z.string(),
})
.optional()
.transform((f) => f ?? defaultConfig.nameEnumField),
nameEnumSchema: z
.function(z.tuple([z.string()]), z.string())
.function({
input: [z.string()],
output: z.string(),
})
.optional()
.transform((f) => f ?? defaultConfig.nameEnumSchema),
nameEnumType: z
.function(z.tuple([z.string()]), z.string())
.function({
input: [z.string()],
output: z.string(),
})
.optional()
.transform((f) => f ?? defaultConfig.nameEnumType),
nameEnumValues: z
.function(z.tuple([z.string()]), z.string())
.function({
input: [z.string()],
output: z.string(),
})
.optional()
.transform((f) => f ?? defaultConfig.nameEnumValues),
nameRecordSchema: z
.function(z.tuple([z.string()]), z.string())
.function({
input: [z.string()],
output: z.string(),
})
.optional()
.transform((f) => f ?? defaultConfig.nameRecordSchema),
nameRecordType: z
.function(z.tuple([z.string()]), z.string())
.function({
input: [z.string()],
output: z.string(),
})
.optional()
.transform((f) => f ?? defaultConfig.nameRecordType),
output: z.string().default(defaultConfig.output),

View File

@@ -58,26 +58,28 @@ export function stringifyContent(collections: CollectionModel[], opts: GenerateO
schema = 'z.boolean()'
break
case 'date':
case 'date': {
const minConstraintDate = field.min ? `.min(new Date("${field.min}"))` : ''
const maxConstraintDate = field.max ? `.max(new Date("${field.max}"))` : ''
schema = `z.string().pipe(z.coerce.date()${minConstraintDate}${maxConstraintDate})`
schema = `z.coerce.date()${minConstraintDate}${maxConstraintDate}`
break
}
case 'editor':
// TODO: implement convertUrls
schema = 'z.string()'
break
case 'email':
case 'email': {
const onlyDomainsConstraint = createDomainConstraint(field.onlyDomains, true, 'email')
const exceptDomainsConstraint = createDomainConstraint(field.exceptDomains, false, 'email')
schema = `z.string().email()${onlyDomainsConstraint}${exceptDomainsConstraint}`
schema = `z.email()${onlyDomainsConstraint}${exceptDomainsConstraint}`
break
}
case 'file':
case 'file': {
const maxSelectFile: number = field.maxSelect
const maxSizeFile: number = field.maxSize
const mimeTypesArray: string[] = field.mimeTypes || []
@@ -98,20 +100,22 @@ export function stringifyContent(collections: CollectionModel[], opts: GenerateO
const baseFileSchema = `z.union([z.string(), ${fileValidation}])`
schema = `${baseFileSchema}${fileFieldTypeArray}`
break
}
case 'json':
schema = field.maxSize > 0 ? `pbJsonField(${field.maxSize})` : 'pbJsonField()'
break
case 'number':
case 'number': {
const maxNumber = field.maxNumber ? `.max(${field.maxNumber})` : ''
const minNumber = field.minNumber ? `.min(${field.minNumber})` : ''
const noDecimal = field.noDecimal ? '.int()' : ''
schema = `z.number()${noDecimal}${minNumber}${maxNumber}`
break
}
case 'relation':
case 'relation': {
// TODO: implement cascadeDelete, displayFields, multiple records query
const multiple =
field.maxSelect === 1 ? '' : `.array().min(${field.minSelect}).max(${field.maxSelect})`
@@ -122,14 +126,16 @@ export function stringifyContent(collections: CollectionModel[], opts: GenerateO
schema = `z.string()${isOptional}${multiple}`
break
}
case 'select':
case 'select': {
const maxSelect = field.maxSelect === 1 ? '' : `.array().max(${field.maxSelect})`
schema = `${opts.nameEnumSchema(opts.nameEnumField(collectionName, field.name))}${maxSelect}`
break
}
case 'text':
case 'text': {
const patternText =
field.pattern && field.pattern.trim() !== ''
? `.regex(new RegExp("${field.pattern.replace(/"/g, '\\"')}"))`
@@ -139,13 +145,15 @@ export function stringifyContent(collections: CollectionModel[], opts: GenerateO
schema = `z.string()${minText}${maxText}${patternText}`
break
}
case 'url':
case 'url': {
const onlyDomainsUrlConstraint = createDomainConstraint(field.onlyDomains, true, 'url')
const exceptDomainsUrlConstraint = createDomainConstraint(field.exceptDomains, false, 'url')
schema = `z.string().url()${onlyDomainsUrlConstraint}${exceptDomainsUrlConstraint}`
schema = `z.url()${onlyDomainsUrlConstraint}${exceptDomainsUrlConstraint}`
break
}
case 'geoPoint':
schema =
@@ -191,7 +199,7 @@ export function stringifyContent(collections: CollectionModel[], opts: GenerateO
return {
collectionNames: `[\n\t${collections.map(({ name }) => `"${name}"`).join(',\n\t')},\n]`,
enums: getCollectionSelectFields().map(stringifyEnum).join('\n\n'),
records: `${collections.map(stringifyRecord).join('\n\n')}\n\nexport const records = new Map<Collection, z.AnyZodObject>([\n\t${collections.map(stringifySchemasEntry).join(',\n\t')},\n]);`,
records: `${collections.map(stringifyRecord).join('\n\n')}\n\nexport const records = new Map<Collection, z.ZodObject>([\n\t${collections.map(stringifySchemasEntry).join(',\n\t')},\n]);`,
services: collections.map(stringifyService).join('\n'),
}
}

View File

@@ -1,25 +1,20 @@
import type { default as Pocketbase, SendOptions } from 'pocketbase'
import type { ZodObject } from 'zod'
import { fullListOptionsFrom, optionsFrom } from '@/options.ts'
import type { RecordsList } from '@/schemas.ts'
import { AnyRecordsList } from '@/schemas.ts'
import type {
AnyZodRecord,
RecordFullListOpts,
RecordIdRef,
RecordRef,
RecordSlugRef,
} from '@/types.ts'
import type { RecordFullListOpts, RecordIdRef, RecordRef, RecordSlugRef } from '@/types.ts'
export function helpersFrom({ fetch, pocketbase }: HelpersFromOpts) {
async function getRecord<C extends string, S extends AnyZodRecord>(
async function getRecord<C extends string, S extends ZodObject>(
ref: RecordSlugRef<C>,
opts: GetRecordOpts<S>,
): Promise<S['_output']>
async function getRecord<C extends string, S extends AnyZodRecord>(
async function getRecord<C extends string, S extends ZodObject>(
ref: RecordIdRef<C>,
opts: GetRecordOpts<S>,
): Promise<S['_output']>
async function getRecord<C extends string, S extends AnyZodRecord>(
async function getRecord<C extends string, S extends ZodObject>(
ref: RecordRef<C>,
opts: GetRecordOpts<S>,
) {
@@ -31,7 +26,7 @@ export function helpersFrom({ fetch, pocketbase }: HelpersFromOpts) {
return schema.parseAsync(unsafeRecord)
}
async function getRecords<C extends string, S extends AnyZodRecord>(
async function getRecords<C extends string, S extends ZodObject>(
collection: C,
opts: GetRecordsOpts<S>,
): Promise<RecordsList<S>> {
@@ -45,6 +40,6 @@ export function helpersFrom({ fetch, pocketbase }: HelpersFromOpts) {
return { getRecord, getRecords }
}
export type GetRecordOpts<S extends AnyZodRecord> = { schema: S }
export type GetRecordsOpts<S extends AnyZodRecord> = RecordFullListOpts<S> & { schema: S }
export type GetRecordOpts<S extends ZodObject> = { schema: S }
export type GetRecordsOpts<S extends ZodObject> = RecordFullListOpts<S> & { schema: S }
export type HelpersFromOpts = { fetch?: SendOptions['fetch']; pocketbase: Pocketbase }

View File

@@ -1,6 +1,6 @@
export * from './config.js'
export * from './helpers.js'
export * from './options.js'
export * from './schemas.js'
export * from './types.ts'
export * from './utils.js'
export * from '@/config.js'
export * from '@/helpers.js'
export * from '@/options.js'
export * from '@/schemas.js'
export * from '@/types.ts'
export * from '@/utils.js'

View File

@@ -1,6 +1,6 @@
import type { AnyZodObject, ZodTypeAny } from 'zod'
import type { ZodObject } from 'zod'
import { z } from 'zod'
import type { AnyZodRecord, RecordFullListOpts, RecordListOpts } from '@/types.ts'
import type { RecordFullListOpts, RecordListOpts } from '@/types.ts'
/**
* Extends the given schema with the given expansion.
@@ -8,7 +8,7 @@ import type { AnyZodRecord, RecordFullListOpts, RecordListOpts } from '@/types.t
* @param shape - The shape of the expansion
* @returns A new schema extended with the given expansion
*/
export function expandFrom<S extends AnyZodRecord>(schema: S) {
export function expandFrom<S extends ZodObject<any, any>>(schema: S) {
return expandFromRec(schema)
.sort((k1, k2) => (k1 < k2 ? -1 : 1))
.join(',')
@@ -20,7 +20,7 @@ export function expandFrom<S extends AnyZodRecord>(schema: S) {
* @param shape - The shape of the expansion
* @returns A new schema extended with the given expansion
*/
export function fieldsFrom<S extends AnyZodRecord>(schema: S) {
export function fieldsFrom<S extends ZodObject<any, any>>(schema: S) {
return fieldsFromRec(schema)
.sort((k1, k2) => (k1 < k2 ? -1 : 1))
.join(',')
@@ -32,7 +32,7 @@ export function fieldsFrom<S extends AnyZodRecord>(schema: S) {
* @param shape - The shape of the expansion
* @returns A new schema extended with the given expansion
*/
export function optionsFrom<S extends AnyZodRecord>(schema: S) {
export function optionsFrom<S extends ZodObject<any, any>>(schema: S) {
return { expand: expandFrom(schema), fields: fieldsFrom(schema) }
}
@@ -42,7 +42,7 @@ export function optionsFrom<S extends AnyZodRecord>(schema: S) {
* @param shape - The shape of the expansion
* @returns A new schema extended with the given expansion
*/
export function listOptionsFrom<S extends AnyZodRecord>(schema: S, opts: RecordListOpts<S>) {
export function listOptionsFrom<S extends ZodObject<any, any>>(schema: S, opts: RecordListOpts<S>) {
const { page = 1, perPage = 30, ...rest } = opts
return { ...optionsFrom(schema), page, perPage, ...rest }
}
@@ -53,7 +53,7 @@ export function listOptionsFrom<S extends AnyZodRecord>(schema: S, opts: RecordL
* @param shape - The shape of the expansion
* @returns A new schema extended with the given expansion
*/
export function fullListOptionsFrom<S extends AnyZodRecord>(
export function fullListOptionsFrom<S extends ZodObject<any, any>>(
schema: S,
opts: RecordFullListOpts<S>,
) {
@@ -61,7 +61,7 @@ export function fullListOptionsFrom<S extends AnyZodRecord>(
return listOptionsFrom(schema, { page, perPage, skipTotal, ...rest })
}
function expandFromRec<S extends ZodTypeAny>(schema: S, prefix = '') {
function expandFromRec<S>(schema: S, prefix = '') {
let expands: string[] = []
const shape = getObjectSchemaDescendant(schema)?.shape
if (!shape || !('expand' in shape)) return []
@@ -76,7 +76,7 @@ function expandFromRec<S extends ZodTypeAny>(schema: S, prefix = '') {
return expands
}
function fieldsFromRec<S extends z.ZodTypeAny>(schema: S, prefix = '') {
function fieldsFromRec<S>(schema: S, prefix = '') {
let fields: string[] = []
const shape = getObjectSchemaDescendant(schema)?.shape
if (!shape) return []
@@ -91,17 +91,63 @@ function fieldsFromRec<S extends z.ZodTypeAny>(schema: S, prefix = '') {
return fields.sort((k1, k2) => (k1 < k2 ? -1 : 1))
}
function hasObjectSchemaDescendant(value: unknown): value is z.ZodTypeAny {
if (value instanceof z.ZodEffects) return hasObjectSchemaDescendant(value.innerType())
if (value instanceof z.ZodArray) return hasObjectSchemaDescendant(value.element)
if (value instanceof z.ZodOptional) return hasObjectSchemaDescendant(value.unwrap())
function hasObjectSchemaDescendant(value: unknown): value is any {
// Handle ZodPipe
if (value && typeof value === 'object' && 'constructor' in value) {
const constructor = (value as any).constructor
if (constructor?.name === 'ZodPipe') {
const inputSchema = (value as any)._def?.in
if (inputSchema) return hasObjectSchemaDescendant(inputSchema)
}
}
// Handle ZodTransform
if (value && typeof value === 'object' && 'constructor' in value) {
const constructor = (value as any).constructor
if (constructor?.name === 'ZodTransform') {
const innerSchema =
(value as any)._def?.input || (value as any)._def?.schema || (value as any).sourceType
if (innerSchema) return hasObjectSchemaDescendant(innerSchema)
}
}
// Handle ZodArray
if (value instanceof z.ZodArray) return hasObjectSchemaDescendant((value as any).element)
// Handle ZodOptional
if (value instanceof z.ZodOptional) return hasObjectSchemaDescendant((value as any).unwrap())
return value instanceof z.ZodObject
}
function getObjectSchemaDescendant<S extends z.ZodTypeAny>(schema: S): AnyZodObject | undefined {
if (schema instanceof z.ZodEffects) return getObjectSchemaDescendant(schema.innerType())
if (schema instanceof z.ZodArray) return getObjectSchemaDescendant(schema.element)
if (schema instanceof z.ZodOptional) return getObjectSchemaDescendant(schema.unwrap())
if (schema instanceof z.ZodObject) return schema
return
function getObjectSchemaDescendant<S>(schema: S): ZodObject | undefined {
// Handle ZodPipe
if (schema && typeof schema === 'object' && 'constructor' in schema) {
const constructor = (schema as any).constructor
if (constructor?.name === 'ZodPipe') {
const inputSchema = (schema as any)._def?.in
if (inputSchema) return getObjectSchemaDescendant(inputSchema)
}
}
// Handle ZodTransform
if (schema && typeof schema === 'object' && 'constructor' in schema) {
const constructor = (schema as any).constructor
if (constructor?.name === 'ZodTransform') {
const innerSchema =
(schema as any)._def?.input || (schema as any)._def?.schema || (schema as any).sourceType
if (innerSchema) return getObjectSchemaDescendant(innerSchema)
}
}
// Handle ZodArray
if (schema instanceof z.ZodArray) return getObjectSchemaDescendant((schema as any).element)
// Handle ZodOptional
if (schema instanceof z.ZodOptional) return getObjectSchemaDescendant((schema as any).unwrap())
// Handle ZodObject
if (schema instanceof z.ZodObject) return schema as ZodObject
return undefined
}

View File

@@ -1,16 +1,16 @@
import type { AnyZodObject, objectUtil, ZodObject, ZodRawShape } from 'zod'
import { ZodEffects, ZodOptional, z } from 'zod'
import type { AnyZodRecord, HasRequiredKeys, ZodRecordKeys } from '@/types.ts'
import type { ZodObject, ZodOptional, ZodRawShape } from 'zod'
import { z } from 'zod'
import type { HasRequiredKeys, ZodRecordKeys } from '@/types.ts'
/**
* Records list schema.
*/
export const AnyRecordsList = z.object({
items: z.any().array(),
page: z.number().int().min(1),
perPage: z.number().int().min(1),
totalItems: z.number().int().min(-1),
totalPages: z.number().int().min(-1),
page: z.int().min(1),
perPage: z.int().min(1),
totalItems: z.int().min(-1),
totalPages: z.int().min(-1),
})
/**
@@ -19,7 +19,7 @@ export const AnyRecordsList = z.object({
* @param shape - The shape of the expansion
* @returns A new schema extended with the given expansion
*/
export function expand<S extends AnyZodObject, E extends ZodRawShape>(schema: S, shape: E) {
export function expand<S extends ZodObject<any, any>, E extends ZodRawShape>(schema: S, shape: E) {
const isExpandOptional = Object.entries(shape).every(
([, value]) => value instanceof z.ZodOptional,
)
@@ -28,7 +28,10 @@ export function expand<S extends AnyZodObject, E extends ZodRawShape>(schema: S,
...schema.shape,
expand: isExpandOptional ? z.object(shape).optional() : z.object(shape),
})
.transform(({ expand, ...rest }) => ({ ...rest, ...(expand ?? {}) })) as ZodObjectExpand<S, E>
.transform(({ expand, ...rest }) => ({
...rest,
...(expand ?? {}),
})) as ZodObjectExpand<S, E>
}
/**
@@ -37,7 +40,10 @@ export function expand<S extends AnyZodObject, E extends ZodRawShape>(schema: S,
* @param keys - The keys to keep
* @returns A new schema with only the given keys
*/
export function pick<S extends AnyZodObject, K extends ZodRecordKeys<S>[]>(schema: S, keys: K) {
export function pick<S extends ZodObject<any, any>, K extends ZodRecordKeys<S>[]>(
schema: S,
keys: K,
) {
return schema.pick(Object.fromEntries(keys.map((key) => [key, true]))) as ZodObjectPick<S, K>
}
@@ -48,47 +54,44 @@ export function pick<S extends AnyZodObject, K extends ZodRecordKeys<S>[]>(schem
* @param shape - The shape of the expansion
* @returns A new schema with only the given keys
*/
export function select<S extends AnyZodObject, K extends ZodRecordKeys<S>[], E extends ZodRawShape>(
schema: S,
keys: K,
shape: E,
): ZodObjectExpand<ZodObjectPick<S, K>, E>
export function select<S extends AnyZodObject, K extends ZodRecordKeys<S>[]>(
export function select<
S extends ZodObject<any, any>,
K extends ZodRecordKeys<S>[],
E extends ZodRawShape,
>(schema: S, keys: K, shape: E): ZodObjectExpand<ZodObjectPick<S, K>, E>
export function select<S extends ZodObject<any, any>, K extends ZodRecordKeys<S>[]>(
schema: S,
keys: K,
): ZodObjectPick<S, K>
export function select<
S extends AnyZodObject,
S extends ZodObject<any, any>,
K extends ZodRecordKeys<S>[],
E extends ZodRawShape | undefined,
>(schema: S, keys: K, shape?: E) {
return shape ? expand(pick(schema, keys), shape) : pick(schema, keys)
}
export type ZodObjectExpand<S extends AnyZodObject, E extends ZodRawShape> = S extends ZodObject<
infer T,
infer U,
infer C
>
? ZodEffects<
export type ZodObjectExpand<
S extends ZodObject<any, any>,
E extends ZodRawShape,
> = S extends ZodObject<infer T, infer U>
? z.ZodPipe<
ZodObject<
objectUtil.extendShape<
T,
{ expand: HasRequiredKeys<E> extends true ? ZodObject<E> : ZodOptional<ZodObject<E>> }
>,
U,
C
T & {
expand: HasRequiredKeys<E> extends true ? ZodObject<E> : ZodOptional<ZodObject<E>>
},
U
>,
ZodObject<objectUtil.extendShape<T, E>, U, C>['_output']
z.ZodTransform<T & E>
>
: never
export type ZodObjectPick<
S extends AnyZodObject,
S extends ZodObject<any, any>,
K extends ZodRecordKeys<S>[],
> = S extends ZodObject<infer T, infer U, infer C> ? ZodObject<Pick<T, K[number]>, U, C> : never
> = S extends ZodObject<infer T, infer U> ? ZodObject<Pick<T, K[number]>, U> : never
export type AnyRecordsList = z.infer<typeof AnyRecordsList>
export type RecordsList<S extends AnyZodRecord> = Omit<AnyRecordsList, 'items'> & {
export type RecordsList<S extends ZodObject<any, any>> = Omit<AnyRecordsList, 'items'> & {
items: S['_output'][]
}

View File

@@ -19,11 +19,11 @@ import type { ResolvedConfig } from '@/config.ts'
import { Config } from '@/config.ts'
import { generate } from '@/server/utils.ts'
import { fetchCollections } from '@/utils.ts'
import pkg from '../../package.json' with { type: 'json' }
import pkg from '%/package.json' with { type: 'json' }
async function getConfig() {
const { config } = await loadConfig({
name: 'zod-pocketbase-continue',
name: 'zod-pocketbase',
rcFile: false,
dotenv: true,
})

View File

@@ -1 +1 @@
export * from './utils.js'
export * from '@/server/utils.js'

View File

@@ -1,10 +1,10 @@
import type { AnyZodObject, ZodEffects, ZodOptional, ZodRawShape, ZodTypeAny } from 'zod'
import type { ZodObject, ZodOptional, ZodRawShape, ZodType } from 'zod'
export type AnyZodRecord = AnyZodObject | ZodEffects<AnyZodObject>
export type RecordFullListOpts<S extends ZodObject<any, any>> = RecordListOpts<S> & {
batch?: number
}
export type RecordFullListOpts<S extends AnyZodRecord> = RecordListOpts<S> & { batch?: number }
export type RecordListOpts<S extends AnyZodRecord> = {
export type RecordListOpts<S extends ZodObject<any, any>> = {
filter?: string
page?: number
perPage?: number
@@ -16,17 +16,17 @@ export type RecordIdRef<C extends string> = { collection: C; id: string }
export type RecordSlugRef<C extends string> = { collection: C; slug: string }
export type RecordRef<C extends string> = RecordIdRef<C> | RecordSlugRef<C>
export type ZodRecordKeys<S extends AnyZodRecord> = Extract<keyof S['_input'], string>
export type ZodRecordKeys<S extends ZodObject<any, any>> = Extract<keyof S['_input'], string>
export type ZodRecordMainKeys<S extends AnyZodRecord> = Exclude<ZodRecordKeys<S>, 'expand'>
export type ZodRecordMainKeys<S extends ZodObject<any, any>> = Exclude<ZodRecordKeys<S>, 'expand'>
export type ZodRecordSort<S extends AnyZodRecord> =
export type ZodRecordSort<S extends ZodObject<any, any>> =
| `${'+' | '-'}${ZodRecordMainKeys<S>}`
| '@random'
type RequiredKeysOf<S extends ZodRawShape> = Exclude<
{
[Key in keyof S]: S[Key] extends ZodOptional<ZodTypeAny> ? never : Key
[Key in keyof S]: S[Key] extends ZodOptional<ZodType> ? never : Key
}[keyof S],
undefined
>