zodvex 0.7.2-beta.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/normalizeCodecPaths.ts","../src/internal/stripUndefined.ts","../src/internal/boundaryHelpers.ts","../src/internal/ids.ts","../src/internal/schema/objectShape.ts","../src/internal/mapping/handlers/enum.ts","../src/internal/mapping/handlers/nullable.ts","../src/internal/mapping/handlers/record.ts","../src/internal/mapping/handlers/union.ts","../src/internal/mapping/utils.ts","../src/internal/mapping/core.ts","../src/internal/registry.ts","../src/internal/results.ts","../src/internal/schema/dateGuards.ts","../src/internal/schema/pick.ts","../src/internal/schema/runtimeHelpers.ts","../src/internal/codec.ts","../src/public/codec.ts","../src/internal/meta.ts","../src/public/codegen/extractCodec.ts","../src/internal/zx.ts","../src/internal/schemaHelpers.ts","../src/internal/modelSchemaBundle.ts","../src/internal/model.ts","../src/public/model.ts","../src/index.ts"],"names":["zodToConvexInternal","v","metadata","z","zodvexCodec","codec","date","nullableOptional","defineZodModel"],"mappings":";;;;;;;AAeA,SAAS,YAAY,MAAA,EAA4B;AAC/C,EAAA,IAAI,OAAA,GAAoB,MAAA;AACxB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,EAAA,EAAI,CAAA,EAAA,EAAK;AAC3B,IAAA,IACE,OAAA,YAAmB,YAAA,IACnB,OAAA,YAAmB,YAAA,IACnB,mBAAmB,WAAA,EACnB;AACA,MAAA,OAAA,GAAU,OAAA,CAAQ,KAAK,GAAA,CAAI,SAAA;AAC3B,MAAA;AAAA,IACF;AACA,IAAA;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;AAOA,SAAS,uBAAA,CAAwB,MAA2B,MAAA,EAAuC;AACjG,EAAA,MAAM,SAA8B,EAAC;AACrC,EAAA,IAAI,OAAA,GAAoB,MAAA;AAExB,EAAA,KA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QAAA,GAAkB;AAChC,EAAA,OAAO,qBAAqB,UAAU,CAAA;AACxC;AAKO,SAAS,MAAA,GAAgB;AAC9B,EAAA,OAAO,qBAAqB,QAAQ,CAAA;AACtC;AAKO,SAAS,YAAA,GAAsB;AACpC,EAAA,OAAO,qBAAqB,cAAc,CAAA;AAC5C;AAKO,SAAS,aAAA,GAAuB;AACrC,EAAA,OAAO,qBAAqB,eAAe,CAAA;AAC7C;AAKO,SAAS,gBAAA,GAA0B;AACxC,EAAA,OAAO,qBAAqB,kBAAkB,CAAA;AAChD;AAKO,SAAS,cAAA,GAAwB;AACtC,EAAA,OAAO,qBAAqB,gBAAgB,CAAA;AAC9C;AAKO,SAAS,mBAAA,GAA6B;AAC3C,EAAA,OAAO,qBAAqB,qBAAqB,CAAA;AACnD;AAKO,SAAS,sBAAA,GAAgC;AAC9C,EAAA,OAAO,qBAAqB,wBAAwB,CAAA;AACtD;AAKO,SAAS,oBAAA,GAA8B;AAC5C,EAAA,OAAO,qBAAqB,sBAAsB,CAAA;AACpD","file":"index.js","sourcesContent":["import {\n $ZodArray,\n $ZodCodec,\n $ZodDefault,\n $ZodError,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodType,\n encode\n} from './zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable/ZodDefault wrappers to get the structural type.\n */\nfunction unwrapOuter(schema: $ZodType): $ZodType {\n let current: $ZodType = schema\n for (let i = 0; i < 10; i++) {\n if (\n current instanceof $ZodOptional ||\n current instanceof $ZodNullable ||\n current instanceof $ZodDefault\n ) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return current\n}\n\n/**\n * Walks a path through a schema tree, truncating at codec boundaries.\n * When a codec is encountered, the path is cut — any deeper segments\n * are wire-internal and should not be exposed to consumers.\n */\nfunction truncateAtCodecBoundary(path: (string | number)[], schema: $ZodType): (string | number)[] {\n const result: (string | number)[] = []\n let current: $ZodType = schema\n\n for (const segment of path) {\n current = unwrapOuter(current)\n\n // If we've landed on a codec, everything from here is wire-internal — stop\n if (current instanceof $ZodCodec) {\n break\n }\n\n // Descend into objects\n if (current instanceof $ZodObject && typeof segment === 'string') {\n const fieldSchema = current._zod.def.shape[segment] as $ZodType | undefined\n if (!fieldSchema) {\n // Unknown field — include segment and stop\n result.push(segment)\n break\n }\n\n result.push(segment)\n\n const unwrapped = unwrapOuter(fieldSchema)\n if (unwrapped instanceof $ZodCodec) {\n // Hit a codec boundary — truncate here\n break\n }\n\n current = fieldSchema\n continue\n }\n\n // Descend into arrays\n if (current instanceof $ZodArray && typeof segment === 'number') {\n result.push(segment)\n current = current._zod.def.element\n continue\n }\n\n // For anything else (unions, records, etc.), include segment and continue\n result.push(segment)\n }\n\n return result\n}\n\n/**\n * Normalizes ZodError paths by truncating at codec boundaries.\n *\n * When z.encode() throws a ZodError, the paths reflect the wire schema\n * structure (e.g., [\"email\", \"value\"] for a custom codec).\n * This function strips the wire-internal segments so consumers see\n * clean field-level paths (e.g., [\"email\"]).\n */\nexport function normalizeCodecPaths(error: $ZodError, schema: $ZodType): $ZodError {\n const normalized = error.issues.map(issue => ({\n ...issue,\n path: truncateAtCodecBoundary(issue.path as (string | number)[], schema)\n }))\n return new $ZodError(normalized)\n}\n\n/**\n * Encodes a value through a Zod schema, normalizing codec-internal\n * path segments in any ZodError before re-throwing.\n *\n * Drop-in replacement for `z.encode(schema, value)` at client boundaries.\n */\nexport function safeEncode(schema: $ZodType, value: unknown): unknown {\n try {\n return encode(schema, value)\n } catch (e) {\n if (e instanceof $ZodError) throw normalizeCodecPaths(e as $ZodError, schema)\n throw e\n }\n}\n","/**\n * Recursively strips `undefined` values from objects and arrays.\n * Used by codec encode/decode to clean wire data.\n *\n * Extracted to its own module so client-safe code (boundaryHelpers)\n * can import it without pulling in zod via utils.ts.\n */\nexport function stripUndefined<T>(value: T): T {\n if (value === null || value === undefined) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUndefined) as T\n }\n\n // Only process plain objects (not class instances, Dates, etc.)\n if (typeof value === 'object' && value.constructor === Object) {\n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n result[key] = stripUndefined(val)\n }\n }\n return result as T\n }\n\n return value\n}\n","import type { FunctionReference } from 'convex/server'\nimport type { $ZodIssue } from 'zod/v4/core'\nimport { safeEncode } from './normalizeCodecPaths'\nimport { stripUndefined } from './stripUndefined'\nimport type { AnyRegistry } from './types'\nimport { $ZodError, safeParse } from './zod-core'\n\n/**\n * Resolves a Convex FunctionReference to its string path.\n *\n * Mirrors `getFunctionName` from `convex/server` but without the server import.\n * Reads the well-known `Symbol.for('functionName')` that Convex attaches to all\n * function references — the same symbol used by Convex's own browser client.\n */\nconst functionNameSymbol = Symbol.for('functionName')\n\nfunction resolveFunctionPath(ref: FunctionReference<any, any, any, any>): string {\n if (typeof ref === 'string') return ref\n const name = (ref as any)[functionNameSymbol]\n if (!name) {\n throw new Error(\n `Expected a Convex function reference (e.g. api.file.func), but received ${JSON.stringify(ref)}`\n )\n }\n return name\n}\n\n/**\n * Options for codec helper behavior.\n */\nexport type BoundaryHelpersOptions = {\n /**\n * How to handle decode failures (schema validation errors on wire data).\n *\n * - `'warn'` (default): log a console.warn and return raw wire data untransformed.\n * - `'throw'`: throw a ZodvexDecodeError (extends z.ZodError). // zod-ok\n */\n onDecodeError?: 'warn' | 'throw'\n}\n\n/**\n * Decode error with function path and wire data context.\n * Extends $ZodError from zod/v4/core for compatibility with both zod and zod/mini.\n * instanceof $ZodError checks work in both variants.\n */\nexport class ZodvexDecodeError extends $ZodError {\n readonly functionPath: string\n readonly wireData: unknown\n\n constructor(functionPath: string, issues: $ZodIssue[], wireData: unknown) {\n super(issues)\n this.functionPath = functionPath\n this.wireData = wireData\n this.name = 'ZodvexDecodeError'\n }\n}\n\n/**\n * Creates shared encode/decode helpers bound to a zodvex registry.\n *\n * These are the core primitives used by all codec boundary implementations:\n * - `encodeArgs`: runtime types -> wire format (e.g., Date -> timestamp number)\n * - `decodeResult`: wire format -> runtime types (e.g., timestamp number -> Date)\n *\n * Both look up the function reference in the registry to find the appropriate\n * Zod schema, then apply the codec transform. Functions not in the registry\n * (or without the relevant schema) pass through unchanged.\n *\n * @param registry - A map of function paths to `{ args?, returns? }` Zod schemas.\n * Typically generated by zodvex codegen into `_zodvex/api.ts`.\n * @param options - Optional configuration for decode error behavior.\n */\nexport function createBoundaryHelpers(registry: AnyRegistry, options?: BoundaryHelpersOptions) {\n const onDecodeError = options?.onDecodeError ?? 'warn'\n const warnedPaths = new Set<string>()\n\n /**\n * Encode args from runtime types to wire format.\n *\n * Uses `safeEncode` (not raw `z.encode`) to normalize codec-internal\n * error paths in ZodErrors, then strips undefined values for Convex\n * serialization compatibility.\n *\n * Passthrough when:\n * - args is null/undefined\n * - function is not in the registry\n * - registry entry has no args schema\n */\n function encodeArgs(ref: FunctionReference<any, any, any, any>, args: any): any {\n if (args == null) return args\n const path = resolveFunctionPath(ref)\n const entry = registry[path]\n if (!entry?.args) {\n if (entry === undefined && !warnedPaths.has(path)) {\n warnedPaths.add(path)\n console.debug(\n `[zodvex] No registry entry for \"${path}\" — args will not be codec-encoded. ` +\n 'If this function uses zodvex wrappers, run `zodvex generate` to update the registry.'\n )\n }\n return args\n }\n return stripUndefined(safeEncode(entry.args, args))\n }\n\n /**\n * Decode a wire result back to runtime types.\n *\n * Uses `.safeParse()` to decode. On failure:\n * - 'warn' (default): logs warning, returns raw wireResult\n * - 'throw': throws ZodvexDecodeError (extends z.ZodError) // zod-ok\n *\n * Passthrough when:\n * - function is not in the registry\n * - registry entry has no returns schema\n */\n function decodeResult(ref: FunctionReference<any, any, any, any>, wireResult: any): any {\n const path = resolveFunctionPath(ref)\n const entry = registry[path]\n if (!entry?.returns) return wireResult\n\n const result = safeParse(entry.returns, wireResult)\n if (result.success) return result.data\n\n if (onDecodeError === 'throw') {\n throw new ZodvexDecodeError(path, result.error.issues, wireResult)\n }\n\n // Default: warn and return raw wire data\n const preview = JSON.stringify(wireResult)\n const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview\n console.warn(\n `[zodvex] Decode failed for ${path}: ${result.error.issues.map((i: $ZodIssue) => `${i.path.join('.')}: ${i.message}`).join(', ')}. Returning raw wire data. Preview: ${truncated}`\n )\n return wireResult\n }\n\n return { encodeArgs, decodeResult }\n}\n\nexport type BoundaryHelpers = ReturnType<typeof createBoundaryHelpers>\n","/**\n * IDs + registry for Convex + Zod v4\n */\n\nimport type { GenericId } from 'convex/values'\nimport { z } from 'zod'\nimport type { $ZodType } from './zod-core'\n\n// Simple registry for metadata\nconst metadata = new WeakMap<$ZodType, any>()\n\nexport const registryHelpers = {\n getMetadata: (type: $ZodType) => metadata.get(type),\n setMetadata: (type: $ZodType, meta: any) => metadata.set(type, meta)\n}\n\n/**\n * Create a Zod validator for a Convex Id\n *\n * Compatible with AI SDK and other tools that don't support transforms.\n * Uses type-level branding instead of runtime transforms for GenericId<T> compatibility.\n *\n * @deprecated Use `zx.id()` instead for consistent naming with other zodvex helpers.\n * ```typescript\n * import { zx } from 'zodvex'\n * zx.id('users') // instead of zid('users')\n * ```\n *\n * @param tableName - The Convex table name for this ID\n * @returns A Zod string validator typed as GenericId<TableName>\n */\nexport function zid<TableName extends string>(\n tableName: TableName\n): $ZodType<GenericId<TableName>> & { _tableName: TableName } {\n // Create base string validator with refinement (no transform or brand)\n const baseSchema = z.string().check(\n z.refine(val => typeof val === 'string' && val.length > 0, {\n message: `Invalid ID for table \"${tableName}\"`\n }),\n // Add a human-readable marker for client-side introspection utilities\n // used in apps/native (e.g., to detect relationship fields in dynamic forms).\n z.describe(`convexId:${tableName}`)\n )\n\n // Store metadata for registry lookup so mapping can convert to v.id(tableName)\n registryHelpers.setMetadata(baseSchema, {\n isConvexId: true,\n tableName\n })\n\n // Add the tableName property for type-level detection\n const branded = baseSchema as any\n branded._tableName = tableName\n\n // Type assertion provides GenericId<TableName> typing without runtime transform\n // This maintains type safety while being compatible with AI SDK and similar tools\n return branded as $ZodType<GenericId<TableName>> & { _tableName: TableName }\n}\n\nexport type Zid<TableName extends string> = ReturnType<typeof zid<TableName>>\n","import { $ZodObject } from '../zod-core'\n\nexport function getObjectShape(obj: any): Record<string, any> {\n if (obj instanceof $ZodObject) {\n return obj._zod.def.shape as Record<string, any>\n }\n if (obj && typeof obj === 'object' && typeof obj.shape === 'object') {\n return obj.shape as Record<string, any>\n }\n return {}\n}\n","import type { GenericValidator, Validator } from 'convex/values'\nimport { v } from 'convex/values'\nimport { $ZodEnum, type $ZodType } from '../../zod-core'\n\n// Helper: Convert Zod enum types to Convex validators\nexport function convertEnumType(actualValidator: $ZodEnum): GenericValidator {\n const entries = actualValidator._zod.def.entries\n const options = Object.keys(entries)\n if (options && Array.isArray(options) && options.length > 0) {\n // Filter out undefined/null and convert to Convex validators\n const validLiterals = options\n .filter((opt: any) => opt !== undefined && opt !== null)\n .map((opt: any) => v.literal(opt))\n\n if (validLiterals.length === 1) {\n const [first] = validLiterals\n return first as Validator<any, 'required', any>\n } else if (validLiterals.length >= 2) {\n const [first, second, ...rest] = validLiterals\n return v.union(\n first as Validator<any, 'required', any>,\n second as Validator<any, 'required', any>,\n ...rest\n )\n } else {\n return v.any()\n }\n } else {\n return v.any()\n }\n}\n","import type { GenericValidator } from 'convex/values'\nimport { v } from 'convex/values'\nimport { $ZodNullable, $ZodOptional, $ZodType } from '../../zod-core'\n\n// Helper: Convert Zod nullable types to Convex validators\nexport function convertNullableType(\n actualValidator: $ZodNullable,\n visited: Set<$ZodType>,\n zodToConvexInternal: (schema: $ZodType, visited: Set<$ZodType>) => any\n): { validator: GenericValidator; isOptional: boolean } {\n const innerSchema = actualValidator._zod.def.innerType\n if (innerSchema && innerSchema instanceof $ZodType) {\n // Check if the inner schema is optional\n if (innerSchema instanceof $ZodOptional) {\n // For nullable(optional(T)), we want optional(union(T, null))\n const innerInnerSchema = innerSchema._zod.def.innerType\n const innerInnerValidator = zodToConvexInternal(innerInnerSchema, visited)\n return {\n validator: v.union(innerInnerValidator, v.null()),\n isOptional: true // Mark as optional so it gets wrapped later\n }\n } else {\n const innerValidator = zodToConvexInternal(innerSchema, visited)\n return {\n validator: v.union(innerValidator, v.null()),\n isOptional: false\n }\n }\n } else {\n return {\n validator: v.any(),\n isOptional: false\n }\n }\n}\n","import type { GenericValidator } from 'convex/values'\nimport { v } from 'convex/values'\nimport { $ZodDefault, $ZodOptional, $ZodRecord, $ZodType } from '../../zod-core'\n\n// Helper: Convert Zod record types to Convex validators\nexport function convertRecordType(\n actualValidator: $ZodRecord,\n visited: Set<$ZodType>,\n zodToConvexInternal: (schema: $ZodType, visited: Set<$ZodType>) => any\n): GenericValidator {\n // $ZodRecord._zod.def has keyType and valueType\n let valueType: $ZodType | undefined = actualValidator._zod.def.valueType\n\n // If valueType is undefined, fall back to keyType (single-argument z.record() form)\n if (!valueType) {\n valueType = actualValidator._zod.def.keyType\n }\n\n if (valueType && valueType instanceof $ZodType) {\n // First check if the Zod value type is optional before conversion\n const isZodOptional =\n valueType instanceof $ZodOptional ||\n valueType instanceof $ZodDefault ||\n (valueType instanceof $ZodDefault && valueType._zod.def.innerType instanceof $ZodOptional)\n\n if (isZodOptional) {\n // For optional record values, we need to handle this specially\n let innerType: any\n let recordDefaultValue: any = undefined\n let recordHasDefault = false\n\n if (valueType instanceof $ZodDefault) {\n // Handle ZodDefault wrapper\n recordHasDefault = true\n recordDefaultValue = valueType._zod.def.defaultValue\n const innerFromDefault = valueType._zod.def.innerType\n if (innerFromDefault instanceof $ZodOptional) {\n innerType = innerFromDefault._zod.def.innerType\n } else {\n innerType = innerFromDefault\n }\n } else if (valueType instanceof $ZodOptional) {\n // Direct ZodOptional\n innerType = valueType._zod.def.innerType\n } else {\n // Shouldn't happen based on isZodOptional check\n innerType = valueType\n }\n\n // Convert the inner type to Convex and wrap in union with null\n const innerConvex = zodToConvexInternal(innerType, visited)\n const unionValidator = v.union(innerConvex, v.null())\n\n // Add default metadata if present\n if (recordHasDefault) {\n ;(unionValidator as any)._zodDefault = recordDefaultValue\n }\n\n return v.record(v.string(), unionValidator)\n } else {\n // Non-optional values can be converted normally\n return v.record(v.string(), zodToConvexInternal(valueType, visited))\n }\n } else {\n return v.record(v.string(), v.any())\n }\n}\n","import type { GenericValidator, Validator } from 'convex/values'\nimport { v } from 'convex/values'\nimport { $ZodDiscriminatedUnion, type $ZodType, $ZodUnion } from '../../zod-core'\n\n// Helper: Convert Zod discriminated union types to Convex validators\nexport function convertDiscriminatedUnionType(\n actualValidator: $ZodType,\n visited: Set<$ZodType>,\n zodToConvexInternal: (schema: $ZodType, visited: Set<$ZodType>) => any\n): GenericValidator {\n const options =\n actualValidator instanceof $ZodDiscriminatedUnion\n ? actualValidator._zod.def.options\n : // cast: fallback for non-standard discriminated union variants\n (actualValidator as any)._zod?.def?.options\n if (options) {\n const opts = Array.isArray(options) ? options : Array.from(options)\n if (opts.length >= 2) {\n // IMPORTANT: Create a new visited set for each union member to prevent false circular\n // reference detection. The same schema can legitimately appear in multiple union branches.\n const convexOptions = opts.map((opt: any) => {\n const branchVisited = new Set(visited)\n return zodToConvexInternal(opt, branchVisited)\n }) as Validator<any, 'required', any>[]\n const [first, second, ...rest] = convexOptions\n return v.union(\n first as Validator<any, 'required', any>,\n second as Validator<any, 'required', any>,\n ...rest\n )\n } else {\n return v.any()\n }\n } else {\n return v.any()\n }\n}\n\n// Helper: Convert Zod union types to Convex validators\nexport function convertUnionType(\n actualValidator: $ZodUnion,\n visited: Set<$ZodType>,\n zodToConvexInternal: (schema: $ZodType, visited: Set<$ZodType>) => any\n): GenericValidator {\n const options = actualValidator._zod.def.options\n if (options && Array.isArray(options) && options.length > 0) {\n if (options.length === 1) {\n return zodToConvexInternal(options[0], visited)\n } else {\n // Convert each option recursively\n // IMPORTANT: Create a new visited set for each union member to prevent false circular\n // reference detection. The same schema can legitimately appear in multiple union branches.\n // However, we do want to preserve the parent visited set to catch actual circular refs\n // that involve the union itself.\n const convexOptions = options.map((opt: any) => {\n // Create a new Set that includes the parent's visited schemas but won't pollute it\n const branchVisited = new Set(visited)\n return zodToConvexInternal(opt, branchVisited)\n }) as Validator<any, 'required', any>[]\n if (convexOptions.length >= 2) {\n const [first, second, ...rest] = convexOptions\n return v.union(\n first as Validator<any, 'required', any>,\n second as Validator<any, 'required', any>,\n ...rest\n )\n } else {\n return v.any()\n }\n }\n } else {\n return v.any()\n }\n}\n","import { v } from 'convex/values'\nimport { registryHelpers, type Zid } from '../ids'\nimport { getObjectShape } from '../schema/objectShape'\nimport { $ZodType } from '../zod-core'\n\n// Helper to check if a schema is a Zid\nexport function isZid<T extends string>(schema: $ZodType): schema is Zid<T> {\n // Check our metadata registry for ConvexId marker\n const metadata = registryHelpers.getMetadata(schema)\n return (\n metadata?.isConvexId === true && metadata?.tableName && typeof metadata.tableName === 'string'\n )\n}\n\n// union helpers\nexport function makeUnion(members: any[]): any {\n const nonNull = members.filter(Boolean)\n if (nonNull.length === 0) return v.any()\n if (nonNull.length === 1) return nonNull[0]\n return v.union(nonNull[0], nonNull[1], ...nonNull.slice(2))\n}\n\nexport { getObjectShape }\n","import type { GenericValidator, PropertyValidators } from 'convex/values'\nimport { v } from 'convex/values'\nimport { registryHelpers } from '../ids'\nimport {\n $ZodArray,\n $ZodCodec,\n $ZodDefault,\n $ZodEnum,\n $ZodLazy,\n $ZodLiteral,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodRecord,\n type $ZodShape,\n $ZodTuple,\n $ZodType,\n $ZodUnion\n} from '../zod-core'\nimport {\n convertDiscriminatedUnionType,\n convertEnumType,\n convertNullableType,\n convertRecordType,\n convertUnionType\n} from './handlers'\nimport type {\n ConvexValidatorFromZod,\n ConvexValidatorFromZodFieldsAuto,\n ZodValidator\n} from './types'\nimport { isZid } from './utils'\n\n// Module-scoped cache: same Zod schema instance → same Convex validator.\n// Avoids redundant allocations when the same schema is converted across\n// multiple function registrations or table definitions.\nconst convexValidatorCache = new WeakMap<$ZodType, GenericValidator>()\n\n// Internal conversion function using ZodType with def.type detection\nfunction zodToConvexInternal<Z extends $ZodType>(\n zodValidator: Z,\n visited: Set<$ZodType> = new Set()\n): ConvexValidatorFromZod<Z, 'required'> {\n // Guard against undefined/null validators (can happen with { field: undefined } in args)\n if (!zodValidator) {\n return v.any() as ConvexValidatorFromZod<Z, 'required'>\n }\n\n // Return cached result if this exact Zod instance was already converted\n const cached = convexValidatorCache.get(zodValidator)\n if (cached) {\n return cached as ConvexValidatorFromZod<Z, 'required'>\n }\n\n // Detect circular references to prevent infinite recursion\n if (visited.has(zodValidator)) {\n return v.any() as ConvexValidatorFromZod<Z, 'required'>\n }\n visited.add(zodValidator)\n\n // Check for default and optional wrappers\n let actualValidator = zodValidator\n let isOptional = false\n let defaultValue: any = undefined\n let hasDefault = false\n\n // Handle ZodDefault (which wraps ZodOptional when using .optional().default())\n if (zodValidator instanceof $ZodDefault) {\n hasDefault = true\n defaultValue = zodValidator._zod.def.defaultValue\n actualValidator = zodValidator._zod.def.innerType as Z\n }\n\n // Check for optional (may be wrapped inside ZodDefault)\n if (actualValidator instanceof $ZodOptional) {\n isOptional = true\n actualValidator = actualValidator._zod.def.innerType as Z\n\n // If the unwrapped type is ZodDefault, handle it here\n if (actualValidator instanceof $ZodDefault) {\n hasDefault = true\n defaultValue = actualValidator._zod.def.defaultValue\n actualValidator = actualValidator._zod.def.innerType as Z\n }\n }\n\n let convexValidator: GenericValidator\n\n // Check for Zid first (special case)\n if (isZid(actualValidator)) {\n const metadata = registryHelpers.getMetadata(actualValidator)\n const tableName = metadata?.tableName || 'unknown'\n convexValidator = v.id(tableName)\n } else {\n // Use def.type for robust, performant type detection instead of instanceof checks.\n // Rationale:\n // 1. Performance: Single switch statement vs. cascading instanceof checks\n // 2. Completeness: def.type covers ALL Zod variants including formats (email, url, uuid, etc.)\n // 3. Future-proof: Zod's internal structure is stable; instanceof checks can miss custom types\n // 4. Precision: def.type distinguishes between semantically different types (date vs number)\n // This private API access is intentional and necessary for comprehensive type coverage.\n // cast: switch handles more defType values than $ZodTypeDef types (e.g. discriminatedUnion)\n const defType = actualValidator._zod.def.type as string\n\n switch (defType) {\n case 'string':\n // This catches ZodString and ALL string format types (email, url, uuid, etc.)\n convexValidator = v.string()\n break\n case 'number':\n convexValidator = v.float64()\n break\n case 'bigint':\n convexValidator = v.int64()\n break\n case 'boolean':\n convexValidator = v.boolean()\n break\n case 'date':\n // LEGACY: Maps z.date() to v.float64() for backwards compatibility in type inference.\n // However, z.date() does NOT work at runtime because:\n // 1. z.date() produces Date objects, not numbers\n // 2. Convex rejects Date objects as non-serializable\n // 3. z.encode() on z.date() returns a Date, not a timestamp\n // Use zx.date() instead, which provides proper Date ↔ timestamp codec.\n // The wrappers and convexCodec will throw if z.date() is used.\n convexValidator = v.float64()\n break\n case 'null':\n convexValidator = v.null()\n break\n case 'nan':\n convexValidator = v.float64()\n break\n case 'array': {\n if (actualValidator instanceof $ZodArray) {\n const element = actualValidator._zod.def.element\n convexValidator = v.array(zodToConvexInternal(element, visited))\n } else {\n convexValidator = v.array(v.any())\n }\n break\n }\n case 'object': {\n if (actualValidator instanceof $ZodObject) {\n const shape = actualValidator._zod.def.shape\n const convexShape: PropertyValidators = {}\n for (const [key, value] of Object.entries(shape)) {\n if (value && value instanceof $ZodType) {\n convexShape[key] = zodToConvexInternal(value, visited)\n }\n }\n convexValidator = v.object(convexShape)\n } else {\n convexValidator = v.object({})\n }\n break\n }\n case 'union': {\n if (actualValidator instanceof $ZodUnion) {\n convexValidator = convertUnionType(actualValidator, visited, zodToConvexInternal)\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'discriminatedUnion': {\n convexValidator = convertDiscriminatedUnionType(\n actualValidator,\n visited,\n zodToConvexInternal\n )\n break\n }\n case 'literal': {\n if (actualValidator instanceof $ZodLiteral) {\n const literalValues = actualValidator._zod.def.values\n const firstValue = literalValues.values().next().value\n if (firstValue !== undefined && firstValue !== null) {\n convexValidator = v.literal(firstValue)\n } else {\n convexValidator = v.any()\n }\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'enum': {\n if (actualValidator instanceof $ZodEnum) {\n convexValidator = convertEnumType(actualValidator)\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'record': {\n if (actualValidator instanceof $ZodRecord) {\n convexValidator = convertRecordType(actualValidator, visited, zodToConvexInternal)\n } else {\n convexValidator = v.record(v.string(), v.any())\n }\n break\n }\n case 'transform':\n case 'pipe': {\n // Check for native Zod v4 codec first (z.codec())\n // Codecs have def.type='pipe' but are specifically for bidirectional transforms\n // Use the input schema (wire format) for Convex validation\n if (actualValidator instanceof $ZodCodec) {\n const inputSchema = actualValidator._zod.def.in\n if (inputSchema && inputSchema instanceof $ZodType) {\n convexValidator = zodToConvexInternal(inputSchema, visited)\n } else {\n convexValidator = v.any()\n }\n } else {\n // Check for brand metadata\n const metadata = registryHelpers.getMetadata(actualValidator)\n if (metadata?.brand && metadata?.originalSchema) {\n // For branded types created by our zBrand function, use the original schema\n convexValidator = zodToConvexInternal(metadata.originalSchema, visited)\n } else {\n // Non-codec transform - extract input schema but warn\n // cast: no instanceof guard available for generic pipe/transform\n const inputSchema = (actualValidator as any)._zod?.def?.in\n if (inputSchema && inputSchema instanceof $ZodType) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n '[zodvex] z.transform() detected. Using input schema for Convex validation.\\n' +\n 'Transforms are unidirectional - they work for parsing but not encoding.\\n' +\n 'For bidirectional transforms, use zx.codec() instead.'\n )\n }\n convexValidator = zodToConvexInternal(inputSchema, visited)\n } else {\n convexValidator = v.any()\n }\n }\n }\n break\n }\n case 'nullable': {\n if (actualValidator instanceof $ZodNullable) {\n const result = convertNullableType(actualValidator, visited, zodToConvexInternal)\n convexValidator = result.validator\n if (result.isOptional) {\n isOptional = true\n }\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'tuple': {\n // Handle tuple types as objects with numeric keys\n if (actualValidator instanceof $ZodTuple) {\n const items = actualValidator._zod.def.items\n if (items && items.length > 0) {\n const convexShape: PropertyValidators = {}\n items.forEach((item, index) => {\n convexShape[`_${index}`] = zodToConvexInternal(item, visited)\n })\n convexValidator = v.object(convexShape)\n } else {\n convexValidator = v.object({})\n }\n } else {\n convexValidator = v.object({})\n }\n break\n }\n case 'lazy': {\n // Handle lazy schemas by resolving them\n // Circular references are protected by the visited set check at function start\n if (actualValidator instanceof $ZodLazy) {\n try {\n const getter = actualValidator._zod.def.getter\n if (getter) {\n const resolvedSchema = getter()\n if (resolvedSchema && resolvedSchema instanceof $ZodType) {\n convexValidator = zodToConvexInternal(resolvedSchema, visited)\n } else {\n convexValidator = v.any()\n }\n } else {\n convexValidator = v.any()\n }\n } catch {\n // If resolution fails, fall back to 'any'\n convexValidator = v.any()\n }\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'any':\n // Handle z.any() directly\n convexValidator = v.any()\n break\n case 'unknown':\n // Handle z.unknown() as any\n convexValidator = v.any()\n break\n case 'undefined':\n case 'void':\n case 'never':\n // These types don't have good Convex equivalents\n convexValidator = v.any()\n break\n case 'intersection':\n // Can't properly handle intersections\n convexValidator = v.any()\n break\n case 'optional': {\n // Fallback for optional types that weren't caught by the instanceof check above.\n // cast: no instanceof guard — this handles edge cases where defType='optional'\n // but the schema isn't a $ZodOptional instance (e.g. pipes wrapped with .optional())\n const innerType = (actualValidator as any)._zod?.def?.innerType\n if (innerType && innerType instanceof $ZodType) {\n convexValidator = zodToConvexInternal(innerType, visited)\n isOptional = true\n } else {\n convexValidator = v.any()\n isOptional = true\n }\n break\n }\n default:\n // For any unrecognized def.type, return v.any()\n // No instanceof fallbacks - keep it simple and performant\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[zodvex] Unrecognized Zod type \"${defType}\" encountered. Falling back to v.any().`,\n 'Schema:',\n actualValidator\n )\n }\n convexValidator = v.any()\n break\n }\n }\n\n // For optional or default fields, always use v.optional()\n const finalValidator = isOptional || hasDefault ? v.optional(convexValidator) : convexValidator\n\n // Add metadata if there's a default value\n if (hasDefault && typeof finalValidator === 'object' && finalValidator !== null) {\n ;(finalValidator as any)._zodDefault = defaultValue\n }\n\n // Cache the result so the same Zod instance returns the same Convex validator\n convexValidatorCache.set(zodValidator, finalValidator)\n\n return finalValidator as ConvexValidatorFromZod<Z, 'required'>\n}\n\nexport function zodToConvex<Z extends $ZodType | ZodValidator>(\n zod: Z\n): Z extends $ZodType\n ? ConvexValidatorFromZod<Z, 'required'>\n : Z extends ZodValidator\n ? ConvexValidatorFromZodFieldsAuto<Z>\n : never {\n if (typeof zod === 'object' && zod !== null && !(zod instanceof $ZodType)) {\n return zodToConvexFields(zod as ZodValidator) as any\n }\n\n return zodToConvexInternal(zod as $ZodType) as any\n}\n\nexport function zodToConvexFields<Z extends $ZodShape>(\n zod: Z\n): ConvexValidatorFromZodFieldsAuto<Z> {\n // If it's a ZodObject, extract the shape\n const fields = zod instanceof $ZodObject ? zod._zod.def.shape : zod\n\n // Build the result object directly to preserve types\n const result: any = {}\n for (const [key, value] of Object.entries(fields)) {\n result[key] = zodToConvexInternal(value as $ZodType)\n }\n\n return result as ConvexValidatorFromZodFieldsAuto<Z>\n}\n","import { z } from 'zod'\nimport { $ZodDate, $ZodType, globalRegistry } from './zod-core'\n\n// ============================================================================\n// JSON Schema Override Support\n// ============================================================================\n// Zod's toJSONSchema doesn't support transforms, brands, and other \"unrepresentable\"\n// types by default. This module provides overrides for zodvex-managed types\n// so they can be used with AI SDKs and other JSON Schema-based tools.\n\n/**\n * Checks if a schema is a zid (Convex ID) schema by looking at its description.\n * zid schemas are marked with \"convexId:{tableName}\" in their description.\n */\nexport function isZidSchema(schema: $ZodType): boolean {\n const description = globalRegistry.get(schema)?.description\n return typeof description === 'string' && description.startsWith('convexId:')\n}\n\n/**\n * Extracts the table name from a zid schema's description.\n * Returns undefined if not a zid schema.\n */\nexport function getZidTableName(schema: $ZodType): string | undefined {\n const description = globalRegistry.get(schema)?.description\n if (typeof description === 'string' && description.startsWith('convexId:')) {\n return description.slice('convexId:'.length)\n }\n return undefined\n}\n\n/**\n * Context object passed to the JSON Schema override function.\n * Uses 'any' types for compatibility with Zod's internal types.\n */\nexport interface JSONSchemaOverrideContext {\n zodSchema: any // Zod's internal $ZodTypes\n jsonSchema: any // Zod's JSONSchema.BaseSchema\n}\n\n/**\n * Override function for z.toJSONSchema that handles zodvex-managed types.\n *\n * Handles:\n * - zx.id() schemas: Converts to { type: \"string\" } with convexId format\n * - zx.date(): Converts to { type: \"string\", format: \"date-time\" }\n *\n * @example\n * ```ts\n * import { z } from 'zod'\n * import { zx, zodvexJSONSchemaOverride } from 'zodvex'\n *\n * const schema = z.object({\n * userId: zx.id('users'),\n * name: z.string()\n * })\n *\n * const jsonSchema = z.toJSONSchema(schema, {\n * unrepresentable: 'any',\n * override: zodvexJSONSchemaOverride\n * })\n * // => { type: \"object\", properties: { userId: { type: \"string\" }, name: { type: \"string\" } } }\n * ```\n */\nexport function zodvexJSONSchemaOverride(ctx: JSONSchemaOverrideContext): void {\n const { zodSchema, jsonSchema } = ctx\n\n // Handle zid schemas (transforms with convexId description)\n if (isZidSchema(zodSchema)) {\n const tableName = getZidTableName(zodSchema)\n // Set our properties - don't clear existing ones set by user overrides\n // When unrepresentable: 'any', Zod already gives us {} so no clearing needed\n jsonSchema.type = 'string'\n if (tableName) {\n jsonSchema.format = `convex-id:${tableName}`\n }\n // Preserve the description from .describe() - this is what the LLM sees\n // Use globalRegistry for mini compatibility (zod/mini lacks the .description getter)\n const schemaDescription = globalRegistry.get(zodSchema)?.description\n if (schemaDescription) {\n jsonSchema.description = schemaDescription\n }\n return\n }\n\n // Handle z.date() - convert to ISO 8601 string format\n // Zod v4 passes real schema instances here (ZodDate has `type === 'date'`).\n if (zodSchema instanceof $ZodDate || zodSchema._zod.def.type === 'date') {\n jsonSchema.type = 'string'\n jsonSchema.format = 'date-time'\n return\n }\n}\n\n/**\n * Composes multiple JSON Schema override functions into one.\n * Overrides run in order - first override runs first.\n *\n * @example\n * ```ts\n * import { composeOverrides, zodvexJSONSchemaOverride } from 'zodvex'\n *\n * const myOverride = (ctx) => {\n * if (ctx.zodSchema.description?.startsWith('myType:')) {\n * ctx.jsonSchema.type = 'string'\n * ctx.jsonSchema.format = 'my-format'\n * }\n * }\n *\n * // User's override runs first, then zodvex's\n * z.toJSONSchema(schema, {\n * unrepresentable: 'any',\n * override: composeOverrides(myOverride, zodvexJSONSchemaOverride)\n * })\n * ```\n */\nexport function composeOverrides(\n ...overrides: Array<((ctx: JSONSchemaOverrideContext) => void) | undefined>\n): (ctx: JSONSchemaOverrideContext) => void {\n return (ctx: JSONSchemaOverrideContext) => {\n for (const override of overrides) {\n override?.(ctx)\n }\n }\n}\n\n/**\n * Options for toJSONSchema, matching Zod's interface.\n */\nexport interface ToJSONSchemaOptions {\n target?: 'draft-4' | 'draft-7' | 'draft-2020-12' | 'openapi-3.0'\n unrepresentable?: 'throw' | 'any'\n cycles?: 'ref' | 'throw'\n reused?: 'ref' | 'inline'\n io?: 'input' | 'output'\n override?: (ctx: JSONSchemaOverrideContext) => void\n}\n\n/**\n * Converts a Zod schema to JSON Schema with zodvex-aware overrides.\n *\n * This is a convenience wrapper around z.toJSONSchema that automatically\n * handles zodvex-managed types like zx.id() and zx.date().\n *\n * @example\n * ```ts\n * import { zx, toJSONSchema } from 'zodvex'\n *\n * const schema = z.object({\n * userId: zx.id('users'),\n * createdAt: zx.date(),\n * name: z.string()\n * })\n *\n * const jsonSchema = toJSONSchema(schema)\n * // Works with AI SDK's generateObject, etc.\n * ```\n */\nexport function toJSONSchema<T extends $ZodType>(\n schema: T,\n options?: ToJSONSchemaOptions\n): Record<string, any> {\n const userOverride = options?.override\n\n return z.toJSONSchema(schema, {\n ...options,\n // Default to 'any' so transforms don't throw\n unrepresentable: options?.unrepresentable ?? 'any',\n // Chain our override with user's override\n override: ctx => {\n zodvexJSONSchemaOverride(ctx)\n userOverride?.(ctx)\n }\n })\n}\n","import { z } from 'zod'\nimport type { $ZodType } from './zod-core'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Result type for mutations that return data on success.\n */\nexport type MutationResult<T> = { success: true; data: T } | { success: false; error: string }\n\n/**\n * Result type for mutations that don't return data (void operations).\n */\nexport type VoidMutationResult = { success: true } | { success: false; error: string }\n\n/**\n * Error structure for form validation results.\n */\nexport type FormError = {\n formErrors: string[]\n fieldErrors: Record<string, string[]>\n}\n\n/**\n * Result type for form submissions with field-level error support.\n * Preserves submitted data on failure for form re-population.\n */\nexport type FormResult<TData> =\n | { success: true; data: TData }\n | { success: false; data: TData; error: FormError }\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create a success result with data.\n * @example success({ id: '123' })\n */\nexport const success = <T>(data: T) => ({ success: true, data }) as const\n\n/**\n * Create a failure result with an error message.\n * @example failure('Not found')\n */\nexport const failure = (error: string) => ({ success: false, error }) as const\n\n/**\n * Create a void success result (no data).\n * @example ok()\n */\nexport const ok = () => ({ success: true }) as const\n\n/**\n * Create a form success result with data.\n * @example formSuccess({ email: 'user@example.com' })\n */\nexport const formSuccess = <T>(data: T) => ({ success: true, data }) as const\n\n/**\n * Create a form failure result with data and errors.\n * @example formFailure({ email: 'bad' }, { formErrors: [], fieldErrors: { email: ['Invalid'] } })\n */\nexport const formFailure = <T>(data: T, error: FormError) =>\n ({ success: false, data, error }) as const\n\n// ============================================================================\n// Zod Schemas for `returns` validation\n// ============================================================================\n\n/**\n * Zod schema for MutationResult<T>.\n * Use in `returns` option to validate mutation responses.\n * @example zMutationResult(z.object({ id: zid('users') }))\n */\nexport const zMutationResult = <T extends $ZodType>(dataSchema: T) =>\n z.discriminatedUnion('success', [\n z.object({ success: z.literal(true), data: dataSchema }),\n z.object({ success: z.literal(false), error: z.string() })\n ])\n\n/**\n * Zod schema for VoidMutationResult.\n * Use in `returns` option for void mutations.\n * @example returns: zVoidMutationResult\n */\nexport const zVoidMutationResult = z.discriminatedUnion('success', [\n z.object({ success: z.literal(true) }),\n z.object({ success: z.literal(false), error: z.string() })\n])\n\n/**\n * Zod schema for FormError.\n */\nexport const zFormError = z.object({\n formErrors: z.array(z.string()),\n fieldErrors: z.record(z.string(), z.array(z.string()))\n})\n\n/**\n * Zod schema for FormResult<T>.\n * Use in `returns` option for form submissions.\n * @example zFormResult(z.object({ email: z.string() }))\n */\nexport const zFormResult = <T extends $ZodType>(dataSchema: T) =>\n z.discriminatedUnion('success', [\n z.object({ success: z.literal(true), data: dataSchema }),\n z.object({ success: z.literal(false), data: dataSchema, error: zFormError })\n ])\n","import { z } from 'zod'\nimport {\n $ZodArray,\n $ZodCodec,\n $ZodDate,\n $ZodDefault,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodRecord,\n $ZodTuple,\n $ZodType,\n $ZodUnion\n} from '../zod-core'\n\n/**\n * @deprecated Use `zx.date()` instead for automatic Date ↔ timestamp conversion.\n */\nexport function mapDateFieldToNumber(field: $ZodType): $ZodType {\n if (field instanceof $ZodDate) {\n return z.number()\n }\n if (field instanceof $ZodOptional && field._zod.def.innerType instanceof $ZodDate) {\n return z.optional(z.number())\n }\n if (field instanceof $ZodNullable && field._zod.def.innerType instanceof $ZodDate) {\n return z.nullable(z.number())\n }\n if (field instanceof $ZodDefault) {\n const inner = field._zod.def.innerType\n if (inner instanceof $ZodDate) {\n return z.optional(z.number())\n }\n }\n return field\n}\n\nfunction containsNativeZodDate(schema: $ZodType): boolean {\n if (schema instanceof $ZodDate) return true\n if (schema instanceof $ZodCodec) return false\n\n if (\n schema instanceof $ZodOptional ||\n schema instanceof $ZodNullable ||\n schema instanceof $ZodDefault\n ) {\n return containsNativeZodDate(schema._zod.def.innerType)\n }\n\n if (schema instanceof $ZodObject) {\n return Object.values(schema._zod.def.shape).some(field => containsNativeZodDate(field))\n }\n if (schema instanceof $ZodArray) {\n return containsNativeZodDate(schema._zod.def.element)\n }\n if (schema instanceof $ZodUnion) {\n return schema._zod.def.options.some(opt => containsNativeZodDate(opt))\n }\n if (schema instanceof $ZodRecord) {\n return containsNativeZodDate(schema._zod.def.valueType)\n }\n if (schema instanceof $ZodTuple) {\n const items = schema._zod.def.items\n return items ? items.some(item => containsNativeZodDate(item)) : false\n }\n\n return false\n}\n\nexport function assertNoNativeZodDate(\n schema: $ZodType,\n context: 'args' | 'returns' | 'schema'\n): void {\n if (containsNativeZodDate(schema)) {\n throw new Error(\n `[zodvex] Native z.date() found in ${context}. ` +\n `Convex stores dates as timestamps (numbers), which z.date() cannot parse.\\n\\n` +\n `Fix: Replace z.date() with zx.date()\\n\\n` +\n `Before: { createdAt: z.date() }\\n` +\n `After: { createdAt: zx.date() }\\n\\n` +\n `zx.date() is a codec that handles timestamp ↔ Date conversion automatically.`\n )\n }\n}\n","import { z } from 'zod'\nimport { getObjectShape } from './objectShape'\n\ntype Mask = readonly string[] | Record<string, boolean | 1 | true>\n\n// Type alias — keeps z.ZodObject off {-ending function signature lines (formatter-safe). // zod-ok\ntype AnyZodObject = z.ZodObject<any> // zod-ok\n\nfunction toKeys(mask: Mask): string[] {\n if (Array.isArray(mask)) return mask.map(String)\n return Object.keys(mask).filter(k => !!(mask as any)[k])\n}\n\nexport function pickShape(\n schemaOrShape: AnyZodObject | Record<string, any>,\n mask: Mask\n): Record<string, any> {\n const keys = toKeys(mask)\n const shape =\n schemaOrShape instanceof z.ZodObject ? getObjectShape(schemaOrShape) : schemaOrShape || {}\n\n const out: Record<string, any> = {}\n for (const k of keys) {\n if (k in shape) out[k] = (shape as any)[k]\n }\n return out\n}\n\nexport function safePick(schema: AnyZodObject, mask: Mask): AnyZodObject {\n return z.object(pickShape(schema, mask))\n}\n\nexport function safeOmit(schema: AnyZodObject, mask: Mask): AnyZodObject {\n const shape = getObjectShape(schema)\n const omit = new Set(toKeys(mask))\n const keep = Object.keys(shape).filter(k => !omit.has(k))\n const picked = pickShape(schema, keep)\n return z.object(picked)\n}\n","import { z } from 'zod'\nimport { $ZodNullable, $ZodOptional, $ZodType, type input as zinput } from '../zod-core'\n\nexport function returnsAs<R extends $ZodType>() {\n return <T extends zinput<R>>(v: T) => v\n}\n\n/** Wrap in .nullable().optional() using core constructors for zod-mini compat. */\nfunction nullableOptional(schema: $ZodType): $ZodType {\n return new $ZodOptional({\n type: 'optional',\n innerType: new $ZodNullable({ type: 'nullable', innerType: schema })\n }) as any\n}\n\nexport function zPaginated<T extends $ZodType>(item: T) {\n return z.object({\n page: z.array(item),\n isDone: z.boolean(),\n continueCursor: z.string(),\n splitCursor: nullableOptional(z.string()),\n pageStatus: nullableOptional(z.enum(['SplitRecommended', 'SplitRequired']))\n })\n}\n","import { z } from 'zod'\nimport { zodToConvex } from './mapping'\nimport { assertNoNativeZodDate } from './schema/dateGuards'\nimport { stripUndefined } from './stripUndefined'\nimport { type ZodvexCodec } from './types'\nimport {\n $ZodObject,\n $ZodOptional,\n $ZodType,\n encode,\n parse,\n type infer as zinfer,\n type input as zinput,\n type output as zoutput\n} from './zod-core'\n\n// Re-export ZodvexCodec type for convenience\nexport { type ZodvexCodec } from './types'\n\n/** @deprecated Use `initZodvex` or `decodeDoc`/`encodeDoc` instead. Will be removed in a future release. */\nexport type ConvexCodec<T> = {\n validator: any\n encode: (value: T) => any\n decode: (value: any) => T\n pick: <K extends keyof T>(keys: K[]) => ConvexCodec<Pick<T, K>>\n}\n\n/** @deprecated Use `initZodvex` or `decodeDoc`/`encodeDoc` instead. Will be removed in a future release. */\nexport function convexCodec<T>(schema: $ZodType<T>): ConvexCodec<T> {\n // Fail fast if z.date() is used - it won't encode correctly\n // Use zx.date() instead for Date ↔ timestamp conversion\n assertNoNativeZodDate(schema as $ZodType, 'schema')\n\n const validator = zodToConvex(schema)\n\n return {\n validator,\n // Strip undefined to ensure Convex-safe output (Convex rejects explicit undefined)\n encode: (value: T) => stripUndefined(encode(schema, value)),\n decode: (value: any) => parse(schema, value),\n pick: <K extends keyof T>(keys: K[] | Record<K, true>) => {\n if (!(schema instanceof $ZodObject)) {\n throw new Error('pick() can only be called on object schemas')\n }\n // Handle both array and object formats\n // Use manual shape extraction instead of .pick() — not available on zod/mini\n const pickKeys = Array.isArray(keys) ? keys : (Object.keys(keys) as K[])\n const shape = (schema as any)._zod.def.shape\n const pickedShape: Record<string, any> = {}\n for (const k of pickKeys) {\n if (k in shape) pickedShape[k as string] = shape[k as string]\n }\n const pickedSchema = z.object(pickedShape)\n return convexCodec(pickedSchema) as ConvexCodec<Pick<T, K>>\n }\n }\n}\n\n/**\n * Decodes a wire-format document (from Convex DB) to runtime types.\n * Runs Zod codec decode transforms (e.g., timestamp → Date via zx.date()).\n */\nexport function decodeDoc<S extends $ZodType>(schema: S, wireDoc: unknown): zoutput<S> {\n return parse(schema, wireDoc)\n}\n\n/**\n * Encodes a runtime document to wire format (for Convex DB writes).\n * Runs Zod codec encode transforms and strips undefined values.\n */\nexport function encodeDoc<S extends $ZodType>(schema: S, runtimeDoc: zoutput<S>): zinput<S> {\n return stripUndefined(encode(schema, runtimeDoc))\n}\n\n/**\n * Encodes a partial runtime document to wire format (for Convex DB patch operations).\n * Only encodes the fields present in the partial. Uses schema.partial() + z.encode().\n */\nexport function encodePartialDoc<S extends $ZodType>(\n schema: S,\n partial: Partial<zoutput<S>>\n): Partial<zinput<S>> {\n if (!(schema instanceof $ZodObject)) {\n // For non-object schemas (unions, etc.), fall back to full encode\n // Cast needed: Partial<output<S>> is structurally compatible but not assignable to output<S>\n return stripUndefined(encode(schema, partial as zoutput<S>)) as Partial<zinput<S>>\n }\n // Use manual shape wrapping instead of .partial() — not available on zod/mini\n const shape = (schema as any)._zod.def.shape\n const partialShape: Record<string, any> = {}\n for (const [key, value] of Object.entries(shape)) {\n partialShape[key] =\n value instanceof $ZodOptional\n ? value\n : new $ZodOptional({ type: 'optional', innerType: value as any })\n }\n const partialSchema = z.object(partialShape)\n return stripUndefined(encode(partialSchema, partial)) as Partial<zinput<S>>\n}\n\n/**\n * Creates a branded ZodCodec for use with zodvex type inference.\n * Thin wrapper around z.codec() that adds type branding, allowing\n * ConvexValidatorFromZod to extract the wire schema even when the\n * codec is wrapped in a custom type alias.\n *\n * @example\n * ```typescript\n * type MyCodec = ZodvexCodec<z.ZodObject<{ ts: z.ZodNumber }>, z.ZodCustom<Date>> // zod-ok\n *\n * function myCodec(): MyCodec {\n * return zodvexCodec(\n * z.object({ ts: z.number() }),\n * z.custom<Date>(() => true),\n * {\n * decode: (wire) => new Date(wire.ts),\n * encode: (date) => ({ ts: date.getTime() })\n * }\n * )\n * }\n * ```\n */\nexport function zodvexCodec<\n W extends $ZodType,\n R extends $ZodType,\n WO = zoutput<W>,\n RI = zoutput<R>\n>(\n wire: W,\n runtime: R,\n transforms: {\n decode: (wire: WO) => RI\n encode: (runtime: RI) => WO\n }\n): ZodvexCodec<W, R> {\n // Cast transforms to satisfy Zod's internal MaybeAsync typing while keeping our API simple\n return z.codec(wire as any, runtime as any, transforms as any) as unknown as ZodvexCodec<W, R>\n}\n","import {\n zodvexCodec as _zodvexCodec,\n type ConvexCodec,\n convexCodec,\n decodeDoc,\n encodeDoc,\n encodePartialDoc\n} from '../internal/codec'\nimport type { $ZodType, output as zoutput } from '../internal/zod-core'\nimport type { FullZodvexCodec } from '../internal/zx'\n\nexport { type ConvexCodec, convexCodec, decodeDoc, encodeDoc, encodePartialDoc }\n\nexport type ZodvexCodec<Wire extends $ZodType, Runtime extends $ZodType> = FullZodvexCodec<\n Wire,\n Runtime\n>\n\nexport function zodvexCodec<\n W extends $ZodType,\n R extends $ZodType,\n WO = zoutput<W>,\n RI = zoutput<R>\n>(\n wire: W,\n runtime: R,\n transforms: {\n decode: (wire: WO) => RI\n encode: (runtime: RI) => WO\n }\n): ZodvexCodec<W, R> {\n return _zodvexCodec(wire, runtime, transforms) as unknown as ZodvexCodec<W, R>\n}\n","import type { $ZodType } from './zod-core'\n\nconst META_KEY = '__zodvexMeta'\n\nexport type ZodvexFunctionMeta = {\n type: 'function'\n zodArgs?: $ZodType\n zodReturns?: $ZodType\n}\n\nexport type ZodvexModelDefinitionSource = 'shape' | 'schema'\n\nexport type ZodvexModelMeta = {\n type: 'model'\n tableName: string\n definitionSource?: ZodvexModelDefinitionSource\n schemas?: {\n doc: $ZodType\n insert: $ZodType\n update: $ZodType\n docArray: $ZodType\n paginatedDoc: $ZodType\n }\n}\n\nexport type ZodvexMeta = ZodvexFunctionMeta | ZodvexModelMeta\n\nexport function attachMeta(target: object, meta: ZodvexMeta): void {\n Object.defineProperty(target, META_KEY, {\n value: meta,\n enumerable: false,\n writable: false,\n configurable: false\n })\n}\n\nexport function readMeta(target: unknown): ZodvexMeta | undefined {\n if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n return undefined\n }\n return (target as Record<string, unknown>)[META_KEY] as ZodvexMeta | undefined\n}\n","import { readMeta } from '../../internal/meta'\nimport {\n $ZodCodec,\n $ZodCustom,\n $ZodNullable,\n $ZodNumber,\n $ZodOptional,\n $ZodType\n} from '../../internal/zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable layers to find the inner ZodCodec.\n * Returns the codec instance, or undefined if none found.\n * Skips zx.date() (ZodCodec with in=ZodNumber, out=ZodCustom).\n *\n * Used internally by the discovery pipeline to probe schemas for codecs.\n */\nexport function findCodec(schema: $ZodType): $ZodType | undefined {\n let current = schema\n for (let i = 0; i < 10; i++) {\n if (current instanceof $ZodCodec) {\n const isZxDate =\n current._zod.def.in instanceof $ZodNumber && current._zod.def.out instanceof $ZodCustom\n if (isZxDate) return undefined\n return current\n }\n if (current instanceof $ZodOptional || current instanceof $ZodNullable) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return undefined\n}\n\n/**\n * Extracts the inner ZodCodec from a schema, throwing if none is found.\n * The codegen only emits extractCodec() calls for schemas it has verified\n * contain a codec during discovery, so a missing codec is a bug.\n *\n * Used by generated _zodvex/api.ts to extract codec references at runtime.\n */\nexport function extractCodec(schema: $ZodType): $ZodType {\n const codec = findCodec(schema)\n if (!codec) {\n throw new Error('zodvex: extractCodec() found no codec in schema — this is a codegen bug')\n }\n return codec\n}\n\n/**\n * Extracts the zodArgs schema from a zodvex-registered function.\n * Used by generated _zodvex/api.ts to access function-embedded codecs at runtime.\n */\nexport function readFnArgs(fn: unknown): $ZodType {\n const meta = readMeta(fn)\n if (!meta || meta.type !== 'function' || !meta.zodArgs) {\n throw new Error('zodvex: function has no zodArgs metadata')\n }\n return meta.zodArgs as $ZodType\n}\n\n/**\n * Extracts the zodReturns schema from a zodvex-registered function.\n * Used by generated _zodvex/api.ts to access function-embedded codecs at runtime.\n */\nexport function readFnReturns(fn: unknown): $ZodType {\n const meta = readMeta(fn)\n if (!meta || meta.type !== 'function' || !meta.zodReturns) {\n throw new Error('zodvex: function has no zodReturns metadata')\n }\n return meta.zodReturns as $ZodType\n}\n","/**\n * zx - zodvex extended validators\n *\n * A namespace for zodvex-specific validators and codecs that handle\n * Convex wire format transformations. The \"zx\" prefix signals:\n * - \"zodvex\" or \"zod + convex\" extended types\n * - Explicit transformations (not magic)\n * - Discoverable via IDE autocomplete on `zx.`\n *\n * @example\n * ```typescript\n * import { z } from 'zod'\n * import { zx } from 'zodvex'\n *\n * const userShape = {\n * name: z.string(), // Standard Zod\n * createdAt: zx.date(), // zodvex: Date ↔ timestamp\n * teamId: zx.id('teams'), // zodvex: Convex ID\n * }\n * ```\n */\n\nimport type { GenericId } from 'convex/values'\nimport { z } from 'zod'\nimport { zodvexCodec } from './codec'\nimport { registryHelpers } from './ids'\nimport { createSchemaUpdateSchema } from './modelSchemaBundle'\nimport { addSystemFields } from './schemaHelpers'\nimport type { ZodvexCodec } from './types'\nimport {\n type $ZodCustom,\n $ZodNullable,\n type $ZodNumber,\n $ZodOptional,\n type $ZodType,\n $ZodType as $ZodTypeValue,\n type output as zoutput\n} from './zod-core'\n\n/**\n * Date codec type for explicit type annotations\n */\nexport type FullZodvexCodec<W extends $ZodType, R extends $ZodType> = z.ZodCodec<W, R> &\n ZodvexCodec<W, R>\n\nexport type ZxDate = FullZodvexCodec<$ZodNumber, $ZodCustom<Date, Date>>\n\n/**\n * Creates a Date codec that transforms between Date objects and timestamps.\n *\n * Wire format: number (Unix timestamp in milliseconds)\n * Runtime format: Date object\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * createdAt: zx.date(),\n * updatedAt: zx.date().optional(),\n * })\n * ```\n */\nfunction date(): ZxDate {\n return zodvexCodec(\n z.number(), // Wire: timestamp\n z.custom<Date>(val => val instanceof Date, {\n message: 'Expected Date instance'\n }),\n {\n decode: (timestamp: number) => new Date(timestamp),\n encode: (date: Date) => date.getTime()\n }\n ) as unknown as ZxDate\n}\n\n/**\n * ID type for explicit type annotations\n */\nexport type ZxId<TableName extends string> = z.ZodString &\n z.ZodType<GenericId<TableName>> & {\n _tableName: TableName\n }\n\n/**\n * Creates a Convex ID validator for a specific table.\n *\n * Wire format: string (Convex ID)\n * Runtime format: GenericId<TableName> (branded string type)\n *\n * Note: Unlike zx.date(), IDs don't require runtime transformation since\n * GenericId<T> is a branded string type. The branding is purely type-level.\n *\n * @param tableName - The Convex table name for this ID\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * userId: zx.id('users'),\n * teamId: zx.id('teams').optional(),\n * })\n * ```\n */\nfunction id<TableName extends string>(tableName: TableName): ZxId<TableName> {\n // Create base string validator with refinement\n const baseSchema = z.string().check(\n z.refine(val => typeof val === 'string' && val.length > 0, {\n message: `Invalid ID for table \"${tableName}\"`\n }),\n z.describe(`convexId:${tableName}`)\n )\n\n // Store metadata for registry lookup so mapping can convert to v.id(tableName)\n registryHelpers.setMetadata(baseSchema, {\n isConvexId: true,\n tableName\n })\n\n // Add the tableName property for type-level detection\n const branded = baseSchema as any\n branded._tableName = tableName\n\n return branded as ZxId<TableName>\n}\n\n/**\n * Creates a custom codec for transforming between wire and runtime formats.\n *\n * Use this when you need custom transformations beyond the built-in helpers.\n *\n * @param wire - Zod schema for the wire format (stored in Convex)\n * @param runtime - Zod schema for the runtime format (used in code)\n * @param transforms - Encode/decode functions\n *\n * @example\n * ```typescript\n * // Encrypted data codec\n * const encryptedString = zx.codec(\n * z.object({ encrypted: z.string() }), // Wire format\n * z.custom<string>(() => true), // Runtime format\n * {\n * decode: (wire) => decrypt(wire.encrypted),\n * encode: (value) => ({ encrypted: encrypt(value) })\n * }\n * )\n * ```\n */\nfunction codec<W extends $ZodType, R extends $ZodType, WO = zoutput<W>, RI = zoutput<R>>(\n wire: W,\n runtime: R,\n transforms: {\n decode: (wire: WO) => RI\n encode: (runtime: RI) => WO\n }\n): FullZodvexCodec<W, R> {\n return zodvexCodec(wire, runtime, transforms) as unknown as FullZodvexCodec<W, R>\n}\n\n/**\n * Minimal model shape accepted by zx helpers.\n * Both full and slim models satisfy this at runtime.\n */\ntype ZxModelInput = {\n readonly name: string\n readonly fields: Record<string, $ZodType>\n readonly schema?: unknown\n}\n\n/**\n * Per-model caches so repeated `zx.doc(model)` / `zx.base(model)` / etc. calls\n * across call sites share a single Zod schema instance.\n *\n * Caches are keyed on a stable identity that survives chain methods\n * (`.index()`, `.searchIndex()`, `.vectorIndex()`), which return new model\n * objects but preserve `fields` (object slim) and `schema` (union slim) by\n * reference. Keying on the model object would force every chain step to\n * re-allocate.\n *\n * Full models bypass these caches entirely — they carry a pre-built schema\n * bundle, and `zx.*(fullModel)` returns the bundle's schema directly so\n * identity matches `fullModel.schema.{doc,base,...}`.\n *\n * The cache maps are pinned to `globalThis` under a `Symbol.for` registry so\n * multiple bundled copies of this module share state. tsup splits each entry\n * into its own bundle (CLI, codegen, main, server, …), duplicating this file\n * per entry. Without the shared registry, `zx.doc(Model)` in user code\n * (loaded from `dist/index.js`) and `zx.doc(ref)` in codegen (loaded from\n * `dist/cli/index.js`) would write to distinct WeakMaps, producing different\n * instances for the same model — identity matching would silently fail.\n */\nfunction sharedWeakMap(name: string): WeakMap<object, $ZodType> {\n const key = Symbol.for(`zodvex.zx.cache.${name}`)\n const g = globalThis as unknown as Record<symbol, WeakMap<object, $ZodType>>\n const existing = g[key]\n if (existing) return existing\n const created = new WeakMap<object, $ZodType>()\n g[key] = created\n return created\n}\n\nconst baseCache = sharedWeakMap('base')\nconst docCache = sharedWeakMap('doc')\nconst updateCache = sharedWeakMap('update')\nconst docArrayCache = sharedWeakMap('docArray')\n\n/**\n * Stable cache key for slim models:\n * - union slim → the user-supplied schema (preserved across chains)\n * - object slim → the fields record (preserved across chains)\n */\nfunction slimCacheKey(model: ZxModelInput): object {\n const s = model.schema as any\n return s instanceof $ZodTypeValue ? s : model.fields\n}\n\n/**\n * Returns the base schema for a model — the user fields as a Zod object (or the\n * user-supplied union for discriminated-union models).\n *\n * Full models: returns the bundle's pre-built `.base` (no allocation).\n * Union slim: returns the user's schema (no allocation — it IS the base).\n * Object slim: builds `z.object(fields)` once, cached on `fields`.\n */\nfunction base(model: ZxModelInput): $ZodType {\n const s = model.schema as any\n if (s?.base instanceof $ZodTypeValue) return s.base\n if (s instanceof $ZodTypeValue) return s\n const cached = baseCache.get(model.fields)\n if (cached) return cached\n if (Object.keys(model.fields).length === 0) {\n throw new Error(`[zodvex] Cannot derive base schema for model '${model.name}'`)\n }\n const built = z.object(model.fields) as any\n baseCache.set(model.fields, built)\n return built\n}\n\n/**\n * Constructs a doc schema: base fields + _id + _creationTime.\n * Full models reuse `model.schema.doc`; slim models cache on slimCacheKey(model).\n */\nfunction doc(model: ZxModelInput) {\n const s = model.schema as any\n if (s?.doc instanceof $ZodTypeValue) return s.doc\n const key = slimCacheKey(model)\n const cached = docCache.get(key)\n if (cached) return cached\n const built = addSystemFields(model.name, base(model)) as any\n docCache.set(key, built)\n return built\n}\n\n/**\n * Constructs an update schema: _id required + _creationTime optional + all user fields optional.\n * Full models reuse `model.schema.update`; slim models cache on slimCacheKey(model).\n */\nfunction update(model: ZxModelInput) {\n const s = model.schema as any\n if (s?.update instanceof $ZodTypeValue) return s.update\n const key = slimCacheKey(model)\n const cached = updateCache.get(key)\n if (cached) return cached\n const built = createSchemaUpdateSchema(model.name, base(model)) as any\n updateCache.set(key, built)\n return built\n}\n\n/**\n * Constructs a doc array schema: z.array(doc(model)).\n * Full models reuse `model.schema.docArray`; slim models cache on slimCacheKey(model).\n */\nfunction docArray(model: ZxModelInput) {\n const s = model.schema as any\n if (s?.docArray instanceof $ZodTypeValue) return s.docArray\n const key = slimCacheKey(model)\n const cached = docArrayCache.get(key)\n if (cached) return cached\n const built = z.array(doc(model)) as any\n docArrayCache.set(key, built)\n return built\n}\n\n/** Wrap in .nullable() using core constructor for zod-mini compat. */\nfunction nullable(schema: $ZodType): $ZodType {\n return new $ZodNullable({ type: 'nullable', innerType: schema }) as any\n}\n\n/** Wrap in .optional() using core constructor for zod-mini compat. */\nfunction optional(schema: $ZodType): $ZodType {\n return new $ZodOptional({ type: 'optional', innerType: schema }) as any\n}\n\n/** Wrap in .nullable().optional() using core constructors for zod-mini compat. */\nfunction nullableOptional(schema: $ZodType): $ZodType {\n return optional(nullable(schema))\n}\n\n/**\n * Pagination options schema — matches Convex's PaginationOptions type.\n */\nfunction paginationOpts() {\n return z.object({\n numItems: z.number(),\n cursor: nullable(z.string()),\n endCursor: nullableOptional(z.string()),\n id: optional(z.number()),\n maximumRowsRead: optional(z.number()),\n maximumBytesRead: optional(z.number())\n })\n}\n\n/**\n * Paginated result schema — wraps any item schema in Convex's PaginationResult shape.\n */\nfunction paginationResult<T extends $ZodType>(itemSchema: T) {\n return z.object({\n page: z.array(itemSchema),\n isDone: z.boolean(),\n continueCursor: z.string(),\n splitCursor: nullableOptional(z.string()),\n pageStatus: nullableOptional(z.enum(['SplitRecommended', 'SplitRequired']))\n })\n}\n\n/**\n * zx namespace - zodvex extended validators\n *\n * Provides explicit, discoverable helpers for Convex-specific transformations.\n */\nexport const zx = {\n /**\n * Date ↔ timestamp codec\n * @see {@link date}\n */\n date,\n\n /**\n * Convex ID validator\n * @see {@link id}\n */\n id,\n\n /**\n * Custom codec builder\n * @see {@link codec}\n */\n codec,\n\n /**\n * Pagination options schema matching Convex's PaginationOptions type\n * @see {@link paginationOpts}\n */\n paginationOpts,\n\n /**\n * Paginated result schema wrapping any item schema in Convex's PaginationResult shape\n * @see {@link paginationResult}\n */\n paginationResult,\n\n /**\n * Base schema for a model (user fields only; no system fields).\n * For object models reconstructs from fields; for union models returns the\n * user-supplied union. Cached per-model.\n * @see {@link base}\n */\n base,\n\n /**\n * Doc schema: model fields + _id + _creationTime\n * @see {@link doc}\n */\n doc,\n\n /**\n * Update schema: _id required, all other fields optional\n * @see {@link update}\n */\n update,\n\n /**\n * Doc array schema: z.array(doc(model))\n * @see {@link docArray}\n */\n docArray\n} as const\n","/**\n * Schema helpers — Pure Zod utilities for union handling and system fields.\n *\n * This module contains helpers extracted from tables.ts that have NO server\n * dependencies (no convex/server, no convex-helpers/server). They are safe\n * to import from zodvex (client-side code).\n *\n * Used by:\n * - model.ts (defineZodModel) — client-safe model definitions\n * - tables.ts (zodTable) — server-side table definitions\n */\n\nimport { z } from 'zod'\nimport {\n $ZodArray,\n $ZodDiscriminatedUnion,\n $ZodNumber,\n $ZodObject,\n type $ZodShape,\n $ZodType,\n $ZodUnion,\n clone\n} from './zod-core'\nimport { type ZxId, zx } from './zx'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Helper type for Convex system fields added to documents\n */\nexport type SystemFields<TableName extends string> = {\n _id: ZxId<TableName>\n _creationTime: $ZodNumber\n}\n\n/**\n * Maps over union options, extending each ZodObject variant with system fields.\n * Non-object variants are preserved as-is.\n */\nexport type MapSystemFields<TableName extends string, Options extends readonly $ZodType[]> = {\n [K in keyof Options]: Options[K] extends z.ZodObject<infer Shape extends $ZodShape> // zod-ok\n ? z.ZodObject<Shape & SystemFields<TableName>> // zod-ok\n : Options[K]\n}\n\n/**\n * Core-compatible version of MapSystemFields.\n * Uses $ZodObject from zod/v4/core instead of z.ZodObject from full zod. // zod-ok\n */\nexport type MapSystemFieldsCore<TableName extends string, Options extends readonly $ZodType[]> = {\n [K in keyof Options]: Options[K] extends $ZodObject<infer Shape extends $ZodShape>\n ? $ZodObject<Shape & SystemFields<TableName>>\n : Options[K]\n}\n\n/**\n * Computes the result of adding system fields to a union/object schema.\n * Uses only $Zod* types from zod/v4/core — safe for shared code and mini consumers.\n *\n * Handles:\n * - $ZodObject → $ZodObject with system fields\n * - $ZodUnion → $ZodUnion with system fields on each variant\n * - $ZodDiscriminatedUnion → $ZodDiscriminatedUnion with system fields on each variant\n * - Other → returned as-is\n */\nexport type AddSystemFieldsToUnion<TableName extends string, Schema extends $ZodType> =\n Schema extends $ZodObject<infer Shape extends $ZodShape>\n ? $ZodObject<Shape & SystemFields<TableName>>\n : Schema extends $ZodUnion<infer Options extends readonly $ZodType[]>\n ? $ZodUnion<MapSystemFieldsCore<TableName, Options>>\n : Schema extends $ZodDiscriminatedUnion<\n infer Options extends readonly $ZodType[],\n infer Disc extends string\n >\n ? $ZodDiscriminatedUnion<MapSystemFieldsCore<TableName, Options>, Disc>\n : Schema\n\n/**\n * Minimum tuple type required by z.union() - at least 2 elements.\n */\ntype UnionTuple<T extends $ZodType = $ZodType> = readonly [T, T, ...T[]]\n\n// ============================================================================\n// Union Helpers - Type-safe utilities for working with Zod unions\n// ============================================================================\n\n/** Full-zod union type alias used by isZodUnion/getUnionOptions — zod-ok by design. */\ntype AnyZodUnion =\n // zod-ok\n | z.ZodUnion<readonly $ZodType[]> // zod-ok\n | z.ZodDiscriminatedUnion<readonly z.ZodObject<$ZodShape>[], string> // zod-ok\n\n/**\n * Type guard to check if a schema is a union type (ZodUnion or ZodDiscriminatedUnion).\n */\nexport function isZodUnion(schema: $ZodType): schema is AnyZodUnion {\n return schema instanceof $ZodUnion || schema instanceof $ZodDiscriminatedUnion\n}\n\n/**\n * Extracts the options array from a ZodUnion or ZodDiscriminatedUnion.\n * Both union types have an `.options` property, but TypeScript doesn't\n * create a common accessor after instanceof checks.\n *\n * @param schema - A ZodUnion or ZodDiscriminatedUnion schema\n * @returns The array of union variant schemas\n */\nexport function getUnionOptions(schema: AnyZodUnion): readonly $ZodType[] {\n // $ZodDiscriminatedUnion extends $ZodUnion, so this covers both\n if (schema instanceof $ZodUnion) {\n return schema._zod.def.options\n }\n // cast: unreachable due to the union type constraint, but satisfies return type\n return (schema as any)._zod.def.options\n}\n\n/**\n * Asserts that an array has at least 2 elements, as required by z.union().\n * Throws an error if the array has fewer than 2 elements.\n *\n * @param options - Array of Zod schemas\n * @throws Error if array has fewer than 2 elements\n */\nexport function assertUnionOptions<T extends $ZodType>(\n options: readonly T[]\n): asserts options is UnionTuple<T> {\n if (options.length < 2) {\n throw new Error(\n `z.union() requires at least 2 options, but received ${options.length}. ` +\n 'This indicates an invalid union schema was passed to zodTable().'\n )\n }\n}\n\n/**\n * Creates a z.union() from an array of options with runtime validation.\n * Ensures the array has at least 2 elements as required by Zod.\n *\n * @param options - Array of Zod schemas (must have at least 2 elements)\n * @returns A ZodUnion schema\n * @throws Error if array has fewer than 2 elements\n */\n// Return type alias — prevents z.ZodUnion on a {-ending line (formatter-safe). // zod-ok\ntype ZodUnionOf<T extends $ZodType> = z.ZodUnion<UnionTuple<T>> // zod-ok\n\nexport function createUnionFromOptions<T extends $ZodType>(options: readonly T[]): ZodUnionOf<T> {\n assertUnionOptions(options)\n return z.union(options)\n}\n\n/**\n * Adds Convex system fields (_id, _creationTime) to a Zod schema.\n *\n * For object schemas: extends with system fields\n * For union schemas: adds system fields to each variant\n *\n * @param tableName - The Convex table name\n * @param schema - The Zod schema (object or union)\n * @returns Schema with system fields added\n */\n// Overload 1: ZodObject - extends with system fields\nexport function addSystemFields<TableName extends string, Shape extends $ZodShape>(\n tableName: TableName,\n schema: z.ZodObject<Shape> // zod-ok\n): z.ZodObject<Shape & SystemFields<TableName>> // zod-ok\n\n// Overload 2: ZodUnion - maps system fields to each variant\nexport function addSystemFields<TableName extends string, Options extends readonly $ZodType[]>(\n tableName: TableName,\n schema: z.ZodUnion<Options> // zod-ok\n): z.ZodUnion<MapSystemFields<TableName, Options>> // zod-ok\n\n// Overload 3: ZodDiscriminatedUnion - maps system fields preserving discriminator\n// Note: Zod v4 signature is ZodDiscriminatedUnion<Options, Discriminator>\nexport function addSystemFields<\n TableName extends string,\n Options extends readonly z.ZodObject<$ZodShape>[], // zod-ok\n Discriminator extends string\n>(\n tableName: TableName,\n schema: z.ZodDiscriminatedUnion<Options, Discriminator> // zod-ok\n): z.ZodDiscriminatedUnion<MapSystemFields<TableName, Options>, Discriminator> // zod-ok\n\n// Overload 4: Fallback for other ZodTypes - returns as-is\nexport function addSystemFields<TableName extends string, S extends $ZodType>(\n tableName: TableName,\n schema: S\n): S\n\n// Implementation\nexport function addSystemFields<TableName extends string>(\n tableName: TableName,\n schema: $ZodType\n): $ZodType {\n // Handle union schemas - add system fields to each variant\n if (isZodUnion(schema)) {\n const originalOptions = getUnionOptions(schema)\n const extendedOptions = originalOptions.map((variant: $ZodType) => {\n if (variant instanceof $ZodObject) {\n const newShape = {\n ...variant._zod.def.shape,\n _id: zx.id(tableName),\n _creationTime: z.number()\n }\n // Clone preserves the original's class + reinitializes with merged def\n return clone(variant, { ...variant._zod.def, shape: newShape })\n }\n // Non-object variants are returned as-is (shouldn't happen in practice)\n return variant\n })\n return createUnionFromOptions(extendedOptions)\n }\n\n // Handle object schemas — clone preserves class, checks, catchall, error\n if (schema instanceof $ZodObject) {\n const newShape = { ...schema._zod.def.shape, _id: zx.id(tableName), _creationTime: z.number() }\n return clone(schema, { ...schema._zod.def, shape: newShape })\n }\n\n // Fallback: return schema as-is\n return schema\n}\n","import { z } from 'zod'\nimport {\n addSystemFields,\n createUnionFromOptions,\n getUnionOptions,\n isZodUnion\n} from './schemaHelpers'\nimport { $ZodNullable, $ZodObject, $ZodOptional, type $ZodShape, $ZodType } from './zod-core'\nimport { zx } from './zx'\n\n// Return type alias so helper signatures don't expose full zod internals everywhere.\ntype AnyOptional = z.ZodOptional<any> // zod-ok\n\nexport type RuntimeModelSchemaBundle = {\n readonly doc: $ZodType\n readonly base: $ZodType\n readonly insert: $ZodType\n readonly update: $ZodType\n readonly docArray: $ZodType\n readonly paginatedDoc: $ZodType\n}\n\n/** Wrap in .optional() only if not already optional. Uses core constructor for zod-mini compat. */\nfunction ensureOptional(schema: $ZodType): AnyOptional {\n if (schema instanceof $ZodOptional) return schema as z.ZodOptional<any> // zod-ok\n return new $ZodOptional({ type: 'optional', innerType: schema }) as z.ZodOptional<any> // zod-ok\n}\n\n/** Wrap in .nullable().optional() using core constructors for zod-mini compat. */\nfunction nullableOptional(schema: $ZodType): $ZodType {\n return new $ZodOptional({\n type: 'optional',\n innerType: new $ZodNullable({ type: 'nullable', innerType: schema })\n }) as any\n}\n\nexport function createPartialShape(shape: Record<string, $ZodType>): Record<string, $ZodType> {\n const partialShape: Record<string, $ZodType> = {}\n for (const [key, value] of Object.entries(shape)) {\n partialShape[key] = ensureOptional(value)\n }\n return partialShape\n}\n\nexport function createUpdateObjectSchema<Name extends string>(\n name: Name,\n shape: Record<string, $ZodType>\n): z.ZodObject<any> {\n return z.object({\n _id: zx.id(name),\n _creationTime: z.optional(z.number()),\n ...createPartialShape(shape)\n })\n}\n\nexport function createPaginatedDocSchema(docSchema: $ZodType): z.ZodObject<any> {\n return z.object({\n page: z.array(docSchema),\n isDone: z.boolean(),\n continueCursor: z.string(),\n splitCursor: nullableOptional(z.string()),\n pageStatus: nullableOptional(z.enum(['SplitRecommended', 'SplitRequired']))\n })\n}\n\nexport function createObjectSchemaBundle<Name extends string>(\n name: Name,\n fields: $ZodShape,\n baseSchema: z.ZodObject<any> = z.object(fields)\n): RuntimeModelSchemaBundle {\n const docSchema = addSystemFields(name, baseSchema)\n\n return {\n doc: docSchema,\n base: baseSchema,\n insert: baseSchema,\n update: createUpdateObjectSchema(name, fields),\n docArray: z.array(docSchema),\n paginatedDoc: createPaginatedDocSchema(docSchema)\n }\n}\n\nexport function createSchemaUpdateSchema<Name extends string>(\n name: Name,\n inputSchema: $ZodType\n): $ZodType {\n if (isZodUnion(inputSchema)) {\n const updateOptions = getUnionOptions(inputSchema).map((variant: $ZodType) => {\n if (variant instanceof $ZodObject) {\n return createUpdateObjectSchema(name, variant._zod.def.shape)\n }\n return variant\n })\n return createUnionFromOptions(updateOptions)\n }\n\n if (inputSchema instanceof $ZodObject) {\n return createUpdateObjectSchema(name, inputSchema._zod.def.shape)\n }\n\n return inputSchema\n}\n\nexport function createSchemaBundle<Name extends string>(\n name: Name,\n inputSchema: $ZodType\n): RuntimeModelSchemaBundle {\n const docSchema = addSystemFields(name, inputSchema)\n\n return {\n doc: docSchema,\n base: inputSchema,\n insert: inputSchema,\n update: createSchemaUpdateSchema(name, inputSchema),\n docArray: z.array(docSchema),\n paginatedDoc: createPaginatedDocSchema(docSchema)\n }\n}\n","/**\n * defineZodModel — Client-safe model definitions with type-safe indexes\n *\n * This module is the client-safe spiritual successor to zodTable().\n * It produces Zod schemas for codec decode/encode and type-safe index\n * definitions via z.input<T> field path extraction.\n *\n * Exported from zodvex (no server imports).\n */\n\nimport { z } from 'zod'\nimport { attachMeta, type ZodvexModelDefinitionSource } from './meta'\nimport {\n createObjectSchemaBundle,\n createSchemaBundle,\n type RuntimeModelSchemaBundle\n} from './modelSchemaBundle'\nimport type { AddSystemFieldsToUnion } from './schemaHelpers'\nimport { $ZodArray, type $ZodShape, $ZodType, type input as zinput } from './zod-core'\nimport type { ZxId } from './zx'\n\n/**\n * Build the user-facing validator for a model. For raw-shape input we build\n * `z.object(fields)` lazily on first access; the bundle's `.insert` already\n * holds an equivalent for full models, but we want a stable identity that's\n * keyed on the model itself (so chained `.index()` calls don't reallocate).\n */\nfunction lazyValidator(fields: $ZodShape, userSchema: $ZodType | null): { get: () => $ZodType } {\n let cached: $ZodType | undefined\n return {\n get: () => {\n if (cached) return cached\n cached = userSchema ?? z.object(fields)\n return cached\n }\n }\n}\n\nfunction createModel<Name extends string>(\n name: Name,\n fields: $ZodShape,\n schema: RuntimeModelSchemaBundle,\n definitionSource: ZodvexModelDefinitionSource,\n indexes: Record<string, readonly string[]> = {},\n searchIndexes: Record<string, SearchIndexConfig> = {},\n vectorIndexes: Record<string, VectorIndexConfig> = {},\n // The user-supplied schema for overload-2 (definitionSource === 'schema').\n // Passing it through preserves identity across chained .index() calls; for\n // shape-input it's null and the lazy getter builds z.object(fields).\n userSchema: $ZodType | null = null\n): any {\n const validatorCache = lazyValidator(fields, userSchema)\n const model: any = {\n name,\n fields,\n schema,\n indexes,\n searchIndexes,\n vectorIndexes,\n get validator() {\n return validatorCache.get()\n },\n index(indexName: string, indexFields: readonly string[]) {\n return createModel(\n name,\n fields,\n schema,\n definitionSource,\n { ...indexes, [indexName]: [...indexFields, '_creationTime'] },\n searchIndexes,\n vectorIndexes,\n userSchema\n )\n },\n searchIndex(indexName: string, config: SearchIndexConfig) {\n return createModel(\n name,\n fields,\n schema,\n definitionSource,\n indexes,\n { ...searchIndexes, [indexName]: config },\n vectorIndexes,\n userSchema\n )\n },\n vectorIndex(indexName: string, config: VectorIndexConfig) {\n return createModel(\n name,\n fields,\n schema,\n definitionSource,\n indexes,\n searchIndexes,\n { ...vectorIndexes, [indexName]: config },\n userSchema\n )\n }\n }\n\n attachMeta(model, { type: 'model', tableName: name, definitionSource, schemas: schema })\n return model\n}\n\n/**\n * Factory for slim models (schemaHelpers: false).\n *\n * Object slim (definitionSource: 'shape'): `userSchema` is null. The model\n * carries only `{ name, fields, indexes, ... }` with no pre-built Zod schemas.\n * Consumers derive schemas on demand via cached zx helpers.\n *\n * Union slim (definitionSource: 'schema'): `userSchema` is the user-supplied\n * union/discriminated union. It can't be recreated from `fields`, so it must\n * be retained on the model. `fields` is `{}` in this case.\n */\nfunction createSlimModel<Name extends string>(\n name: Name,\n fields: $ZodShape,\n userSchema: $ZodType | null,\n definitionSource: ZodvexModelDefinitionSource,\n indexes: Record<string, readonly string[]> = {},\n searchIndexes: Record<string, SearchIndexConfig> = {},\n vectorIndexes: Record<string, VectorIndexConfig> = {}\n): any {\n const validatorCache = lazyValidator(fields, userSchema)\n const model: any = {\n name,\n fields,\n indexes,\n searchIndexes,\n vectorIndexes,\n get validator() {\n return validatorCache.get()\n },\n index(indexName: string, indexFields: readonly string[]) {\n return createSlimModel(\n name,\n fields,\n userSchema,\n definitionSource,\n { ...indexes, [indexName]: [...indexFields, '_creationTime'] },\n searchIndexes,\n vectorIndexes\n )\n },\n searchIndex(indexName: string, config: SearchIndexConfig) {\n return createSlimModel(\n name,\n fields,\n userSchema,\n definitionSource,\n indexes,\n { ...searchIndexes, [indexName]: config },\n vectorIndexes\n )\n },\n vectorIndex(indexName: string, config: VectorIndexConfig) {\n return createSlimModel(name, fields, userSchema, definitionSource, indexes, searchIndexes, {\n ...vectorIndexes,\n [indexName]: config\n })\n }\n }\n\n if (userSchema !== null) model.schema = userSchema\n\n attachMeta(model, { type: 'model', tableName: name, definitionSource })\n return model\n}\n\n// ============================================================================\n// Field Path Types\n// ============================================================================\n\n/**\n * Extract all valid field paths from a TypeScript object type.\n * Mirrors Convex's ExtractFieldPaths but operates on plain TS types\n * inferred from z.input<T> (wire format).\n *\n * - Recurses into nested objects to produce dotted paths (\"address.city\")\n * - Distributes over unions (T extends T trick)\n * - Excludes arrays (can't index into array elements)\n * - Unwraps nullable/optional via NonNullable before recursing\n */\nexport type FieldPaths<T> = T extends any[]\n ? never\n : T extends Record<string, any>\n ? T extends T // distribute over unions\n ? {\n [K in keyof T & string]:\n | K\n | (NonNullable<T[K]> extends any[]\n ? never\n : NonNullable<T[K]> extends Record<string, any>\n ? `${K}.${FieldPaths<NonNullable<T[K]>>}`\n : never)\n }[keyof T & string]\n : never\n : never\n\n/**\n * Field paths valid for index definitions on a model.\n * Uses z.input<T> to get wire-format paths, plus _creationTime system field.\n */\nexport type ModelFieldPaths<InsertSchema extends $ZodType> =\n | FieldPaths<zinput<InsertSchema>>\n | '_creationTime'\n\n// ============================================================================\n// Index Config Types\n// ============================================================================\n\nexport type SearchIndexConfig = {\n searchField: string\n filterFields?: string[]\n}\n\nexport type VectorIndexConfig = {\n vectorField: string\n dimensions: number\n filterFields?: string[]\n}\n\n// ============================================================================\n// ZodModel Type\n// ============================================================================\n\n/**\n * Constraint for the schema bundle carried by ZodModel.\n * Concrete types (FullZodModelSchemas, MiniModelSchemas) satisfy this.\n */\nexport type ModelSchemas = {\n readonly doc: $ZodType\n readonly base: $ZodType\n readonly insert: $ZodType\n readonly update: $ZodType\n readonly docArray: $ZodType\n readonly paginatedDoc: $ZodType\n}\n\n/**\n * Schema types for union/discriminated union models.\n * Preserves the specific Schema type so ConvexTableFor can compute\n * validators from the union, and consumers get typed schema.doc access.\n */\nexport type UnionModelSchemas<Name extends string, Schema extends $ZodType> = {\n readonly doc: AddSystemFieldsToUnion<Name, Schema>\n readonly base: Schema\n readonly insert: Schema\n readonly update: $ZodType\n readonly docArray: $ZodArray<AddSystemFieldsToUnion<Name, Schema>>\n readonly paginatedDoc: $ZodType\n}\n\n/** @internal Update shape for FullZodModelSchemas — full-zod types only. */ // zod-ok\ntype FullUpdateShape<Name extends string, Fields extends $ZodShape> = {\n // zod-ok\n _id: ZxId<Name> // zod-ok\n _creationTime: z.ZodOptional<z.ZodNumber> // zod-ok\n} & { [K in keyof Fields]: z.ZodOptional<Fields[K]> } // zod-ok\n\n/** @internal Doc shape used by docArray and paginatedDoc. */ // zod-ok\ntype FullDocShape<Name extends string, Fields extends $ZodShape> = Fields & {\n // zod-ok\n _id: ZxId<Name> // zod-ok\n _creationTime: z.ZodNumber // zod-ok\n} // zod-ok\n\n/** @internal PaginatedDoc shape for FullZodModelSchemas. */ // zod-ok\ntype FullPaginatedShape<Name extends string, Fields extends $ZodShape> = {\n // zod-ok\n page: z.ZodArray<z.ZodObject<FullDocShape<Name, Fields>>> // zod-ok\n isDone: z.ZodBoolean // zod-ok\n continueCursor: z.ZodOptional<z.ZodNullable<z.ZodString>> // zod-ok\n} // zod-ok\n\n/**\n * Full-zod schema types — the default for `zodvex` consumers.\n * Each property uses z.ZodObject / z.ZodArray etc. from full zod, // zod-ok\n * providing method chaining (.parse(), .shape, .nullable(), etc.).\n */\nexport type FullZodModelSchemas<Name extends string, Fields extends $ZodShape> = {\n readonly doc: z.ZodObject<FullDocShape<Name, Fields>> // zod-ok\n readonly base: z.ZodObject<Fields> // zod-ok\n readonly insert: z.ZodObject<Fields> // zod-ok\n readonly update: z.ZodObject<FullUpdateShape<Name, Fields>> // zod-ok\n readonly docArray: z.ZodArray<z.ZodObject<FullDocShape<Name, Fields>>> // zod-ok\n readonly paginatedDoc: z.ZodObject<FullPaginatedShape<Name, Fields>> // zod-ok\n}\n\n/**\n * A client-safe model definition with type-safe schemas and index metadata.\n *\n * Produced by defineZodModel(). Chainable via .index(), .searchIndex(), .vectorIndex().\n * Each chain call returns a new immutable model with accumulated metadata.\n *\n * The `Schemas` parameter carries the concrete schema types — full-zod types\n * from `zodvex`, mini types from `zodvex/mini`. Chain methods preserve `Schemas`\n * unchanged since they only modify index metadata.\n *\n * Downstream consumers wrap this to add domain metadata (e.g., security rules).\n */\nexport type ZodModel<\n Name extends string = string,\n Fields extends $ZodShape = $ZodShape,\n InsertSchema extends $ZodType = $ZodType,\n Schemas extends ModelSchemas = ModelSchemas,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = {\n readonly name: Name\n readonly fields: Fields\n readonly schema: Schemas\n readonly indexes: Indexes\n readonly searchIndexes: SearchIndexes\n readonly vectorIndexes: VectorIndexes\n /**\n * The user-facing, parseable validator for the model — see ZodModelBase\n * for the contract. Same `InsertSchema` type so refinements survive when\n * the model was constructed from a pre-built schema (#56).\n */\n readonly validator: InsertSchema\n\n index<\n IndexName extends string,\n First extends ModelFieldPaths<InsertSchema>,\n Rest extends ModelFieldPaths<InsertSchema>[]\n >(\n name: IndexName,\n fields: readonly [First, ...Rest]\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes & Record<IndexName, readonly [First, ...Rest, '_creationTime']>,\n SearchIndexes,\n VectorIndexes\n >\n\n searchIndex<IndexName extends string>(\n name: IndexName,\n config: SearchIndexConfig\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes,\n SearchIndexes & Record<IndexName, SearchIndexConfig>,\n VectorIndexes\n >\n\n vectorIndex<IndexName extends string>(\n name: IndexName,\n config: VectorIndexConfig\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes,\n SearchIndexes,\n VectorIndexes & Record<IndexName, VectorIndexConfig>\n >\n}\n\nexport type AnyZodModel = ZodModel<string, $ZodShape, $ZodType, ModelSchemas>\n\n// ============================================================================\n// ZodModelBase — internal constraint type (no schema bundle)\n// ============================================================================\n\n/**\n * Base model type — the contract that all zodvex internals constrain against.\n *\n * Deliberately excludes `schema` so that internal code (defineZodSchema,\n * tableFromModel, DB wrapper) cannot depend on the schema bundle shape.\n * This guarantees both full and slim models work with all internals.\n */\nexport type ZodModelBase<\n Name extends string = string,\n Fields extends $ZodShape = $ZodShape,\n InsertSchema extends $ZodType = $ZodType,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = {\n readonly name: Name\n readonly fields: Fields\n readonly indexes: Indexes\n readonly searchIndexes: SearchIndexes\n readonly vectorIndexes: VectorIndexes\n /**\n * The user-facing, parseable schema for the model — typed as exactly the\n * input the caller passed to `defineZodModel`:\n *\n * - For raw-shape input (overload 1): `z.object(model.fields)`, built\n * lazily on first access and cached. Equivalent to calling\n * `z.object(model.fields)` yourself, but typed precisely and shared.\n * - For pre-built schema input (overload 2): the exact schema you passed,\n * refinements / checks / wrappers preserved. Avoids the trap of\n * round-tripping through `fields` and dropping `.refine()` constraints.\n *\n * Designed for client-side validation use cases (TanStack Form, RHF,\n * standalone `.safeParse(...)`). See #56.\n */\n readonly validator: InsertSchema\n\n index<\n IndexName extends string,\n First extends ModelFieldPaths<InsertSchema>,\n Rest extends ModelFieldPaths<InsertSchema>[]\n >(\n name: IndexName,\n fields: readonly [First, ...Rest]\n ): ZodModelBase<\n Name,\n Fields,\n InsertSchema,\n Indexes & Record<IndexName, readonly [First, ...Rest, '_creationTime']>,\n SearchIndexes,\n VectorIndexes\n >\n\n searchIndex<IndexName extends string>(\n name: IndexName,\n config: SearchIndexConfig\n ): ZodModelBase<\n Name,\n Fields,\n InsertSchema,\n Indexes,\n SearchIndexes & Record<IndexName, SearchIndexConfig>,\n VectorIndexes\n >\n\n vectorIndex<IndexName extends string>(\n name: IndexName,\n config: VectorIndexConfig\n ): ZodModelBase<\n Name,\n Fields,\n InsertSchema,\n Indexes,\n SearchIndexes,\n VectorIndexes & Record<IndexName, VectorIndexConfig>\n >\n}\n\n/** Widened base type for internal constraints. */\nexport type AnyZodModelBase = ZodModelBase<string, $ZodShape, $ZodType>\n\n/** Options for defineZodModel. */\nexport type DefineZodModelOptions = {\n /**\n * When `true` (default), the model carries a full schema bundle with\n * `doc`, `base`, `insert`, `update`, `docArray`, `paginatedDoc`.\n *\n * When `false`, the model carries only `schema` (the base) and `doc`.\n * Use `zx.update(model)`, `zx.docArray(model)`, `zx.paginationResult(model.doc)`\n * to derive schemas on demand.\n *\n * @default true\n */\n schemaHelpers?: boolean\n}\n\n/**\n * Slim model for object shapes — produced when `schemaHelpers: false` with a raw shape.\n *\n * Carries only table name, fields, and index metadata — no pre-built Zod schemas.\n * Derive schemas on demand via cached `zx.*` helpers:\n * - `zx.doc(model)` — doc with system fields\n * - `zx.base(model)` — base object (user fields only)\n * - `zx.update(model)` — partial update schema\n * - `zx.docArray(model)` — array of docs\n * - `zx.paginationResult(zx.doc(model))` — paginated doc\n */\nexport type SlimObjectModel<\n Name extends string = string,\n Fields extends $ZodShape = $ZodShape,\n InsertSchema extends $ZodType = $ZodType,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = ZodModelBase<Name, Fields, InsertSchema, Indexes, SearchIndexes, VectorIndexes>\n\n/**\n * Slim model for union/discriminated union schemas — produced when `schemaHelpers: false`\n * with a pre-built schema.\n *\n * Retains the user-supplied `schema` since it can't be reconstructed from fields.\n * All other schemas derived on demand via `zx.*`.\n */\nexport type SlimUnionModel<\n Name extends string = string,\n Schema extends $ZodType = $ZodType,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = ZodModelBase<Name, $ZodShape, Schema, Indexes, SearchIndexes, VectorIndexes> & {\n readonly schema: Schema\n}\n\n// ============================================================================\n// defineZodModel\n// ============================================================================\n\n/**\n * Define a client-safe model with Zod schemas and type-safe index definitions.\n *\n * Accepts either a raw Zod shape (object mapping field names to Zod types) or\n * a pre-built Zod schema (union, discriminated union, or object).\n *\n * @param name - The table name (literal string type preserved)\n * @param fieldsOrSchema - Raw Zod shape or pre-built Zod schema\n * @returns A ZodModel with schemas, chainable index methods\n *\n * @example Raw shape (most common)\n * ```ts\n * const patients = defineZodModel('patients', {\n * clinicId: z.string(),\n * email: z.string().email().optional(),\n * createdAt: zx.date(),\n * })\n * .index('byClinic', ['clinicId'])\n * .index('byCreation', ['_creationTime'])\n * ```\n *\n * @example Discriminated union\n * ```ts\n * const visits = defineZodModel('visits', z.discriminatedUnion('type', [\n * z.object({ type: z.literal('phone'), duration: z.number() }),\n * z.object({ type: z.literal('in-person'), roomId: z.string() }),\n * ]))\n * .index('byType', ['type'])\n * ```\n */\n// Overload: raw shape with schemaHelpers: false → SlimObjectModel\nexport function defineZodModel<Name extends string, Fields extends $ZodShape>(\n name: Name,\n fields: Fields,\n options: { schemaHelpers: false }\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional\n): SlimObjectModel<Name, Fields, z.ZodObject<Fields>, {}, {}, {}> // zod-ok\n\n// Overload: pre-built schema with schemaHelpers: false → SlimUnionModel\nexport function defineZodModel<Name extends string, Schema extends $ZodType>(\n name: Name,\n schema: Schema,\n options: { schemaHelpers: false }\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional\n): SlimUnionModel<Name, Schema, {}, {}, {}>\n\n// Overload: raw shape (existing behavior)\nexport function defineZodModel<Name extends string, Fields extends $ZodShape>(\n name: Name,\n fields: Fields\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional — represents zero indexes/searchIndexes/vectorIndexes\n): ZodModel<Name, Fields, z.ZodObject<Fields>, FullZodModelSchemas<Name, Fields>, {}, {}, {}> // zod-ok\n\n// Overload: pre-built schema (union or object)\nexport function defineZodModel<Name extends string, Schema extends $ZodType>(\n name: Name,\n schema: Schema\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional — represents zero indexes/searchIndexes/vectorIndexes\n): ZodModel<Name, $ZodShape, Schema, UnionModelSchemas<Name, Schema>, {}, {}, {}>\n\n// Implementation\nexport function defineZodModel<Name extends string>(\n name: Name,\n fieldsOrSchema: $ZodShape | $ZodType,\n options?: DefineZodModelOptions\n): any {\n const slim = options?.schemaHelpers === false\n\n // Detect if input is a pre-built Zod schema (union, object, etc.) vs raw shape\n if (fieldsOrSchema instanceof $ZodType) {\n if (slim) {\n return createSlimModel(name, {}, fieldsOrSchema as $ZodType, 'schema')\n }\n return createModel(\n name,\n {},\n createSchemaBundle(name, fieldsOrSchema as $ZodType),\n 'schema',\n undefined,\n undefined,\n undefined,\n fieldsOrSchema as $ZodType\n )\n }\n\n const fields = fieldsOrSchema as $ZodShape\n if (slim) {\n // Object slim — no base schema retained; reconstructed from fields on demand.\n return createSlimModel(name, fields, null, 'shape')\n }\n return createModel(name, fields, createObjectSchemaBundle(name, fields), 'shape')\n}\n","import { z } from 'zod'\nimport {\n defineZodModel as _defineZodModel,\n type AnyZodModelBase,\n type DefineZodModelOptions,\n type SlimObjectModel,\n type SlimUnionModel,\n type ZodModelBase\n} from '../internal/model'\nimport type { AddSystemFieldsToUnion } from '../internal/schemaHelpers'\nimport { $ZodArray, type $ZodShape, $ZodType, type input as zinput } from '../internal/zod-core'\nimport type { ZxId } from './zx'\n\nexport type FieldPaths<T> = T extends any[]\n ? never\n : T extends Record<string, any>\n ? T extends T\n ? {\n [K in keyof T & string]:\n | K\n | (NonNullable<T[K]> extends any[]\n ? never\n : NonNullable<T[K]> extends Record<string, any>\n ? `${K}.${FieldPaths<NonNullable<T[K]>>}`\n : never)\n }[keyof T & string]\n : never\n : never\n\nexport type ModelFieldPaths<InsertSchema extends $ZodType> =\n | FieldPaths<zinput<InsertSchema>>\n | '_creationTime'\n\nexport type SearchIndexConfig = {\n searchField: string\n filterFields?: string[]\n}\n\nexport type VectorIndexConfig = {\n vectorField: string\n dimensions: number\n filterFields?: string[]\n}\n\nexport type ModelSchemas = {\n readonly doc: $ZodType\n readonly base: $ZodType\n readonly insert: $ZodType\n readonly update: $ZodType\n readonly docArray: $ZodType\n readonly paginatedDoc: $ZodType\n}\n\nexport type UnionModelSchemas<Name extends string, Schema extends $ZodType> = {\n readonly doc: AddSystemFieldsToUnion<Name, Schema>\n readonly base: Schema\n readonly insert: Schema\n readonly update: $ZodType\n readonly docArray: $ZodArray<AddSystemFieldsToUnion<Name, Schema>>\n readonly paginatedDoc: $ZodType\n}\n\ntype FullUpdateShape<Name extends string, Fields extends $ZodShape> = {\n _id: ZxId<Name>\n _creationTime: z.ZodOptional<z.ZodNumber>\n} & { [K in keyof Fields]: z.ZodOptional<Fields[K]> }\n\ntype FullDocShape<Name extends string, Fields extends $ZodShape> = Fields & {\n _id: ZxId<Name>\n _creationTime: z.ZodNumber\n}\n\ntype FullPaginatedShape<Name extends string, Fields extends $ZodShape> = {\n page: z.ZodArray<z.ZodObject<FullDocShape<Name, Fields>>>\n isDone: z.ZodBoolean\n continueCursor: z.ZodString\n splitCursor: z.ZodOptional<z.ZodNullable<z.ZodString>>\n pageStatus: z.ZodOptional<z.ZodNullable<z.ZodEnum>>\n}\n\nexport type FullZodModelSchemas<Name extends string, Fields extends $ZodShape> = {\n readonly doc: z.ZodObject<FullDocShape<Name, Fields>>\n readonly base: z.ZodObject<Fields>\n readonly insert: z.ZodObject<Fields>\n readonly update: z.ZodObject<FullUpdateShape<Name, Fields>>\n readonly docArray: z.ZodArray<z.ZodObject<FullDocShape<Name, Fields>>>\n readonly paginatedDoc: z.ZodObject<FullPaginatedShape<Name, Fields>>\n}\n\ntype DefaultFullModelSchemas<\n Name extends string,\n Fields extends $ZodShape,\n InsertSchema extends $ZodType\n> =\n InsertSchema extends z.ZodObject<Fields>\n ? FullZodModelSchemas<Name, Fields>\n : UnionModelSchemas<Name, InsertSchema>\n\nexport type ZodModel<\n Name extends string = string,\n Fields extends $ZodShape = $ZodShape,\n InsertSchema extends $ZodType = z.ZodObject<Fields>,\n Schemas extends ModelSchemas = DefaultFullModelSchemas<Name, Fields, InsertSchema>,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = {\n readonly name: Name\n readonly fields: Fields\n readonly schema: Schemas\n readonly indexes: Indexes\n readonly searchIndexes: SearchIndexes\n readonly vectorIndexes: VectorIndexes\n /**\n * The user-facing, parseable validator for the model. For raw-shape input\n * this is `z.object(model.fields)`; for pre-built schema input this is the\n * exact schema the caller passed, refinements / checks preserved. See #56.\n */\n readonly validator: InsertSchema\n\n index<\n IndexName extends string,\n First extends ModelFieldPaths<InsertSchema>,\n Rest extends ModelFieldPaths<InsertSchema>[]\n >(\n name: IndexName,\n fields: readonly [First, ...Rest]\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes & Record<IndexName, readonly [First, ...Rest, '_creationTime']>,\n SearchIndexes,\n VectorIndexes\n >\n\n searchIndex<IndexName extends string>(\n name: IndexName,\n config: SearchIndexConfig\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes,\n SearchIndexes & Record<IndexName, SearchIndexConfig>,\n VectorIndexes\n >\n\n vectorIndex<IndexName extends string>(\n name: IndexName,\n config: VectorIndexConfig\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes,\n SearchIndexes,\n VectorIndexes & Record<IndexName, VectorIndexConfig>\n >\n}\n\n// Overload: raw shape with schemaHelpers: false → SlimObjectModel\nexport function defineZodModel<Name extends string, Fields extends $ZodShape>(\n name: Name,\n fields: Fields,\n options: { schemaHelpers: false }\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional\n): SlimObjectModel<Name, Fields, z.ZodObject<Fields>, {}, {}, {}>\n\n// Overload: pre-built schema with schemaHelpers: false → SlimUnionModel\nexport function defineZodModel<Name extends string, Schema extends $ZodType>(\n name: Name,\n schema: Schema,\n options: { schemaHelpers: false }\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional\n): SlimUnionModel<Name, Schema, {}, {}, {}>\n\nexport function defineZodModel<Name extends string, Fields extends $ZodShape>(\n name: Name,\n fields: Fields\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional — represents zero indexes/searchIndexes/vectorIndexes\n): ZodModel<Name, Fields, z.ZodObject<Fields>, FullZodModelSchemas<Name, Fields>, {}, {}, {}>\n\nexport function defineZodModel<Name extends string, Schema extends $ZodType>(\n name: Name,\n schema: Schema\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional — represents zero indexes/searchIndexes/vectorIndexes\n): ZodModel<Name, $ZodShape, Schema, UnionModelSchemas<Name, Schema>, {}, {}, {}>\n\nexport function defineZodModel<Name extends string>(\n name: Name,\n fieldsOrSchema: $ZodShape | $ZodType,\n options?: DefineZodModelOptions\n): any {\n if (fieldsOrSchema instanceof $ZodType) {\n return (_defineZodModel as any)(name, fieldsOrSchema, options)\n }\n return (_defineZodModel as any)(name, fieldsOrSchema, options)\n}\n\nexport type {\n AnyZodModelBase,\n DefineZodModelOptions,\n SlimObjectModel,\n SlimUnionModel,\n ZodModelBase\n}\n","/**\n * zodvex - Client-safe full-Zod surface.\n *\n * This is the canonical entrypoint for standard full-Zod consumers.\n * Server-only APIs live under `zodvex/server`.\n *\n * @example\n * ```ts\n * import { zx, defineZodModel } from 'zodvex'\n * import { defineZodSchema, initZodvex } from 'zodvex/server'\n * ```\n */\n\nexport * from './public'\n\nconst legacyMigrationGuide = 'docs/migration/v0.6.md'\n\nfunction deprecatedRootExport(name: string): never {\n throw new Error(\n `[zodvex] \\`${name}\\` is deprecated and is no longer exported from \\`zodvex\\`.\\n` +\n `Import it from \\`zodvex/legacy\\` temporarily, or migrate away from the legacy API.\\n` +\n `Migration guide: ${legacyMigrationGuide}`\n )\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `defineZodModel` + `defineZodSchema`.\n */\nexport function zodTable(): never {\n return deprecatedRootExport('zodTable')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `defineZodModel`.\n */\nexport function zodDoc(): never {\n return deprecatedRootExport('zodDoc')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `defineZodModel`.\n */\nexport function zodDocOrNull(): never {\n return deprecatedRootExport('zodDocOrNull')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex()`.\n */\nexport function zQueryBuilder(): never {\n return deprecatedRootExport('zQueryBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex()`.\n */\nexport function zMutationBuilder(): never {\n return deprecatedRootExport('zMutationBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex()`.\n */\nexport function zActionBuilder(): never {\n return deprecatedRootExport('zActionBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex().zq.withContext()`.\n */\nexport function zCustomQueryBuilder(): never {\n return deprecatedRootExport('zCustomQueryBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex().zm.withContext()`.\n */\nexport function zCustomMutationBuilder(): never {\n return deprecatedRootExport('zCustomMutationBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex().za.withContext()`.\n */\nexport function zCustomActionBuilder(): never {\n return deprecatedRootExport('zCustomActionBuilder')\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/normalizeCodecPaths.ts","../src/internal/stripUndefined.ts","../src/internal/boundaryHelpers.ts","../src/internal/ids.ts","../src/internal/schema/objectShape.ts","../src/internal/mapping/handlers/enum.ts","../src/internal/mapping/handlers/nullable.ts","../src/internal/mapping/handlers/record.ts","../src/internal/mapping/handlers/union.ts","../src/internal/mapping/utils.ts","../src/internal/mapping/core.ts","../src/internal/registry.ts","../src/internal/results.ts","../src/internal/schema/dateGuards.ts","../src/internal/schema/pick.ts","../src/internal/schema/runtimeHelpers.ts","../src/internal/codec.ts","../src/public/codec.ts","../src/internal/meta.ts","../src/public/codegen/extractCodec.ts","../src/internal/zx.ts","../src/internal/schemaHelpers.ts","../src/internal/modelSchemaBundle.ts","../src/internal/model.ts","../src/public/model.ts","../src/index.ts"],"names":["zodToConvexInternal","v","metadata","z","zodvexCodec","codec","date","nullableOptional","defineZodModel"],"mappings":";;;;;;;AAeA,SAAS,YAAY,MAAA,EAA4B;AAC/C,EAAA,IAAI,OAAA,GAAoB,MAAA;AACxB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,EAAA,EAAI,CAAA,EAAA,EAAK;AAC3B,IAAA,IACE,OAAA,YAAmB,YAAA,IACnB,OAAA,YAAmB,YAAA,IACnB,mBAAmB,WAAA,EACnB;AACA,MAAA,OAAA,GAAU,OAAA,CAAQ,KAAK,GAAA,CAAI,SAAA;AAC3B,MAAA;AAAA,IACF;AACA,IAAA;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;AAOA,SAAS,uBAAA,CAAwB,MAA2B,MAAA,EAAuC;AACjG,EAAA,MAAM,SAA8B,EAAC;AACr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ACzZO,SAASK,eAAAA,CACd,IAAA,EACA,cAAA,EACA,OAAA,EACK;AACL,EAAA,IAAI,0BAA0B,QAAA,EAAU;AACtC,IAAA,OAAQ,cAAA,CAAwB,IAAA,EAAM,cAAA,EAAgB,OAAO,CAAA;AAAA,EAC/D;AACA,EAAA,OAAQ,cAAA,CAAwB,IAAA,EAAM,cAAA,EAAgB,OAAO,CAAA;AAC/D;;;AC1LA,IAAM,oBAAA,GAAuB,wBAAA;AAE7B,SAAS,qBAAqB,IAAA,EAAqB;AACjD,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,cAAc,IAAI,CAAA;AAAA;AAAA,iBAAA,EAEI,oBAAoB,CAAA;AAAA,GAC5C;AACF;AAKO,SAAS,QAAA,GAAkB;AAChC,EAAA,OAAO,qBAAqB,UAAU,CAAA;AACxC;AAKO,SAAS,MAAA,GAAgB;AAC9B,EAAA,OAAO,qBAAqB,QAAQ,CAAA;AACtC;AAKO,SAAS,YAAA,GAAsB;AACpC,EAAA,OAAO,qBAAqB,cAAc,CAAA;AAC5C;AAKO,SAAS,aAAA,GAAuB;AACrC,EAAA,OAAO,qBAAqB,eAAe,CAAA;AAC7C;AAKO,SAAS,gBAAA,GAA0B;AACxC,EAAA,OAAO,qBAAqB,kBAAkB,CAAA;AAChD;AAKO,SAAS,cAAA,GAAwB;AACtC,EAAA,OAAO,qBAAqB,gBAAgB,CAAA;AAC9C;AAKO,SAAS,mBAAA,GAA6B;AAC3C,EAAA,OAAO,qBAAqB,qBAAqB,CAAA;AACnD;AAKO,SAAS,sBAAA,GAAgC;AAC9C,EAAA,OAAO,qBAAqB,wBAAwB,CAAA;AACtD;AAKO,SAAS,oBAAA,GAA8B;AAC5C,EAAA,OAAO,qBAAqB,sBAAsB,CAAA;AACpD","file":"index.js","sourcesContent":["import {\n $ZodArray,\n $ZodCodec,\n $ZodDefault,\n $ZodError,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodType,\n encode\n} from './zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable/ZodDefault wrappers to get the structural type.\n */\nfunction unwrapOuter(schema: $ZodType): $ZodType {\n let current: $ZodType = schema\n for (let i = 0; i < 10; i++) {\n if (\n current instanceof $ZodOptional ||\n current instanceof $ZodNullable ||\n current instanceof $ZodDefault\n ) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return current\n}\n\n/**\n * Walks a path through a schema tree, truncating at codec boundaries.\n * When a codec is encountered, the path is cut — any deeper segments\n * are wire-internal and should not be exposed to consumers.\n */\nfunction truncateAtCodecBoundary(path: (string | number)[], schema: $ZodType): (string | number)[] {\n const result: (string | number)[] = []\n let current: $ZodType = schema\n\n for (const segment of path) {\n current = unwrapOuter(current)\n\n // If we've landed on a codec, everything from here is wire-internal — stop\n if (current instanceof $ZodCodec) {\n break\n }\n\n // Descend into objects\n if (current instanceof $ZodObject && typeof segment === 'string') {\n const fieldSchema = current._zod.def.shape[segment] as $ZodType | undefined\n if (!fieldSchema) {\n // Unknown field — include segment and stop\n result.push(segment)\n break\n }\n\n result.push(segment)\n\n const unwrapped = unwrapOuter(fieldSchema)\n if (unwrapped instanceof $ZodCodec) {\n // Hit a codec boundary — truncate here\n break\n }\n\n current = fieldSchema\n continue\n }\n\n // Descend into arrays\n if (current instanceof $ZodArray && typeof segment === 'number') {\n result.push(segment)\n current = current._zod.def.element\n continue\n }\n\n // For anything else (unions, records, etc.), include segment and continue\n result.push(segment)\n }\n\n return result\n}\n\n/**\n * Normalizes ZodError paths by truncating at codec boundaries.\n *\n * When z.encode() throws a ZodError, the paths reflect the wire schema\n * structure (e.g., [\"email\", \"value\"] for a custom codec).\n * This function strips the wire-internal segments so consumers see\n * clean field-level paths (e.g., [\"email\"]).\n */\nexport function normalizeCodecPaths(error: $ZodError, schema: $ZodType): $ZodError {\n const normalized = error.issues.map(issue => ({\n ...issue,\n path: truncateAtCodecBoundary(issue.path as (string | number)[], schema)\n }))\n return new $ZodError(normalized)\n}\n\n/**\n * Encodes a value through a Zod schema, normalizing codec-internal\n * path segments in any ZodError before re-throwing.\n *\n * Drop-in replacement for `z.encode(schema, value)` at client boundaries.\n */\nexport function safeEncode(schema: $ZodType, value: unknown): unknown {\n try {\n return encode(schema, value)\n } catch (e) {\n if (e instanceof $ZodError) throw normalizeCodecPaths(e as $ZodError, schema)\n throw e\n }\n}\n","/**\n * Recursively strips `undefined` values from objects and arrays.\n * Used by codec encode/decode to clean wire data.\n *\n * Extracted to its own module so client-safe code (boundaryHelpers)\n * can import it without pulling in zod via utils.ts.\n */\nexport function stripUndefined<T>(value: T): T {\n if (value === null || value === undefined) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUndefined) as T\n }\n\n // Only process plain objects (not class instances, Dates, etc.)\n if (typeof value === 'object' && value.constructor === Object) {\n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n result[key] = stripUndefined(val)\n }\n }\n return result as T\n }\n\n return value\n}\n","import type { FunctionReference } from 'convex/server'\nimport type { $ZodIssue } from 'zod/v4/core'\nimport { safeEncode } from './normalizeCodecPaths'\nimport { stripUndefined } from './stripUndefined'\nimport type { AnyRegistry } from './types'\nimport { $ZodError, safeParse } from './zod-core'\n\n/**\n * Resolves a Convex FunctionReference to its string path.\n *\n * Mirrors `getFunctionName` from `convex/server` but without the server import.\n * Reads the well-known `Symbol.for('functionName')` that Convex attaches to all\n * function references — the same symbol used by Convex's own browser client.\n */\nconst functionNameSymbol = Symbol.for('functionName')\n\nfunction resolveFunctionPath(ref: FunctionReference<any, any, any, any>): string {\n if (typeof ref === 'string') return ref\n const name = (ref as any)[functionNameSymbol]\n if (!name) {\n throw new Error(\n `Expected a Convex function reference (e.g. api.file.func), but received ${JSON.stringify(ref)}`\n )\n }\n return name\n}\n\n/**\n * Options for codec helper behavior.\n */\nexport type BoundaryHelpersOptions = {\n /**\n * How to handle decode failures (schema validation errors on wire data).\n *\n * - `'warn'` (default): log a console.warn and return raw wire data untransformed.\n * - `'throw'`: throw a ZodvexDecodeError (extends z.ZodError). // zod-ok\n */\n onDecodeError?: 'warn' | 'throw'\n}\n\n/**\n * Decode error with function path and wire data context.\n * Extends $ZodError from zod/v4/core for compatibility with both zod and zod/mini.\n * instanceof $ZodError checks work in both variants.\n */\nexport class ZodvexDecodeError extends $ZodError {\n readonly functionPath: string\n readonly wireData: unknown\n\n constructor(functionPath: string, issues: $ZodIssue[], wireData: unknown) {\n super(issues)\n this.functionPath = functionPath\n this.wireData = wireData\n this.name = 'ZodvexDecodeError'\n }\n}\n\n/**\n * Creates shared encode/decode helpers bound to a zodvex registry.\n *\n * These are the core primitives used by all codec boundary implementations:\n * - `encodeArgs`: runtime types -> wire format (e.g., Date -> timestamp number)\n * - `decodeResult`: wire format -> runtime types (e.g., timestamp number -> Date)\n *\n * Both look up the function reference in the registry to find the appropriate\n * Zod schema, then apply the codec transform. Functions not in the registry\n * (or without the relevant schema) pass through unchanged.\n *\n * @param registry - A map of function paths to `{ args?, returns? }` Zod schemas.\n * Typically generated by zodvex codegen into `_zodvex/api.ts`.\n * @param options - Optional configuration for decode error behavior.\n */\nexport function createBoundaryHelpers(registry: AnyRegistry, options?: BoundaryHelpersOptions) {\n const onDecodeError = options?.onDecodeError ?? 'warn'\n const warnedPaths = new Set<string>()\n\n /**\n * Encode args from runtime types to wire format.\n *\n * Uses `safeEncode` (not raw `z.encode`) to normalize codec-internal\n * error paths in ZodErrors, then strips undefined values for Convex\n * serialization compatibility.\n *\n * Passthrough when:\n * - args is null/undefined\n * - function is not in the registry\n * - registry entry has no args schema\n */\n function encodeArgs(ref: FunctionReference<any, any, any, any>, args: any): any {\n if (args == null) return args\n const path = resolveFunctionPath(ref)\n const entry = registry[path]\n if (!entry?.args) {\n if (entry === undefined && !warnedPaths.has(path)) {\n warnedPaths.add(path)\n console.debug(\n `[zodvex] No registry entry for \"${path}\" — args will not be codec-encoded. ` +\n 'If this function uses zodvex wrappers, run `zodvex generate` to update the registry.'\n )\n }\n return args\n }\n return stripUndefined(safeEncode(entry.args, args))\n }\n\n /**\n * Decode a wire result back to runtime types.\n *\n * Uses `.safeParse()` to decode. On failure:\n * - 'warn' (default): logs warning, returns raw wireResult\n * - 'throw': throws ZodvexDecodeError (extends z.ZodError) // zod-ok\n *\n * Passthrough when:\n * - function is not in the registry\n * - registry entry has no returns schema\n */\n function decodeResult(ref: FunctionReference<any, any, any, any>, wireResult: any): any {\n const path = resolveFunctionPath(ref)\n const entry = registry[path]\n if (!entry?.returns) return wireResult\n\n const result = safeParse(entry.returns, wireResult)\n if (result.success) return result.data\n\n if (onDecodeError === 'throw') {\n throw new ZodvexDecodeError(path, result.error.issues, wireResult)\n }\n\n // Default: warn and return raw wire data\n const preview = JSON.stringify(wireResult)\n const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview\n console.warn(\n `[zodvex] Decode failed for ${path}: ${result.error.issues.map((i: $ZodIssue) => `${i.path.join('.')}: ${i.message}`).join(', ')}. Returning raw wire data. Preview: ${truncated}`\n )\n return wireResult\n }\n\n return { encodeArgs, decodeResult }\n}\n\nexport type BoundaryHelpers = ReturnType<typeof createBoundaryHelpers>\n","/**\n * IDs + registry for Convex + Zod v4\n */\n\nimport type { GenericId } from 'convex/values'\nimport { z } from 'zod'\nimport type { $ZodType } from './zod-core'\n\n// Simple registry for metadata\nconst metadata = new WeakMap<$ZodType, any>()\n\nexport const registryHelpers = {\n getMetadata: (type: $ZodType) => metadata.get(type),\n setMetadata: (type: $ZodType, meta: any) => metadata.set(type, meta)\n}\n\n/**\n * Create a Zod validator for a Convex Id\n *\n * Compatible with AI SDK and other tools that don't support transforms.\n * Uses type-level branding instead of runtime transforms for GenericId<T> compatibility.\n *\n * @deprecated Use `zx.id()` instead for consistent naming with other zodvex helpers.\n * ```typescript\n * import { zx } from 'zodvex'\n * zx.id('users') // instead of zid('users')\n * ```\n *\n * @param tableName - The Convex table name for this ID\n * @returns A Zod string validator typed as GenericId<TableName>\n */\nexport function zid<TableName extends string>(\n tableName: TableName\n): $ZodType<GenericId<TableName>> & { _tableName: TableName } {\n // Create base string validator with refinement (no transform or brand)\n const baseSchema = z.string().check(\n z.refine(val => typeof val === 'string' && val.length > 0, {\n message: `Invalid ID for table \"${tableName}\"`\n }),\n // Add a human-readable marker for client-side introspection utilities\n // used in apps/native (e.g., to detect relationship fields in dynamic forms).\n z.describe(`convexId:${tableName}`)\n )\n\n // Store metadata for registry lookup so mapping can convert to v.id(tableName)\n registryHelpers.setMetadata(baseSchema, {\n isConvexId: true,\n tableName\n })\n\n // Add the tableName property for type-level detection\n const branded = baseSchema as any\n branded._tableName = tableName\n\n // Type assertion provides GenericId<TableName> typing without runtime transform\n // This maintains type safety while being compatible with AI SDK and similar tools\n return branded as $ZodType<GenericId<TableName>> & { _tableName: TableName }\n}\n\nexport type Zid<TableName extends string> = ReturnType<typeof zid<TableName>>\n","import { $ZodObject } from '../zod-core'\n\nexport function getObjectShape(obj: any): Record<string, any> {\n if (obj instanceof $ZodObject) {\n return obj._zod.def.shape as Record<string, any>\n }\n if (obj && typeof obj === 'object' && typeof obj.shape === 'object') {\n return obj.shape as Record<string, any>\n }\n return {}\n}\n","import type { GenericValidator, Validator } from 'convex/values'\nimport { v } from 'convex/values'\nimport { $ZodEnum, type $ZodType } from '../../zod-core'\n\n// Helper: Convert Zod enum types to Convex validators\nexport function convertEnumType(actualValidator: $ZodEnum): GenericValidator {\n const entries = actualValidator._zod.def.entries\n const options = Object.keys(entries)\n if (options && Array.isArray(options) && options.length > 0) {\n // Filter out undefined/null and convert to Convex validators\n const validLiterals = options\n .filter((opt: any) => opt !== undefined && opt !== null)\n .map((opt: any) => v.literal(opt))\n\n if (validLiterals.length === 1) {\n const [first] = validLiterals\n return first as Validator<any, 'required', any>\n } else if (validLiterals.length >= 2) {\n const [first, second, ...rest] = validLiterals\n return v.union(\n first as Validator<any, 'required', any>,\n second as Validator<any, 'required', any>,\n ...rest\n )\n } else {\n return v.any()\n }\n } else {\n return v.any()\n }\n}\n","import type { GenericValidator } from 'convex/values'\nimport { v } from 'convex/values'\nimport { $ZodNullable, $ZodOptional, $ZodType } from '../../zod-core'\n\n// Helper: Convert Zod nullable types to Convex validators\nexport function convertNullableType(\n actualValidator: $ZodNullable,\n visited: Set<$ZodType>,\n zodToConvexInternal: (schema: $ZodType, visited: Set<$ZodType>) => any\n): { validator: GenericValidator; isOptional: boolean } {\n const innerSchema = actualValidator._zod.def.innerType\n if (innerSchema && innerSchema instanceof $ZodType) {\n // Check if the inner schema is optional\n if (innerSchema instanceof $ZodOptional) {\n // For nullable(optional(T)), we want optional(union(T, null))\n const innerInnerSchema = innerSchema._zod.def.innerType\n const innerInnerValidator = zodToConvexInternal(innerInnerSchema, visited)\n return {\n validator: v.union(innerInnerValidator, v.null()),\n isOptional: true // Mark as optional so it gets wrapped later\n }\n } else {\n const innerValidator = zodToConvexInternal(innerSchema, visited)\n return {\n validator: v.union(innerValidator, v.null()),\n isOptional: false\n }\n }\n } else {\n return {\n validator: v.any(),\n isOptional: false\n }\n }\n}\n","import type { GenericValidator } from 'convex/values'\nimport { v } from 'convex/values'\nimport { $ZodDefault, $ZodOptional, $ZodRecord, $ZodType } from '../../zod-core'\n\n// Helper: Convert Zod record types to Convex validators\nexport function convertRecordType(\n actualValidator: $ZodRecord,\n visited: Set<$ZodType>,\n zodToConvexInternal: (schema: $ZodType, visited: Set<$ZodType>) => any\n): GenericValidator {\n // $ZodRecord._zod.def has keyType and valueType\n let valueType: $ZodType | undefined = actualValidator._zod.def.valueType\n\n // If valueType is undefined, fall back to keyType (single-argument z.record() form)\n if (!valueType) {\n valueType = actualValidator._zod.def.keyType\n }\n\n if (valueType && valueType instanceof $ZodType) {\n // First check if the Zod value type is optional before conversion\n const isZodOptional =\n valueType instanceof $ZodOptional ||\n valueType instanceof $ZodDefault ||\n (valueType instanceof $ZodDefault && valueType._zod.def.innerType instanceof $ZodOptional)\n\n if (isZodOptional) {\n // For optional record values, we need to handle this specially\n let innerType: any\n let recordDefaultValue: any = undefined\n let recordHasDefault = false\n\n if (valueType instanceof $ZodDefault) {\n // Handle ZodDefault wrapper\n recordHasDefault = true\n recordDefaultValue = valueType._zod.def.defaultValue\n const innerFromDefault = valueType._zod.def.innerType\n if (innerFromDefault instanceof $ZodOptional) {\n innerType = innerFromDefault._zod.def.innerType\n } else {\n innerType = innerFromDefault\n }\n } else if (valueType instanceof $ZodOptional) {\n // Direct ZodOptional\n innerType = valueType._zod.def.innerType\n } else {\n // Shouldn't happen based on isZodOptional check\n innerType = valueType\n }\n\n // Convert the inner type to Convex and wrap in union with null\n const innerConvex = zodToConvexInternal(innerType, visited)\n const unionValidator = v.union(innerConvex, v.null())\n\n // Add default metadata if present\n if (recordHasDefault) {\n ;(unionValidator as any)._zodDefault = recordDefaultValue\n }\n\n return v.record(v.string(), unionValidator)\n } else {\n // Non-optional values can be converted normally\n return v.record(v.string(), zodToConvexInternal(valueType, visited))\n }\n } else {\n return v.record(v.string(), v.any())\n }\n}\n","import type { GenericValidator, Validator } from 'convex/values'\nimport { v } from 'convex/values'\nimport { $ZodDiscriminatedUnion, type $ZodType, $ZodUnion } from '../../zod-core'\n\n// Helper: Convert Zod discriminated union types to Convex validators\nexport function convertDiscriminatedUnionType(\n actualValidator: $ZodType,\n visited: Set<$ZodType>,\n zodToConvexInternal: (schema: $ZodType, visited: Set<$ZodType>) => any\n): GenericValidator {\n const options =\n actualValidator instanceof $ZodDiscriminatedUnion\n ? actualValidator._zod.def.options\n : // cast: fallback for non-standard discriminated union variants\n (actualValidator as any)._zod?.def?.options\n if (options) {\n const opts = Array.isArray(options) ? options : Array.from(options)\n if (opts.length >= 2) {\n // IMPORTANT: Create a new visited set for each union member to prevent false circular\n // reference detection. The same schema can legitimately appear in multiple union branches.\n const convexOptions = opts.map((opt: any) => {\n const branchVisited = new Set(visited)\n return zodToConvexInternal(opt, branchVisited)\n }) as Validator<any, 'required', any>[]\n const [first, second, ...rest] = convexOptions\n return v.union(\n first as Validator<any, 'required', any>,\n second as Validator<any, 'required', any>,\n ...rest\n )\n } else {\n return v.any()\n }\n } else {\n return v.any()\n }\n}\n\n// Helper: Convert Zod union types to Convex validators\nexport function convertUnionType(\n actualValidator: $ZodUnion,\n visited: Set<$ZodType>,\n zodToConvexInternal: (schema: $ZodType, visited: Set<$ZodType>) => any\n): GenericValidator {\n const options = actualValidator._zod.def.options\n if (options && Array.isArray(options) && options.length > 0) {\n if (options.length === 1) {\n return zodToConvexInternal(options[0], visited)\n } else {\n // Convert each option recursively\n // IMPORTANT: Create a new visited set for each union member to prevent false circular\n // reference detection. The same schema can legitimately appear in multiple union branches.\n // However, we do want to preserve the parent visited set to catch actual circular refs\n // that involve the union itself.\n const convexOptions = options.map((opt: any) => {\n // Create a new Set that includes the parent's visited schemas but won't pollute it\n const branchVisited = new Set(visited)\n return zodToConvexInternal(opt, branchVisited)\n }) as Validator<any, 'required', any>[]\n if (convexOptions.length >= 2) {\n const [first, second, ...rest] = convexOptions\n return v.union(\n first as Validator<any, 'required', any>,\n second as Validator<any, 'required', any>,\n ...rest\n )\n } else {\n return v.any()\n }\n }\n } else {\n return v.any()\n }\n}\n","import { v } from 'convex/values'\nimport { registryHelpers, type Zid } from '../ids'\nimport { getObjectShape } from '../schema/objectShape'\nimport { $ZodType } from '../zod-core'\n\n// Helper to check if a schema is a Zid\nexport function isZid<T extends string>(schema: $ZodType): schema is Zid<T> {\n // Check our metadata registry for ConvexId marker\n const metadata = registryHelpers.getMetadata(schema)\n return (\n metadata?.isConvexId === true && metadata?.tableName && typeof metadata.tableName === 'string'\n )\n}\n\n// union helpers\nexport function makeUnion(members: any[]): any {\n const nonNull = members.filter(Boolean)\n if (nonNull.length === 0) return v.any()\n if (nonNull.length === 1) return nonNull[0]\n return v.union(nonNull[0], nonNull[1], ...nonNull.slice(2))\n}\n\nexport { getObjectShape }\n","import type { GenericValidator, PropertyValidators } from 'convex/values'\nimport { v } from 'convex/values'\nimport { registryHelpers } from '../ids'\nimport {\n $ZodArray,\n $ZodCodec,\n $ZodDefault,\n $ZodEnum,\n $ZodLazy,\n $ZodLiteral,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodRecord,\n type $ZodShape,\n $ZodTuple,\n $ZodType,\n $ZodUnion\n} from '../zod-core'\nimport {\n convertDiscriminatedUnionType,\n convertEnumType,\n convertNullableType,\n convertRecordType,\n convertUnionType\n} from './handlers'\nimport type {\n ConvexValidatorFromZod,\n ConvexValidatorFromZodFieldsAuto,\n ZodValidator\n} from './types'\nimport { isZid } from './utils'\n\n// Module-scoped cache: same Zod schema instance → same Convex validator.\n// Avoids redundant allocations when the same schema is converted across\n// multiple function registrations or table definitions.\nconst convexValidatorCache = new WeakMap<$ZodType, GenericValidator>()\n\n// Internal conversion function using ZodType with def.type detection\nfunction zodToConvexInternal<Z extends $ZodType>(\n zodValidator: Z,\n visited: Set<$ZodType> = new Set()\n): ConvexValidatorFromZod<Z, 'required'> {\n // Guard against undefined/null validators (can happen with { field: undefined } in args)\n if (!zodValidator) {\n return v.any() as ConvexValidatorFromZod<Z, 'required'>\n }\n\n // Return cached result if this exact Zod instance was already converted\n const cached = convexValidatorCache.get(zodValidator)\n if (cached) {\n return cached as ConvexValidatorFromZod<Z, 'required'>\n }\n\n // Detect circular references to prevent infinite recursion\n if (visited.has(zodValidator)) {\n return v.any() as ConvexValidatorFromZod<Z, 'required'>\n }\n visited.add(zodValidator)\n\n // Check for default and optional wrappers\n let actualValidator = zodValidator\n let isOptional = false\n let defaultValue: any = undefined\n let hasDefault = false\n\n // Handle ZodDefault (which wraps ZodOptional when using .optional().default())\n if (zodValidator instanceof $ZodDefault) {\n hasDefault = true\n defaultValue = zodValidator._zod.def.defaultValue\n actualValidator = zodValidator._zod.def.innerType as Z\n }\n\n // Check for optional (may be wrapped inside ZodDefault)\n if (actualValidator instanceof $ZodOptional) {\n isOptional = true\n actualValidator = actualValidator._zod.def.innerType as Z\n\n // If the unwrapped type is ZodDefault, handle it here\n if (actualValidator instanceof $ZodDefault) {\n hasDefault = true\n defaultValue = actualValidator._zod.def.defaultValue\n actualValidator = actualValidator._zod.def.innerType as Z\n }\n }\n\n let convexValidator: GenericValidator\n\n // Check for Zid first (special case)\n if (isZid(actualValidator)) {\n const metadata = registryHelpers.getMetadata(actualValidator)\n const tableName = metadata?.tableName || 'unknown'\n convexValidator = v.id(tableName)\n } else {\n // Use def.type for robust, performant type detection instead of instanceof checks.\n // Rationale:\n // 1. Performance: Single switch statement vs. cascading instanceof checks\n // 2. Completeness: def.type covers ALL Zod variants including formats (email, url, uuid, etc.)\n // 3. Future-proof: Zod's internal structure is stable; instanceof checks can miss custom types\n // 4. Precision: def.type distinguishes between semantically different types (date vs number)\n // This private API access is intentional and necessary for comprehensive type coverage.\n // cast: switch handles more defType values than $ZodTypeDef types (e.g. discriminatedUnion)\n const defType = actualValidator._zod.def.type as string\n\n switch (defType) {\n case 'string':\n // This catches ZodString and ALL string format types (email, url, uuid, etc.)\n convexValidator = v.string()\n break\n case 'number':\n convexValidator = v.float64()\n break\n case 'bigint':\n convexValidator = v.int64()\n break\n case 'boolean':\n convexValidator = v.boolean()\n break\n case 'date':\n // LEGACY: Maps z.date() to v.float64() for backwards compatibility in type inference.\n // However, z.date() does NOT work at runtime because:\n // 1. z.date() produces Date objects, not numbers\n // 2. Convex rejects Date objects as non-serializable\n // 3. z.encode() on z.date() returns a Date, not a timestamp\n // Use zx.date() instead, which provides proper Date ↔ timestamp codec.\n // The wrappers and convexCodec will throw if z.date() is used.\n convexValidator = v.float64()\n break\n case 'null':\n convexValidator = v.null()\n break\n case 'nan':\n convexValidator = v.float64()\n break\n case 'array': {\n if (actualValidator instanceof $ZodArray) {\n const element = actualValidator._zod.def.element\n convexValidator = v.array(zodToConvexInternal(element, visited))\n } else {\n convexValidator = v.array(v.any())\n }\n break\n }\n case 'object': {\n if (actualValidator instanceof $ZodObject) {\n const shape = actualValidator._zod.def.shape\n const convexShape: PropertyValidators = {}\n for (const [key, value] of Object.entries(shape)) {\n if (value && value instanceof $ZodType) {\n convexShape[key] = zodToConvexInternal(value, visited)\n }\n }\n convexValidator = v.object(convexShape)\n } else {\n convexValidator = v.object({})\n }\n break\n }\n case 'union': {\n if (actualValidator instanceof $ZodUnion) {\n convexValidator = convertUnionType(actualValidator, visited, zodToConvexInternal)\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'discriminatedUnion': {\n convexValidator = convertDiscriminatedUnionType(\n actualValidator,\n visited,\n zodToConvexInternal\n )\n break\n }\n case 'literal': {\n if (actualValidator instanceof $ZodLiteral) {\n const literalValues = actualValidator._zod.def.values\n const firstValue = literalValues.values().next().value\n if (firstValue !== undefined && firstValue !== null) {\n convexValidator = v.literal(firstValue)\n } else {\n convexValidator = v.any()\n }\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'enum': {\n if (actualValidator instanceof $ZodEnum) {\n convexValidator = convertEnumType(actualValidator)\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'record': {\n if (actualValidator instanceof $ZodRecord) {\n convexValidator = convertRecordType(actualValidator, visited, zodToConvexInternal)\n } else {\n convexValidator = v.record(v.string(), v.any())\n }\n break\n }\n case 'transform':\n case 'pipe': {\n // Check for native Zod v4 codec first (z.codec())\n // Codecs have def.type='pipe' but are specifically for bidirectional transforms\n // Use the input schema (wire format) for Convex validation\n if (actualValidator instanceof $ZodCodec) {\n const inputSchema = actualValidator._zod.def.in\n if (inputSchema && inputSchema instanceof $ZodType) {\n convexValidator = zodToConvexInternal(inputSchema, visited)\n } else {\n convexValidator = v.any()\n }\n } else {\n // Check for brand metadata\n const metadata = registryHelpers.getMetadata(actualValidator)\n if (metadata?.brand && metadata?.originalSchema) {\n // For branded types created by our zBrand function, use the original schema\n convexValidator = zodToConvexInternal(metadata.originalSchema, visited)\n } else {\n // Non-codec transform - extract input schema but warn\n // cast: no instanceof guard available for generic pipe/transform\n const inputSchema = (actualValidator as any)._zod?.def?.in\n if (inputSchema && inputSchema instanceof $ZodType) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n '[zodvex] z.transform() detected. Using input schema for Convex validation.\\n' +\n 'Transforms are unidirectional - they work for parsing but not encoding.\\n' +\n 'For bidirectional transforms, use zx.codec() instead.'\n )\n }\n convexValidator = zodToConvexInternal(inputSchema, visited)\n } else {\n convexValidator = v.any()\n }\n }\n }\n break\n }\n case 'nullable': {\n if (actualValidator instanceof $ZodNullable) {\n const result = convertNullableType(actualValidator, visited, zodToConvexInternal)\n convexValidator = result.validator\n if (result.isOptional) {\n isOptional = true\n }\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'tuple': {\n // Handle tuple types as objects with numeric keys\n if (actualValidator instanceof $ZodTuple) {\n const items = actualValidator._zod.def.items\n if (items && items.length > 0) {\n const convexShape: PropertyValidators = {}\n items.forEach((item, index) => {\n convexShape[`_${index}`] = zodToConvexInternal(item, visited)\n })\n convexValidator = v.object(convexShape)\n } else {\n convexValidator = v.object({})\n }\n } else {\n convexValidator = v.object({})\n }\n break\n }\n case 'lazy': {\n // Handle lazy schemas by resolving them\n // Circular references are protected by the visited set check at function start\n if (actualValidator instanceof $ZodLazy) {\n try {\n const getter = actualValidator._zod.def.getter\n if (getter) {\n const resolvedSchema = getter()\n if (resolvedSchema && resolvedSchema instanceof $ZodType) {\n convexValidator = zodToConvexInternal(resolvedSchema, visited)\n } else {\n convexValidator = v.any()\n }\n } else {\n convexValidator = v.any()\n }\n } catch {\n // If resolution fails, fall back to 'any'\n convexValidator = v.any()\n }\n } else {\n convexValidator = v.any()\n }\n break\n }\n case 'any':\n // Handle z.any() directly\n convexValidator = v.any()\n break\n case 'unknown':\n // Handle z.unknown() as any\n convexValidator = v.any()\n break\n case 'undefined':\n case 'void':\n case 'never':\n // These types don't have good Convex equivalents\n convexValidator = v.any()\n break\n case 'intersection':\n // Can't properly handle intersections\n convexValidator = v.any()\n break\n case 'optional': {\n // Fallback for optional types that weren't caught by the instanceof check above.\n // cast: no instanceof guard — this handles edge cases where defType='optional'\n // but the schema isn't a $ZodOptional instance (e.g. pipes wrapped with .optional())\n const innerType = (actualValidator as any)._zod?.def?.innerType\n if (innerType && innerType instanceof $ZodType) {\n convexValidator = zodToConvexInternal(innerType, visited)\n isOptional = true\n } else {\n convexValidator = v.any()\n isOptional = true\n }\n break\n }\n default:\n // For any unrecognized def.type, return v.any()\n // No instanceof fallbacks - keep it simple and performant\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[zodvex] Unrecognized Zod type \"${defType}\" encountered. Falling back to v.any().`,\n 'Schema:',\n actualValidator\n )\n }\n convexValidator = v.any()\n break\n }\n }\n\n // For optional or default fields, always use v.optional()\n const finalValidator = isOptional || hasDefault ? v.optional(convexValidator) : convexValidator\n\n // Add metadata if there's a default value\n if (hasDefault && typeof finalValidator === 'object' && finalValidator !== null) {\n ;(finalValidator as any)._zodDefault = defaultValue\n }\n\n // Cache the result so the same Zod instance returns the same Convex validator\n convexValidatorCache.set(zodValidator, finalValidator)\n\n return finalValidator as ConvexValidatorFromZod<Z, 'required'>\n}\n\nexport function zodToConvex<Z extends $ZodType | ZodValidator>(\n zod: Z\n): Z extends $ZodType\n ? ConvexValidatorFromZod<Z, 'required'>\n : Z extends ZodValidator\n ? ConvexValidatorFromZodFieldsAuto<Z>\n : never {\n if (typeof zod === 'object' && zod !== null && !(zod instanceof $ZodType)) {\n return zodToConvexFields(zod as ZodValidator) as any\n }\n\n return zodToConvexInternal(zod as $ZodType) as any\n}\n\nexport function zodToConvexFields<Z extends $ZodShape>(\n zod: Z\n): ConvexValidatorFromZodFieldsAuto<Z> {\n // If it's a ZodObject, extract the shape\n const fields = zod instanceof $ZodObject ? zod._zod.def.shape : zod\n\n // Build the result object directly to preserve types\n const result: any = {}\n for (const [key, value] of Object.entries(fields)) {\n result[key] = zodToConvexInternal(value as $ZodType)\n }\n\n return result as ConvexValidatorFromZodFieldsAuto<Z>\n}\n","import { z } from 'zod'\nimport { $ZodDate, $ZodType, globalRegistry } from './zod-core'\n\n// ============================================================================\n// JSON Schema Override Support\n// ============================================================================\n// Zod's toJSONSchema doesn't support transforms, brands, and other \"unrepresentable\"\n// types by default. This module provides overrides for zodvex-managed types\n// so they can be used with AI SDKs and other JSON Schema-based tools.\n\n/**\n * Checks if a schema is a zid (Convex ID) schema by looking at its description.\n * zid schemas are marked with \"convexId:{tableName}\" in their description.\n */\nexport function isZidSchema(schema: $ZodType): boolean {\n const description = globalRegistry.get(schema)?.description\n return typeof description === 'string' && description.startsWith('convexId:')\n}\n\n/**\n * Extracts the table name from a zid schema's description.\n * Returns undefined if not a zid schema.\n */\nexport function getZidTableName(schema: $ZodType): string | undefined {\n const description = globalRegistry.get(schema)?.description\n if (typeof description === 'string' && description.startsWith('convexId:')) {\n return description.slice('convexId:'.length)\n }\n return undefined\n}\n\n/**\n * Context object passed to the JSON Schema override function.\n * Uses 'any' types for compatibility with Zod's internal types.\n */\nexport interface JSONSchemaOverrideContext {\n zodSchema: any // Zod's internal $ZodTypes\n jsonSchema: any // Zod's JSONSchema.BaseSchema\n}\n\n/**\n * Override function for z.toJSONSchema that handles zodvex-managed types.\n *\n * Handles:\n * - zx.id() schemas: Converts to { type: \"string\" } with convexId format\n * - zx.date(): Converts to { type: \"string\", format: \"date-time\" }\n *\n * @example\n * ```ts\n * import { z } from 'zod'\n * import { zx, zodvexJSONSchemaOverride } from 'zodvex'\n *\n * const schema = z.object({\n * userId: zx.id('users'),\n * name: z.string()\n * })\n *\n * const jsonSchema = z.toJSONSchema(schema, {\n * unrepresentable: 'any',\n * override: zodvexJSONSchemaOverride\n * })\n * // => { type: \"object\", properties: { userId: { type: \"string\" }, name: { type: \"string\" } } }\n * ```\n */\nexport function zodvexJSONSchemaOverride(ctx: JSONSchemaOverrideContext): void {\n const { zodSchema, jsonSchema } = ctx\n\n // Handle zid schemas (transforms with convexId description)\n if (isZidSchema(zodSchema)) {\n const tableName = getZidTableName(zodSchema)\n // Set our properties - don't clear existing ones set by user overrides\n // When unrepresentable: 'any', Zod already gives us {} so no clearing needed\n jsonSchema.type = 'string'\n if (tableName) {\n jsonSchema.format = `convex-id:${tableName}`\n }\n // Preserve the description from .describe() - this is what the LLM sees\n // Use globalRegistry for mini compatibility (zod/mini lacks the .description getter)\n const schemaDescription = globalRegistry.get(zodSchema)?.description\n if (schemaDescription) {\n jsonSchema.description = schemaDescription\n }\n return\n }\n\n // Handle z.date() - convert to ISO 8601 string format\n // Zod v4 passes real schema instances here (ZodDate has `type === 'date'`).\n if (zodSchema instanceof $ZodDate || zodSchema._zod.def.type === 'date') {\n jsonSchema.type = 'string'\n jsonSchema.format = 'date-time'\n return\n }\n}\n\n/**\n * Composes multiple JSON Schema override functions into one.\n * Overrides run in order - first override runs first.\n *\n * @example\n * ```ts\n * import { composeOverrides, zodvexJSONSchemaOverride } from 'zodvex'\n *\n * const myOverride = (ctx) => {\n * if (ctx.zodSchema.description?.startsWith('myType:')) {\n * ctx.jsonSchema.type = 'string'\n * ctx.jsonSchema.format = 'my-format'\n * }\n * }\n *\n * // User's override runs first, then zodvex's\n * z.toJSONSchema(schema, {\n * unrepresentable: 'any',\n * override: composeOverrides(myOverride, zodvexJSONSchemaOverride)\n * })\n * ```\n */\nexport function composeOverrides(\n ...overrides: Array<((ctx: JSONSchemaOverrideContext) => void) | undefined>\n): (ctx: JSONSchemaOverrideContext) => void {\n return (ctx: JSONSchemaOverrideContext) => {\n for (const override of overrides) {\n override?.(ctx)\n }\n }\n}\n\n/**\n * Options for toJSONSchema, matching Zod's interface.\n */\nexport interface ToJSONSchemaOptions {\n target?: 'draft-4' | 'draft-7' | 'draft-2020-12' | 'openapi-3.0'\n unrepresentable?: 'throw' | 'any'\n cycles?: 'ref' | 'throw'\n reused?: 'ref' | 'inline'\n io?: 'input' | 'output'\n override?: (ctx: JSONSchemaOverrideContext) => void\n}\n\n/**\n * Converts a Zod schema to JSON Schema with zodvex-aware overrides.\n *\n * This is a convenience wrapper around z.toJSONSchema that automatically\n * handles zodvex-managed types like zx.id() and zx.date().\n *\n * @example\n * ```ts\n * import { zx, toJSONSchema } from 'zodvex'\n *\n * const schema = z.object({\n * userId: zx.id('users'),\n * createdAt: zx.date(),\n * name: z.string()\n * })\n *\n * const jsonSchema = toJSONSchema(schema)\n * // Works with AI SDK's generateObject, etc.\n * ```\n */\nexport function toJSONSchema<T extends $ZodType>(\n schema: T,\n options?: ToJSONSchemaOptions\n): Record<string, any> {\n const userOverride = options?.override\n\n return z.toJSONSchema(schema, {\n ...options,\n // Default to 'any' so transforms don't throw\n unrepresentable: options?.unrepresentable ?? 'any',\n // Chain our override with user's override\n override: ctx => {\n zodvexJSONSchemaOverride(ctx)\n userOverride?.(ctx)\n }\n })\n}\n","import { z } from 'zod'\nimport type { $ZodType } from './zod-core'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Result type for mutations that return data on success.\n */\nexport type MutationResult<T> = { success: true; data: T } | { success: false; error: string }\n\n/**\n * Result type for mutations that don't return data (void operations).\n */\nexport type VoidMutationResult = { success: true } | { success: false; error: string }\n\n/**\n * Error structure for form validation results.\n */\nexport type FormError = {\n formErrors: string[]\n fieldErrors: Record<string, string[]>\n}\n\n/**\n * Result type for form submissions with field-level error support.\n * Preserves submitted data on failure for form re-population.\n */\nexport type FormResult<TData> =\n | { success: true; data: TData }\n | { success: false; data: TData; error: FormError }\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Create a success result with data.\n * @example success({ id: '123' })\n */\nexport const success = <T>(data: T) => ({ success: true, data }) as const\n\n/**\n * Create a failure result with an error message.\n * @example failure('Not found')\n */\nexport const failure = (error: string) => ({ success: false, error }) as const\n\n/**\n * Create a void success result (no data).\n * @example ok()\n */\nexport const ok = () => ({ success: true }) as const\n\n/**\n * Create a form success result with data.\n * @example formSuccess({ email: 'user@example.com' })\n */\nexport const formSuccess = <T>(data: T) => ({ success: true, data }) as const\n\n/**\n * Create a form failure result with data and errors.\n * @example formFailure({ email: 'bad' }, { formErrors: [], fieldErrors: { email: ['Invalid'] } })\n */\nexport const formFailure = <T>(data: T, error: FormError) =>\n ({ success: false, data, error }) as const\n\n// ============================================================================\n// Zod Schemas for `returns` validation\n// ============================================================================\n\n/**\n * Zod schema for MutationResult<T>.\n * Use in `returns` option to validate mutation responses.\n * @example zMutationResult(z.object({ id: zid('users') }))\n */\nexport const zMutationResult = <T extends $ZodType>(dataSchema: T) =>\n z.discriminatedUnion('success', [\n z.object({ success: z.literal(true), data: dataSchema }),\n z.object({ success: z.literal(false), error: z.string() })\n ])\n\n/**\n * Zod schema for VoidMutationResult.\n * Use in `returns` option for void mutations.\n * @example returns: zVoidMutationResult\n */\nexport const zVoidMutationResult = z.discriminatedUnion('success', [\n z.object({ success: z.literal(true) }),\n z.object({ success: z.literal(false), error: z.string() })\n])\n\n/**\n * Zod schema for FormError.\n */\nexport const zFormError = z.object({\n formErrors: z.array(z.string()),\n fieldErrors: z.record(z.string(), z.array(z.string()))\n})\n\n/**\n * Zod schema for FormResult<T>.\n * Use in `returns` option for form submissions.\n * @example zFormResult(z.object({ email: z.string() }))\n */\nexport const zFormResult = <T extends $ZodType>(dataSchema: T) =>\n z.discriminatedUnion('success', [\n z.object({ success: z.literal(true), data: dataSchema }),\n z.object({ success: z.literal(false), data: dataSchema, error: zFormError })\n ])\n","import { z } from 'zod'\nimport {\n $ZodArray,\n $ZodCodec,\n $ZodDate,\n $ZodDefault,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodRecord,\n $ZodTuple,\n $ZodType,\n $ZodUnion\n} from '../zod-core'\n\n/**\n * @deprecated Use `zx.date()` instead for automatic Date ↔ timestamp conversion.\n */\nexport function mapDateFieldToNumber(field: $ZodType): $ZodType {\n if (field instanceof $ZodDate) {\n return z.number()\n }\n if (field instanceof $ZodOptional && field._zod.def.innerType instanceof $ZodDate) {\n return z.optional(z.number())\n }\n if (field instanceof $ZodNullable && field._zod.def.innerType instanceof $ZodDate) {\n return z.nullable(z.number())\n }\n if (field instanceof $ZodDefault) {\n const inner = field._zod.def.innerType\n if (inner instanceof $ZodDate) {\n return z.optional(z.number())\n }\n }\n return field\n}\n\nfunction containsNativeZodDate(schema: $ZodType): boolean {\n if (schema instanceof $ZodDate) return true\n if (schema instanceof $ZodCodec) return false\n\n if (\n schema instanceof $ZodOptional ||\n schema instanceof $ZodNullable ||\n schema instanceof $ZodDefault\n ) {\n return containsNativeZodDate(schema._zod.def.innerType)\n }\n\n if (schema instanceof $ZodObject) {\n return Object.values(schema._zod.def.shape).some(field => containsNativeZodDate(field))\n }\n if (schema instanceof $ZodArray) {\n return containsNativeZodDate(schema._zod.def.element)\n }\n if (schema instanceof $ZodUnion) {\n return schema._zod.def.options.some(opt => containsNativeZodDate(opt))\n }\n if (schema instanceof $ZodRecord) {\n return containsNativeZodDate(schema._zod.def.valueType)\n }\n if (schema instanceof $ZodTuple) {\n const items = schema._zod.def.items\n return items ? items.some(item => containsNativeZodDate(item)) : false\n }\n\n return false\n}\n\nexport function assertNoNativeZodDate(\n schema: $ZodType,\n context: 'args' | 'returns' | 'schema'\n): void {\n if (containsNativeZodDate(schema)) {\n throw new Error(\n `[zodvex] Native z.date() found in ${context}. ` +\n `Convex stores dates as timestamps (numbers), which z.date() cannot parse.\\n\\n` +\n `Fix: Replace z.date() with zx.date()\\n\\n` +\n `Before: { createdAt: z.date() }\\n` +\n `After: { createdAt: zx.date() }\\n\\n` +\n `zx.date() is a codec that handles timestamp ↔ Date conversion automatically.`\n )\n }\n}\n","import { z } from 'zod'\nimport { getObjectShape } from './objectShape'\n\ntype Mask = readonly string[] | Record<string, boolean | 1 | true>\n\n// Type alias — keeps z.ZodObject off {-ending function signature lines (formatter-safe). // zod-ok\ntype AnyZodObject = z.ZodObject<any> // zod-ok\n\nfunction toKeys(mask: Mask): string[] {\n if (Array.isArray(mask)) return mask.map(String)\n return Object.keys(mask).filter(k => !!(mask as any)[k])\n}\n\nexport function pickShape(\n schemaOrShape: AnyZodObject | Record<string, any>,\n mask: Mask\n): Record<string, any> {\n const keys = toKeys(mask)\n const shape =\n schemaOrShape instanceof z.ZodObject ? getObjectShape(schemaOrShape) : schemaOrShape || {}\n\n const out: Record<string, any> = {}\n for (const k of keys) {\n if (k in shape) out[k] = (shape as any)[k]\n }\n return out\n}\n\nexport function safePick(schema: AnyZodObject, mask: Mask): AnyZodObject {\n return z.object(pickShape(schema, mask))\n}\n\nexport function safeOmit(schema: AnyZodObject, mask: Mask): AnyZodObject {\n const shape = getObjectShape(schema)\n const omit = new Set(toKeys(mask))\n const keep = Object.keys(shape).filter(k => !omit.has(k))\n const picked = pickShape(schema, keep)\n return z.object(picked)\n}\n","import { z } from 'zod'\nimport { $ZodNullable, $ZodOptional, $ZodType, type input as zinput } from '../zod-core'\n\nexport function returnsAs<R extends $ZodType>() {\n return <T extends zinput<R>>(v: T) => v\n}\n\n/** Wrap in .nullable().optional() using core constructors for zod-mini compat. */\nfunction nullableOptional(schema: $ZodType): $ZodType {\n return new $ZodOptional({\n type: 'optional',\n innerType: new $ZodNullable({ type: 'nullable', innerType: schema })\n }) as any\n}\n\nexport function zPaginated<T extends $ZodType>(item: T) {\n return z.object({\n page: z.array(item),\n isDone: z.boolean(),\n continueCursor: z.string(),\n splitCursor: nullableOptional(z.string()),\n pageStatus: nullableOptional(z.enum(['SplitRecommended', 'SplitRequired']))\n })\n}\n","import { z } from 'zod'\nimport { zodToConvex } from './mapping'\nimport { assertNoNativeZodDate } from './schema/dateGuards'\nimport { stripUndefined } from './stripUndefined'\nimport { type ZodvexCodec } from './types'\nimport {\n $ZodObject,\n $ZodOptional,\n $ZodType,\n encode,\n parse,\n type infer as zinfer,\n type input as zinput,\n type output as zoutput\n} from './zod-core'\n\n// Re-export ZodvexCodec type for convenience\nexport { type ZodvexCodec } from './types'\n\n/** @deprecated Use `initZodvex` or `decodeDoc`/`encodeDoc` instead. Will be removed in a future release. */\nexport type ConvexCodec<T> = {\n validator: any\n encode: (value: T) => any\n decode: (value: any) => T\n pick: <K extends keyof T>(keys: K[]) => ConvexCodec<Pick<T, K>>\n}\n\n/** @deprecated Use `initZodvex` or `decodeDoc`/`encodeDoc` instead. Will be removed in a future release. */\nexport function convexCodec<T>(schema: $ZodType<T>): ConvexCodec<T> {\n // Fail fast if z.date() is used - it won't encode correctly\n // Use zx.date() instead for Date ↔ timestamp conversion\n assertNoNativeZodDate(schema as $ZodType, 'schema')\n\n const validator = zodToConvex(schema)\n\n return {\n validator,\n // Strip undefined to ensure Convex-safe output (Convex rejects explicit undefined)\n encode: (value: T) => stripUndefined(encode(schema, value)),\n decode: (value: any) => parse(schema, value),\n pick: <K extends keyof T>(keys: K[] | Record<K, true>) => {\n if (!(schema instanceof $ZodObject)) {\n throw new Error('pick() can only be called on object schemas')\n }\n // Handle both array and object formats\n // Use manual shape extraction instead of .pick() — not available on zod/mini\n const pickKeys = Array.isArray(keys) ? keys : (Object.keys(keys) as K[])\n const shape = (schema as any)._zod.def.shape\n const pickedShape: Record<string, any> = {}\n for (const k of pickKeys) {\n if (k in shape) pickedShape[k as string] = shape[k as string]\n }\n const pickedSchema = z.object(pickedShape)\n return convexCodec(pickedSchema) as ConvexCodec<Pick<T, K>>\n }\n }\n}\n\n/**\n * Decodes a wire-format document (from Convex DB) to runtime types.\n * Runs Zod codec decode transforms (e.g., timestamp → Date via zx.date()).\n */\nexport function decodeDoc<S extends $ZodType>(schema: S, wireDoc: unknown): zoutput<S> {\n return parse(schema, wireDoc)\n}\n\n/**\n * Encodes a runtime document to wire format (for Convex DB writes).\n * Runs Zod codec encode transforms and strips undefined values.\n */\nexport function encodeDoc<S extends $ZodType>(schema: S, runtimeDoc: zoutput<S>): zinput<S> {\n return stripUndefined(encode(schema, runtimeDoc))\n}\n\n/**\n * Encodes a partial runtime document to wire format (for Convex DB patch operations).\n * Only encodes the fields present in the partial. Uses schema.partial() + z.encode().\n */\nexport function encodePartialDoc<S extends $ZodType>(\n schema: S,\n partial: Partial<zoutput<S>>\n): Partial<zinput<S>> {\n if (!(schema instanceof $ZodObject)) {\n // For non-object schemas (unions, etc.), fall back to full encode\n // Cast needed: Partial<output<S>> is structurally compatible but not assignable to output<S>\n return stripUndefined(encode(schema, partial as zoutput<S>)) as Partial<zinput<S>>\n }\n // Use manual shape wrapping instead of .partial() — not available on zod/mini\n const shape = (schema as any)._zod.def.shape\n const partialShape: Record<string, any> = {}\n for (const [key, value] of Object.entries(shape)) {\n partialShape[key] =\n value instanceof $ZodOptional\n ? value\n : new $ZodOptional({ type: 'optional', innerType: value as any })\n }\n const partialSchema = z.object(partialShape)\n return stripUndefined(encode(partialSchema, partial)) as Partial<zinput<S>>\n}\n\n/**\n * Creates a branded ZodCodec for use with zodvex type inference.\n * Thin wrapper around z.codec() that adds type branding, allowing\n * ConvexValidatorFromZod to extract the wire schema even when the\n * codec is wrapped in a custom type alias.\n *\n * @example\n * ```typescript\n * type MyCodec = ZodvexCodec<z.ZodObject<{ ts: z.ZodNumber }>, z.ZodCustom<Date>> // zod-ok\n *\n * function myCodec(): MyCodec {\n * return zodvexCodec(\n * z.object({ ts: z.number() }),\n * z.custom<Date>(() => true),\n * {\n * decode: (wire) => new Date(wire.ts),\n * encode: (date) => ({ ts: date.getTime() })\n * }\n * )\n * }\n * ```\n */\nexport function zodvexCodec<\n W extends $ZodType,\n R extends $ZodType,\n WO = zoutput<W>,\n RI = zoutput<R>\n>(\n wire: W,\n runtime: R,\n transforms: {\n decode: (wire: WO) => RI\n encode: (runtime: RI) => WO\n }\n): ZodvexCodec<W, R> {\n // Cast transforms to satisfy Zod's internal MaybeAsync typing while keeping our API simple\n return z.codec(wire as any, runtime as any, transforms as any) as unknown as ZodvexCodec<W, R>\n}\n","import {\n zodvexCodec as _zodvexCodec,\n type ConvexCodec,\n convexCodec,\n decodeDoc,\n encodeDoc,\n encodePartialDoc\n} from '../internal/codec'\nimport type { $ZodType, output as zoutput } from '../internal/zod-core'\nimport type { FullZodvexCodec } from '../internal/zx'\n\nexport { type ConvexCodec, convexCodec, decodeDoc, encodeDoc, encodePartialDoc }\n\nexport type ZodvexCodec<Wire extends $ZodType, Runtime extends $ZodType> = FullZodvexCodec<\n Wire,\n Runtime\n>\n\nexport function zodvexCodec<\n W extends $ZodType,\n R extends $ZodType,\n WO = zoutput<W>,\n RI = zoutput<R>\n>(\n wire: W,\n runtime: R,\n transforms: {\n decode: (wire: WO) => RI\n encode: (runtime: RI) => WO\n }\n): ZodvexCodec<W, R> {\n return _zodvexCodec(wire, runtime, transforms) as unknown as ZodvexCodec<W, R>\n}\n","import type { $ZodType } from './zod-core'\n\nconst META_KEY = '__zodvexMeta'\n\nexport type ZodvexFunctionMeta = {\n type: 'function'\n zodArgs?: $ZodType\n zodReturns?: $ZodType\n}\n\nexport type ZodvexModelDefinitionSource = 'shape' | 'schema'\n\nexport type ZodvexModelMeta = {\n type: 'model'\n tableName: string\n definitionSource?: ZodvexModelDefinitionSource\n schemas?: {\n doc: $ZodType\n insert: $ZodType\n update: $ZodType\n docArray: $ZodType\n paginatedDoc: $ZodType\n }\n}\n\nexport type ZodvexMeta = ZodvexFunctionMeta | ZodvexModelMeta\n\nexport function attachMeta(target: object, meta: ZodvexMeta): void {\n Object.defineProperty(target, META_KEY, {\n value: meta,\n enumerable: false,\n writable: false,\n configurable: false\n })\n}\n\nexport function readMeta(target: unknown): ZodvexMeta | undefined {\n if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {\n return undefined\n }\n return (target as Record<string, unknown>)[META_KEY] as ZodvexMeta | undefined\n}\n\nconst CODEC_BRAND_KEY = '__zodvexCodecBrand'\n\n/**\n * Attaches a provenance brand to a codec instance. Codegen reads this at\n * discovery time to match a function-embedded codec to its importable twin\n * by *declared* identity instead of inferring it from structure. Stored\n * non-enumerably so it never leaks into user data, and survives\n * `.optional()` / `.nullable()` wrapping (codegen unwraps to the codec).\n * See `docs/decisions/2026-06-08-codec-provenance-brands.md`.\n */\nexport function attachCodecBrand(target: object, brand: string): void {\n Object.defineProperty(target, CODEC_BRAND_KEY, {\n value: brand,\n enumerable: false,\n writable: false,\n configurable: false\n })\n}\n\n/** Reads a codec's provenance brand, or undefined if unbranded. */\nexport function readCodecBrand(target: unknown): string | undefined {\n if (target == null || typeof target !== 'object') return undefined\n const value = (target as Record<string, unknown>)[CODEC_BRAND_KEY]\n return typeof value === 'string' ? value : undefined\n}\n","import { readMeta } from '../../internal/meta'\nimport {\n $ZodCodec,\n $ZodCustom,\n $ZodNullable,\n $ZodNumber,\n $ZodOptional,\n $ZodType\n} from '../../internal/zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable layers to find the inner ZodCodec.\n * Returns the codec instance, or undefined if none found.\n * Skips zx.date() (ZodCodec with in=ZodNumber, out=ZodCustom).\n *\n * Used internally by the discovery pipeline to probe schemas for codecs.\n */\nexport function findCodec(schema: $ZodType): $ZodType | undefined {\n let current = schema\n for (let i = 0; i < 10; i++) {\n if (current instanceof $ZodCodec) {\n const isZxDate =\n current._zod.def.in instanceof $ZodNumber && current._zod.def.out instanceof $ZodCustom\n if (isZxDate) return undefined\n return current\n }\n if (current instanceof $ZodOptional || current instanceof $ZodNullable) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return undefined\n}\n\n/**\n * Extracts the inner ZodCodec from a schema, throwing if none is found.\n * The codegen only emits extractCodec() calls for schemas it has verified\n * contain a codec during discovery, so a missing codec is a bug.\n *\n * Used by generated _zodvex/api.ts to extract codec references at runtime.\n */\nexport function extractCodec(schema: $ZodType): $ZodType {\n const codec = findCodec(schema)\n if (!codec) {\n throw new Error('zodvex: extractCodec() found no codec in schema — this is a codegen bug')\n }\n return codec\n}\n\n/**\n * Extracts the zodArgs schema from a zodvex-registered function.\n * Used by generated _zodvex/api.ts to access function-embedded codecs at runtime.\n */\nexport function readFnArgs(fn: unknown): $ZodType {\n const meta = readMeta(fn)\n if (!meta || meta.type !== 'function' || !meta.zodArgs) {\n throw new Error('zodvex: function has no zodArgs metadata')\n }\n return meta.zodArgs as $ZodType\n}\n\n/**\n * Extracts the zodReturns schema from a zodvex-registered function.\n * Used by generated _zodvex/api.ts to access function-embedded codecs at runtime.\n */\nexport function readFnReturns(fn: unknown): $ZodType {\n const meta = readMeta(fn)\n if (!meta || meta.type !== 'function' || !meta.zodReturns) {\n throw new Error('zodvex: function has no zodReturns metadata')\n }\n return meta.zodReturns as $ZodType\n}\n","/**\n * zx - zodvex extended validators\n *\n * A namespace for zodvex-specific validators and codecs that handle\n * Convex wire format transformations. The \"zx\" prefix signals:\n * - \"zodvex\" or \"zod + convex\" extended types\n * - Explicit transformations (not magic)\n * - Discoverable via IDE autocomplete on `zx.`\n *\n * @example\n * ```typescript\n * import { z } from 'zod'\n * import { zx } from 'zodvex'\n *\n * const userShape = {\n * name: z.string(), // Standard Zod\n * createdAt: zx.date(), // zodvex: Date ↔ timestamp\n * teamId: zx.id('teams'), // zodvex: Convex ID\n * }\n * ```\n */\n\nimport type { GenericId } from 'convex/values'\nimport { z } from 'zod'\nimport { zodvexCodec } from './codec'\nimport { registryHelpers } from './ids'\nimport { attachCodecBrand } from './meta'\nimport { createSchemaUpdateSchema } from './modelSchemaBundle'\nimport { addSystemFields } from './schemaHelpers'\nimport type { ZodvexCodec } from './types'\nimport {\n type $ZodCustom,\n $ZodNullable,\n type $ZodNumber,\n $ZodOptional,\n type $ZodType,\n $ZodType as $ZodTypeValue,\n type output as zoutput\n} from './zod-core'\n\n/**\n * Date codec type for explicit type annotations\n */\nexport type FullZodvexCodec<W extends $ZodType, R extends $ZodType> = z.ZodCodec<W, R> &\n ZodvexCodec<W, R>\n\nexport type ZxDate = FullZodvexCodec<$ZodNumber, $ZodCustom<Date, Date>>\n\n/**\n * Creates a Date codec that transforms between Date objects and timestamps.\n *\n * Wire format: number (Unix timestamp in milliseconds)\n * Runtime format: Date object\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * createdAt: zx.date(),\n * updatedAt: zx.date().optional(),\n * })\n * ```\n */\nfunction date(): ZxDate {\n return zodvexCodec(\n z.number(), // Wire: timestamp\n z.custom<Date>(val => val instanceof Date, {\n message: 'Expected Date instance'\n }),\n {\n decode: (timestamp: number) => new Date(timestamp),\n encode: (date: Date) => date.getTime()\n }\n ) as unknown as ZxDate\n}\n\n/**\n * ID type for explicit type annotations\n */\nexport type ZxId<TableName extends string> = z.ZodString &\n z.ZodType<GenericId<TableName>> & {\n _tableName: TableName\n }\n\n/**\n * Creates a Convex ID validator for a specific table.\n *\n * Wire format: string (Convex ID)\n * Runtime format: GenericId<TableName> (branded string type)\n *\n * Note: Unlike zx.date(), IDs don't require runtime transformation since\n * GenericId<T> is a branded string type. The branding is purely type-level.\n *\n * @param tableName - The Convex table name for this ID\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * userId: zx.id('users'),\n * teamId: zx.id('teams').optional(),\n * })\n * ```\n */\nfunction id<TableName extends string>(tableName: TableName): ZxId<TableName> {\n // Create base string validator with refinement\n const baseSchema = z.string().check(\n z.refine(val => typeof val === 'string' && val.length > 0, {\n message: `Invalid ID for table \"${tableName}\"`\n }),\n z.describe(`convexId:${tableName}`)\n )\n\n // Store metadata for registry lookup so mapping can convert to v.id(tableName)\n registryHelpers.setMetadata(baseSchema, {\n isConvexId: true,\n tableName\n })\n\n // Add the tableName property for type-level detection\n const branded = baseSchema as any\n branded._tableName = tableName\n\n return branded as ZxId<TableName>\n}\n\n/**\n * Creates a custom codec for transforming between wire and runtime formats.\n *\n * Use this when you need custom transformations beyond the built-in helpers.\n *\n * @param wire - Zod schema for the wire format (stored in Convex)\n * @param runtime - Zod schema for the runtime format (used in code)\n * @param transforms - Encode/decode functions\n * @param opts.brand - Optional provenance brand. When set, codegen matches a\n * function-embedded instance of this codec to its importable twin (an\n * exported const or model field with the same brand) by *declared* identity\n * rather than inferring it from structure — collision-free and namespaced\n * across factories. Useful for codec factories like `tagged()` / `sensitive()`\n * whose every call returns a fresh instance. See\n * `docs/decisions/2026-06-08-codec-provenance-brands.md`.\n *\n * @example\n * ```typescript\n * // Encrypted data codec\n * const encryptedString = zx.codec(\n * z.object({ encrypted: z.string() }), // Wire format\n * z.custom<string>(() => true), // Runtime format\n * {\n * decode: (wire) => decrypt(wire.encrypted),\n * encode: (value) => ({ encrypted: encrypt(value) })\n * }\n * )\n *\n * // Branded factory codec — codegen matches inline instances by brand\n * function tagged(inner, name) {\n * return zx.codec(wire(inner), runtime(inner), transforms, { brand: `tagged:${name}` })\n * }\n * ```\n */\nfunction codec<W extends $ZodType, R extends $ZodType, WO = zoutput<W>, RI = zoutput<R>>(\n wire: W,\n runtime: R,\n transforms: {\n decode: (wire: WO) => RI\n encode: (runtime: RI) => WO\n },\n opts?: { brand?: string }\n): FullZodvexCodec<W, R> {\n const built = zodvexCodec(wire, runtime, transforms) as unknown as FullZodvexCodec<W, R>\n if (opts?.brand) attachCodecBrand(built as object, opts.brand)\n return built\n}\n\n/**\n * Minimal model shape accepted by zx helpers.\n * Both full and slim models satisfy this at runtime.\n */\ntype ZxModelInput = {\n readonly name: string\n readonly fields: Record<string, $ZodType>\n readonly schema?: unknown\n}\n\n/**\n * Per-model caches so repeated `zx.doc(model)` / `zx.base(model)` / etc. calls\n * across call sites share a single Zod schema instance.\n *\n * Caches are keyed on a stable identity that survives chain methods\n * (`.index()`, `.searchIndex()`, `.vectorIndex()`), which return new model\n * objects but preserve `fields` (object slim) and `schema` (union slim) by\n * reference. Keying on the model object would force every chain step to\n * re-allocate.\n *\n * Full models bypass these caches entirely — they carry a pre-built schema\n * bundle, and `zx.*(fullModel)` returns the bundle's schema directly so\n * identity matches `fullModel.schema.{doc,base,...}`.\n *\n * The cache maps are pinned to `globalThis` under a `Symbol.for` registry so\n * multiple bundled copies of this module share state. tsup splits each entry\n * into its own bundle (CLI, codegen, main, server, …), duplicating this file\n * per entry. Without the shared registry, `zx.doc(Model)` in user code\n * (loaded from `dist/index.js`) and `zx.doc(ref)` in codegen (loaded from\n * `dist/cli/index.js`) would write to distinct WeakMaps, producing different\n * instances for the same model — identity matching would silently fail.\n */\nfunction sharedWeakMap(name: string): WeakMap<object, $ZodType> {\n const key = Symbol.for(`zodvex.zx.cache.${name}`)\n const g = globalThis as unknown as Record<symbol, WeakMap<object, $ZodType>>\n const existing = g[key]\n if (existing) return existing\n const created = new WeakMap<object, $ZodType>()\n g[key] = created\n return created\n}\n\nconst baseCache = sharedWeakMap('base')\nconst docCache = sharedWeakMap('doc')\nconst updateCache = sharedWeakMap('update')\nconst docArrayCache = sharedWeakMap('docArray')\n\n/**\n * Stable cache key for slim models:\n * - union slim → the user-supplied schema (preserved across chains)\n * - object slim → the fields record (preserved across chains)\n */\nfunction slimCacheKey(model: ZxModelInput): object {\n const s = model.schema as any\n return s instanceof $ZodTypeValue ? s : model.fields\n}\n\n/**\n * Returns the base schema for a model — the user fields as a Zod object (or the\n * user-supplied union for discriminated-union models).\n *\n * Full models: returns the bundle's pre-built `.base` (no allocation).\n * Union slim: returns the user's schema (no allocation — it IS the base).\n * Object slim: builds `z.object(fields)` once, cached on `fields`.\n */\nfunction base(model: ZxModelInput): $ZodType {\n const s = model.schema as any\n if (s?.base instanceof $ZodTypeValue) return s.base\n if (s instanceof $ZodTypeValue) return s\n const cached = baseCache.get(model.fields)\n if (cached) return cached\n if (Object.keys(model.fields).length === 0) {\n throw new Error(`[zodvex] Cannot derive base schema for model '${model.name}'`)\n }\n const built = z.object(model.fields) as any\n baseCache.set(model.fields, built)\n return built\n}\n\n/**\n * Constructs a doc schema: base fields + _id + _creationTime.\n * Full models reuse `model.schema.doc`; slim models cache on slimCacheKey(model).\n */\nfunction doc(model: ZxModelInput) {\n const s = model.schema as any\n if (s?.doc instanceof $ZodTypeValue) return s.doc\n const key = slimCacheKey(model)\n const cached = docCache.get(key)\n if (cached) return cached\n const built = addSystemFields(model.name, base(model)) as any\n docCache.set(key, built)\n return built\n}\n\n/**\n * Constructs an update schema: _id required + _creationTime optional + all user fields optional.\n * Full models reuse `model.schema.update`; slim models cache on slimCacheKey(model).\n */\nfunction update(model: ZxModelInput) {\n const s = model.schema as any\n if (s?.update instanceof $ZodTypeValue) return s.update\n const key = slimCacheKey(model)\n const cached = updateCache.get(key)\n if (cached) return cached\n const built = createSchemaUpdateSchema(model.name, base(model)) as any\n updateCache.set(key, built)\n return built\n}\n\n/**\n * Constructs a doc array schema: z.array(doc(model)).\n * Full models reuse `model.schema.docArray`; slim models cache on slimCacheKey(model).\n */\nfunction docArray(model: ZxModelInput) {\n const s = model.schema as any\n if (s?.docArray instanceof $ZodTypeValue) return s.docArray\n const key = slimCacheKey(model)\n const cached = docArrayCache.get(key)\n if (cached) return cached\n const built = z.array(doc(model)) as any\n docArrayCache.set(key, built)\n return built\n}\n\n/** Wrap in .nullable() using core constructor for zod-mini compat. */\nfunction nullable(schema: $ZodType): $ZodType {\n return new $ZodNullable({ type: 'nullable', innerType: schema }) as any\n}\n\n/** Wrap in .optional() using core constructor for zod-mini compat. */\nfunction optional(schema: $ZodType): $ZodType {\n return new $ZodOptional({ type: 'optional', innerType: schema }) as any\n}\n\n/** Wrap in .nullable().optional() using core constructors for zod-mini compat. */\nfunction nullableOptional(schema: $ZodType): $ZodType {\n return optional(nullable(schema))\n}\n\n/**\n * Pagination options schema — matches Convex's PaginationOptions type.\n */\nfunction paginationOpts() {\n return z.object({\n numItems: z.number(),\n cursor: nullable(z.string()),\n endCursor: nullableOptional(z.string()),\n id: optional(z.number()),\n maximumRowsRead: optional(z.number()),\n maximumBytesRead: optional(z.number())\n })\n}\n\n/**\n * Paginated result schema — wraps any item schema in Convex's PaginationResult shape.\n */\nfunction paginationResult<T extends $ZodType>(itemSchema: T) {\n return z.object({\n page: z.array(itemSchema),\n isDone: z.boolean(),\n continueCursor: z.string(),\n splitCursor: nullableOptional(z.string()),\n pageStatus: nullableOptional(z.enum(['SplitRecommended', 'SplitRequired']))\n })\n}\n\n/**\n * zx namespace - zodvex extended validators\n *\n * Provides explicit, discoverable helpers for Convex-specific transformations.\n */\nexport const zx = {\n /**\n * Date ↔ timestamp codec\n * @see {@link date}\n */\n date,\n\n /**\n * Convex ID validator\n * @see {@link id}\n */\n id,\n\n /**\n * Custom codec builder\n * @see {@link codec}\n */\n codec,\n\n /**\n * Pagination options schema matching Convex's PaginationOptions type\n * @see {@link paginationOpts}\n */\n paginationOpts,\n\n /**\n * Paginated result schema wrapping any item schema in Convex's PaginationResult shape\n * @see {@link paginationResult}\n */\n paginationResult,\n\n /**\n * Base schema for a model (user fields only; no system fields).\n * For object models reconstructs from fields; for union models returns the\n * user-supplied union. Cached per-model.\n * @see {@link base}\n */\n base,\n\n /**\n * Doc schema: model fields + _id + _creationTime\n * @see {@link doc}\n */\n doc,\n\n /**\n * Update schema: _id required, all other fields optional\n * @see {@link update}\n */\n update,\n\n /**\n * Doc array schema: z.array(doc(model))\n * @see {@link docArray}\n */\n docArray\n} as const\n","/**\n * Schema helpers — Pure Zod utilities for union handling and system fields.\n *\n * This module contains helpers extracted from tables.ts that have NO server\n * dependencies (no convex/server, no convex-helpers/server). They are safe\n * to import from zodvex (client-side code).\n *\n * Used by:\n * - model.ts (defineZodModel) — client-safe model definitions\n * - tables.ts (zodTable) — server-side table definitions\n */\n\nimport { z } from 'zod'\nimport {\n $ZodArray,\n $ZodDiscriminatedUnion,\n $ZodNumber,\n $ZodObject,\n type $ZodShape,\n $ZodType,\n $ZodUnion,\n clone\n} from './zod-core'\nimport { type ZxId, zx } from './zx'\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Helper type for Convex system fields added to documents\n */\nexport type SystemFields<TableName extends string> = {\n _id: ZxId<TableName>\n _creationTime: $ZodNumber\n}\n\n/**\n * Maps over union options, extending each ZodObject variant with system fields.\n * Non-object variants are preserved as-is.\n */\nexport type MapSystemFields<TableName extends string, Options extends readonly $ZodType[]> = {\n [K in keyof Options]: Options[K] extends z.ZodObject<infer Shape extends $ZodShape> // zod-ok\n ? z.ZodObject<Shape & SystemFields<TableName>> // zod-ok\n : Options[K]\n}\n\n/**\n * Core-compatible version of MapSystemFields.\n * Uses $ZodObject from zod/v4/core instead of z.ZodObject from full zod. // zod-ok\n */\nexport type MapSystemFieldsCore<TableName extends string, Options extends readonly $ZodType[]> = {\n [K in keyof Options]: Options[K] extends $ZodObject<infer Shape extends $ZodShape>\n ? $ZodObject<Shape & SystemFields<TableName>>\n : Options[K]\n}\n\n/**\n * Computes the result of adding system fields to a union/object schema.\n * Uses only $Zod* types from zod/v4/core — safe for shared code and mini consumers.\n *\n * Handles:\n * - $ZodObject → $ZodObject with system fields\n * - $ZodUnion → $ZodUnion with system fields on each variant\n * - $ZodDiscriminatedUnion → $ZodDiscriminatedUnion with system fields on each variant\n * - Other → returned as-is\n */\nexport type AddSystemFieldsToUnion<TableName extends string, Schema extends $ZodType> =\n Schema extends $ZodObject<infer Shape extends $ZodShape>\n ? $ZodObject<Shape & SystemFields<TableName>>\n : Schema extends $ZodUnion<infer Options extends readonly $ZodType[]>\n ? $ZodUnion<MapSystemFieldsCore<TableName, Options>>\n : Schema extends $ZodDiscriminatedUnion<\n infer Options extends readonly $ZodType[],\n infer Disc extends string\n >\n ? $ZodDiscriminatedUnion<MapSystemFieldsCore<TableName, Options>, Disc>\n : Schema\n\n/**\n * Minimum tuple type required by z.union() - at least 2 elements.\n */\ntype UnionTuple<T extends $ZodType = $ZodType> = readonly [T, T, ...T[]]\n\n// ============================================================================\n// Union Helpers - Type-safe utilities for working with Zod unions\n// ============================================================================\n\n/** Full-zod union type alias used by isZodUnion/getUnionOptions — zod-ok by design. */\ntype AnyZodUnion =\n // zod-ok\n | z.ZodUnion<readonly $ZodType[]> // zod-ok\n | z.ZodDiscriminatedUnion<readonly z.ZodObject<$ZodShape>[], string> // zod-ok\n\n/**\n * Type guard to check if a schema is a union type (ZodUnion or ZodDiscriminatedUnion).\n */\nexport function isZodUnion(schema: $ZodType): schema is AnyZodUnion {\n return schema instanceof $ZodUnion || schema instanceof $ZodDiscriminatedUnion\n}\n\n/**\n * Extracts the options array from a ZodUnion or ZodDiscriminatedUnion.\n * Both union types have an `.options` property, but TypeScript doesn't\n * create a common accessor after instanceof checks.\n *\n * @param schema - A ZodUnion or ZodDiscriminatedUnion schema\n * @returns The array of union variant schemas\n */\nexport function getUnionOptions(schema: AnyZodUnion): readonly $ZodType[] {\n // $ZodDiscriminatedUnion extends $ZodUnion, so this covers both\n if (schema instanceof $ZodUnion) {\n return schema._zod.def.options\n }\n // cast: unreachable due to the union type constraint, but satisfies return type\n return (schema as any)._zod.def.options\n}\n\n/**\n * Asserts that an array has at least 2 elements, as required by z.union().\n * Throws an error if the array has fewer than 2 elements.\n *\n * @param options - Array of Zod schemas\n * @throws Error if array has fewer than 2 elements\n */\nexport function assertUnionOptions<T extends $ZodType>(\n options: readonly T[]\n): asserts options is UnionTuple<T> {\n if (options.length < 2) {\n throw new Error(\n `z.union() requires at least 2 options, but received ${options.length}. ` +\n 'This indicates an invalid union schema was passed to zodTable().'\n )\n }\n}\n\n/**\n * Creates a z.union() from an array of options with runtime validation.\n * Ensures the array has at least 2 elements as required by Zod.\n *\n * @param options - Array of Zod schemas (must have at least 2 elements)\n * @returns A ZodUnion schema\n * @throws Error if array has fewer than 2 elements\n */\n// Return type alias — prevents z.ZodUnion on a {-ending line (formatter-safe). // zod-ok\ntype ZodUnionOf<T extends $ZodType> = z.ZodUnion<UnionTuple<T>> // zod-ok\n\nexport function createUnionFromOptions<T extends $ZodType>(options: readonly T[]): ZodUnionOf<T> {\n assertUnionOptions(options)\n return z.union(options)\n}\n\n/**\n * Adds Convex system fields (_id, _creationTime) to a Zod schema.\n *\n * For object schemas: extends with system fields\n * For union schemas: adds system fields to each variant\n *\n * @param tableName - The Convex table name\n * @param schema - The Zod schema (object or union)\n * @returns Schema with system fields added\n */\n// Overload 1: ZodObject - extends with system fields\nexport function addSystemFields<TableName extends string, Shape extends $ZodShape>(\n tableName: TableName,\n schema: z.ZodObject<Shape> // zod-ok\n): z.ZodObject<Shape & SystemFields<TableName>> // zod-ok\n\n// Overload 2: ZodUnion - maps system fields to each variant\nexport function addSystemFields<TableName extends string, Options extends readonly $ZodType[]>(\n tableName: TableName,\n schema: z.ZodUnion<Options> // zod-ok\n): z.ZodUnion<MapSystemFields<TableName, Options>> // zod-ok\n\n// Overload 3: ZodDiscriminatedUnion - maps system fields preserving discriminator\n// Note: Zod v4 signature is ZodDiscriminatedUnion<Options, Discriminator>\nexport function addSystemFields<\n TableName extends string,\n Options extends readonly z.ZodObject<$ZodShape>[], // zod-ok\n Discriminator extends string\n>(\n tableName: TableName,\n schema: z.ZodDiscriminatedUnion<Options, Discriminator> // zod-ok\n): z.ZodDiscriminatedUnion<MapSystemFields<TableName, Options>, Discriminator> // zod-ok\n\n// Overload 4: Fallback for other ZodTypes - returns as-is\nexport function addSystemFields<TableName extends string, S extends $ZodType>(\n tableName: TableName,\n schema: S\n): S\n\n// Implementation\nexport function addSystemFields<TableName extends string>(\n tableName: TableName,\n schema: $ZodType\n): $ZodType {\n // Handle union schemas - add system fields to each variant\n if (isZodUnion(schema)) {\n const originalOptions = getUnionOptions(schema)\n const extendedOptions = originalOptions.map((variant: $ZodType) => {\n if (variant instanceof $ZodObject) {\n const newShape = {\n ...variant._zod.def.shape,\n _id: zx.id(tableName),\n _creationTime: z.number()\n }\n // Clone preserves the original's class + reinitializes with merged def\n return clone(variant, { ...variant._zod.def, shape: newShape })\n }\n // Non-object variants are returned as-is (shouldn't happen in practice)\n return variant\n })\n return createUnionFromOptions(extendedOptions)\n }\n\n // Handle object schemas — clone preserves class, checks, catchall, error\n if (schema instanceof $ZodObject) {\n const newShape = { ...schema._zod.def.shape, _id: zx.id(tableName), _creationTime: z.number() }\n return clone(schema, { ...schema._zod.def, shape: newShape })\n }\n\n // Fallback: return schema as-is\n return schema\n}\n","import { z } from 'zod'\nimport {\n addSystemFields,\n createUnionFromOptions,\n getUnionOptions,\n isZodUnion\n} from './schemaHelpers'\nimport { $ZodNullable, $ZodObject, $ZodOptional, type $ZodShape, $ZodType } from './zod-core'\nimport { zx } from './zx'\n\n// Return type alias so helper signatures don't expose full zod internals everywhere.\ntype AnyOptional = z.ZodOptional<any> // zod-ok\n\nexport type RuntimeModelSchemaBundle = {\n readonly doc: $ZodType\n readonly base: $ZodType\n readonly insert: $ZodType\n readonly update: $ZodType\n readonly docArray: $ZodType\n readonly paginatedDoc: $ZodType\n}\n\n/** Wrap in .optional() only if not already optional. Uses core constructor for zod-mini compat. */\nfunction ensureOptional(schema: $ZodType): AnyOptional {\n if (schema instanceof $ZodOptional) return schema as z.ZodOptional<any> // zod-ok\n return new $ZodOptional({ type: 'optional', innerType: schema }) as z.ZodOptional<any> // zod-ok\n}\n\n/** Wrap in .nullable().optional() using core constructors for zod-mini compat. */\nfunction nullableOptional(schema: $ZodType): $ZodType {\n return new $ZodOptional({\n type: 'optional',\n innerType: new $ZodNullable({ type: 'nullable', innerType: schema })\n }) as any\n}\n\nexport function createPartialShape(shape: Record<string, $ZodType>): Record<string, $ZodType> {\n const partialShape: Record<string, $ZodType> = {}\n for (const [key, value] of Object.entries(shape)) {\n partialShape[key] = ensureOptional(value)\n }\n return partialShape\n}\n\nexport function createUpdateObjectSchema<Name extends string>(\n name: Name,\n shape: Record<string, $ZodType>\n): z.ZodObject<any> {\n return z.object({\n _id: zx.id(name),\n _creationTime: z.optional(z.number()),\n ...createPartialShape(shape)\n })\n}\n\nexport function createPaginatedDocSchema(docSchema: $ZodType): z.ZodObject<any> {\n return z.object({\n page: z.array(docSchema),\n isDone: z.boolean(),\n continueCursor: z.string(),\n splitCursor: nullableOptional(z.string()),\n pageStatus: nullableOptional(z.enum(['SplitRecommended', 'SplitRequired']))\n })\n}\n\nexport function createObjectSchemaBundle<Name extends string>(\n name: Name,\n fields: $ZodShape,\n baseSchema: z.ZodObject<any> = z.object(fields)\n): RuntimeModelSchemaBundle {\n const docSchema = addSystemFields(name, baseSchema)\n\n return {\n doc: docSchema,\n base: baseSchema,\n insert: baseSchema,\n update: createUpdateObjectSchema(name, fields),\n docArray: z.array(docSchema),\n paginatedDoc: createPaginatedDocSchema(docSchema)\n }\n}\n\nexport function createSchemaUpdateSchema<Name extends string>(\n name: Name,\n inputSchema: $ZodType\n): $ZodType {\n if (isZodUnion(inputSchema)) {\n const updateOptions = getUnionOptions(inputSchema).map((variant: $ZodType) => {\n if (variant instanceof $ZodObject) {\n return createUpdateObjectSchema(name, variant._zod.def.shape)\n }\n return variant\n })\n return createUnionFromOptions(updateOptions)\n }\n\n if (inputSchema instanceof $ZodObject) {\n return createUpdateObjectSchema(name, inputSchema._zod.def.shape)\n }\n\n return inputSchema\n}\n\nexport function createSchemaBundle<Name extends string>(\n name: Name,\n inputSchema: $ZodType\n): RuntimeModelSchemaBundle {\n const docSchema = addSystemFields(name, inputSchema)\n\n return {\n doc: docSchema,\n base: inputSchema,\n insert: inputSchema,\n update: createSchemaUpdateSchema(name, inputSchema),\n docArray: z.array(docSchema),\n paginatedDoc: createPaginatedDocSchema(docSchema)\n }\n}\n","/**\n * defineZodModel — Client-safe model definitions with type-safe indexes\n *\n * This module is the client-safe spiritual successor to zodTable().\n * It produces Zod schemas for codec decode/encode and type-safe index\n * definitions via z.input<T> field path extraction.\n *\n * Exported from zodvex (no server imports).\n */\n\nimport { z } from 'zod'\nimport { attachMeta, type ZodvexModelDefinitionSource } from './meta'\nimport {\n createObjectSchemaBundle,\n createSchemaBundle,\n type RuntimeModelSchemaBundle\n} from './modelSchemaBundle'\nimport type { AddSystemFieldsToUnion } from './schemaHelpers'\nimport { $ZodArray, type $ZodShape, $ZodType, type input as zinput } from './zod-core'\nimport type { ZxId } from './zx'\n\n/**\n * Build the user-facing validator for a model. For raw-shape input we build\n * `z.object(fields)` lazily on first access; the bundle's `.insert` already\n * holds an equivalent for full models, but we want a stable identity that's\n * keyed on the model itself (so chained `.index()` calls don't reallocate).\n */\nfunction lazyValidator(fields: $ZodShape, userSchema: $ZodType | null): { get: () => $ZodType } {\n let cached: $ZodType | undefined\n return {\n get: () => {\n if (cached) return cached\n cached = userSchema ?? z.object(fields)\n return cached\n }\n }\n}\n\nfunction createModel<Name extends string>(\n name: Name,\n fields: $ZodShape,\n schema: RuntimeModelSchemaBundle,\n definitionSource: ZodvexModelDefinitionSource,\n indexes: Record<string, readonly string[]> = {},\n searchIndexes: Record<string, SearchIndexConfig> = {},\n vectorIndexes: Record<string, VectorIndexConfig> = {},\n // The user-supplied schema for overload-2 (definitionSource === 'schema').\n // Passing it through preserves identity across chained .index() calls; for\n // shape-input it's null and the lazy getter builds z.object(fields).\n userSchema: $ZodType | null = null\n): any {\n const validatorCache = lazyValidator(fields, userSchema)\n const model: any = {\n name,\n fields,\n schema,\n indexes,\n searchIndexes,\n vectorIndexes,\n get validator() {\n return validatorCache.get()\n },\n index(indexName: string, indexFields: readonly string[]) {\n return createModel(\n name,\n fields,\n schema,\n definitionSource,\n { ...indexes, [indexName]: [...indexFields, '_creationTime'] },\n searchIndexes,\n vectorIndexes,\n userSchema\n )\n },\n searchIndex(indexName: string, config: SearchIndexConfig) {\n return createModel(\n name,\n fields,\n schema,\n definitionSource,\n indexes,\n { ...searchIndexes, [indexName]: config },\n vectorIndexes,\n userSchema\n )\n },\n vectorIndex(indexName: string, config: VectorIndexConfig) {\n return createModel(\n name,\n fields,\n schema,\n definitionSource,\n indexes,\n searchIndexes,\n { ...vectorIndexes, [indexName]: config },\n userSchema\n )\n }\n }\n\n attachMeta(model, { type: 'model', tableName: name, definitionSource, schemas: schema })\n return model\n}\n\n/**\n * Factory for slim models (schemaHelpers: false).\n *\n * Object slim (definitionSource: 'shape'): `userSchema` is null. The model\n * carries only `{ name, fields, indexes, ... }` with no pre-built Zod schemas.\n * Consumers derive schemas on demand via cached zx helpers.\n *\n * Union slim (definitionSource: 'schema'): `userSchema` is the user-supplied\n * union/discriminated union. It can't be recreated from `fields`, so it must\n * be retained on the model. `fields` is `{}` in this case.\n */\nfunction createSlimModel<Name extends string>(\n name: Name,\n fields: $ZodShape,\n userSchema: $ZodType | null,\n definitionSource: ZodvexModelDefinitionSource,\n indexes: Record<string, readonly string[]> = {},\n searchIndexes: Record<string, SearchIndexConfig> = {},\n vectorIndexes: Record<string, VectorIndexConfig> = {}\n): any {\n const validatorCache = lazyValidator(fields, userSchema)\n const model: any = {\n name,\n fields,\n indexes,\n searchIndexes,\n vectorIndexes,\n get validator() {\n return validatorCache.get()\n },\n index(indexName: string, indexFields: readonly string[]) {\n return createSlimModel(\n name,\n fields,\n userSchema,\n definitionSource,\n { ...indexes, [indexName]: [...indexFields, '_creationTime'] },\n searchIndexes,\n vectorIndexes\n )\n },\n searchIndex(indexName: string, config: SearchIndexConfig) {\n return createSlimModel(\n name,\n fields,\n userSchema,\n definitionSource,\n indexes,\n { ...searchIndexes, [indexName]: config },\n vectorIndexes\n )\n },\n vectorIndex(indexName: string, config: VectorIndexConfig) {\n return createSlimModel(name, fields, userSchema, definitionSource, indexes, searchIndexes, {\n ...vectorIndexes,\n [indexName]: config\n })\n }\n }\n\n if (userSchema !== null) model.schema = userSchema\n\n attachMeta(model, { type: 'model', tableName: name, definitionSource })\n return model\n}\n\n// ============================================================================\n// Field Path Types\n// ============================================================================\n\n/**\n * Extract all valid field paths from a TypeScript object type.\n * Mirrors Convex's ExtractFieldPaths but operates on plain TS types\n * inferred from z.input<T> (wire format).\n *\n * - Recurses into nested objects to produce dotted paths (\"address.city\")\n * - Distributes over unions (T extends T trick)\n * - Excludes arrays (can't index into array elements)\n * - Unwraps nullable/optional via NonNullable before recursing\n */\nexport type FieldPaths<T> = T extends any[]\n ? never\n : T extends Record<string, any>\n ? T extends T // distribute over unions\n ? {\n [K in keyof T & string]:\n | K\n | (NonNullable<T[K]> extends any[]\n ? never\n : NonNullable<T[K]> extends Record<string, any>\n ? `${K}.${FieldPaths<NonNullable<T[K]>>}`\n : never)\n }[keyof T & string]\n : never\n : never\n\n/**\n * Field paths valid for index definitions on a model.\n * Uses z.input<T> to get wire-format paths, plus _creationTime system field.\n */\nexport type ModelFieldPaths<InsertSchema extends $ZodType> =\n | FieldPaths<zinput<InsertSchema>>\n | '_creationTime'\n\n// ============================================================================\n// Index Config Types\n// ============================================================================\n\nexport type SearchIndexConfig = {\n searchField: string\n filterFields?: string[]\n}\n\nexport type VectorIndexConfig = {\n vectorField: string\n dimensions: number\n filterFields?: string[]\n}\n\n// ============================================================================\n// ZodModel Type\n// ============================================================================\n\n/**\n * Constraint for the schema bundle carried by ZodModel.\n * Concrete types (FullZodModelSchemas, MiniModelSchemas) satisfy this.\n */\nexport type ModelSchemas = {\n readonly doc: $ZodType\n readonly base: $ZodType\n readonly insert: $ZodType\n readonly update: $ZodType\n readonly docArray: $ZodType\n readonly paginatedDoc: $ZodType\n}\n\n/**\n * Schema types for union/discriminated union models.\n * Preserves the specific Schema type so ConvexTableFor can compute\n * validators from the union, and consumers get typed schema.doc access.\n */\nexport type UnionModelSchemas<Name extends string, Schema extends $ZodType> = {\n readonly doc: AddSystemFieldsToUnion<Name, Schema>\n readonly base: Schema\n readonly insert: Schema\n readonly update: $ZodType\n readonly docArray: $ZodArray<AddSystemFieldsToUnion<Name, Schema>>\n readonly paginatedDoc: $ZodType\n}\n\n/** @internal Update shape for FullZodModelSchemas — full-zod types only. */ // zod-ok\ntype FullUpdateShape<Name extends string, Fields extends $ZodShape> = {\n // zod-ok\n _id: ZxId<Name> // zod-ok\n _creationTime: z.ZodOptional<z.ZodNumber> // zod-ok\n} & { [K in keyof Fields]: z.ZodOptional<Fields[K]> } // zod-ok\n\n/** @internal Doc shape used by docArray and paginatedDoc. */ // zod-ok\ntype FullDocShape<Name extends string, Fields extends $ZodShape> = Fields & {\n // zod-ok\n _id: ZxId<Name> // zod-ok\n _creationTime: z.ZodNumber // zod-ok\n} // zod-ok\n\n/** @internal PaginatedDoc shape for FullZodModelSchemas. */ // zod-ok\ntype FullPaginatedShape<Name extends string, Fields extends $ZodShape> = {\n // zod-ok\n page: z.ZodArray<z.ZodObject<FullDocShape<Name, Fields>>> // zod-ok\n isDone: z.ZodBoolean // zod-ok\n continueCursor: z.ZodOptional<z.ZodNullable<z.ZodString>> // zod-ok\n} // zod-ok\n\n/**\n * Full-zod schema types — the default for `zodvex` consumers.\n * Each property uses z.ZodObject / z.ZodArray etc. from full zod, // zod-ok\n * providing method chaining (.parse(), .shape, .nullable(), etc.).\n */\nexport type FullZodModelSchemas<Name extends string, Fields extends $ZodShape> = {\n readonly doc: z.ZodObject<FullDocShape<Name, Fields>> // zod-ok\n readonly base: z.ZodObject<Fields> // zod-ok\n readonly insert: z.ZodObject<Fields> // zod-ok\n readonly update: z.ZodObject<FullUpdateShape<Name, Fields>> // zod-ok\n readonly docArray: z.ZodArray<z.ZodObject<FullDocShape<Name, Fields>>> // zod-ok\n readonly paginatedDoc: z.ZodObject<FullPaginatedShape<Name, Fields>> // zod-ok\n}\n\n/**\n * A client-safe model definition with type-safe schemas and index metadata.\n *\n * Produced by defineZodModel(). Chainable via .index(), .searchIndex(), .vectorIndex().\n * Each chain call returns a new immutable model with accumulated metadata.\n *\n * The `Schemas` parameter carries the concrete schema types — full-zod types\n * from `zodvex`, mini types from `zodvex/mini`. Chain methods preserve `Schemas`\n * unchanged since they only modify index metadata.\n *\n * Downstream consumers wrap this to add domain metadata (e.g., security rules).\n */\nexport type ZodModel<\n Name extends string = string,\n Fields extends $ZodShape = $ZodShape,\n InsertSchema extends $ZodType = $ZodType,\n Schemas extends ModelSchemas = ModelSchemas,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = {\n readonly name: Name\n readonly fields: Fields\n readonly schema: Schemas\n readonly indexes: Indexes\n readonly searchIndexes: SearchIndexes\n readonly vectorIndexes: VectorIndexes\n /**\n * The user-facing, parseable validator for the model — see ZodModelBase\n * for the contract. Same `InsertSchema` type so refinements survive when\n * the model was constructed from a pre-built schema (#56).\n */\n readonly validator: InsertSchema\n\n index<\n IndexName extends string,\n First extends ModelFieldPaths<InsertSchema>,\n Rest extends ModelFieldPaths<InsertSchema>[]\n >(\n name: IndexName,\n fields: readonly [First, ...Rest]\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes & Record<IndexName, readonly [First, ...Rest, '_creationTime']>,\n SearchIndexes,\n VectorIndexes\n >\n\n searchIndex<IndexName extends string>(\n name: IndexName,\n config: SearchIndexConfig\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes,\n SearchIndexes & Record<IndexName, SearchIndexConfig>,\n VectorIndexes\n >\n\n vectorIndex<IndexName extends string>(\n name: IndexName,\n config: VectorIndexConfig\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes,\n SearchIndexes,\n VectorIndexes & Record<IndexName, VectorIndexConfig>\n >\n}\n\nexport type AnyZodModel = ZodModel<string, $ZodShape, $ZodType, ModelSchemas>\n\n// ============================================================================\n// ZodModelBase — internal constraint type (no schema bundle)\n// ============================================================================\n\n/**\n * Base model type — the contract that all zodvex internals constrain against.\n *\n * Deliberately excludes `schema` so that internal code (defineZodSchema,\n * tableFromModel, DB wrapper) cannot depend on the schema bundle shape.\n * This guarantees both full and slim models work with all internals.\n */\nexport type ZodModelBase<\n Name extends string = string,\n Fields extends $ZodShape = $ZodShape,\n InsertSchema extends $ZodType = $ZodType,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = {\n readonly name: Name\n readonly fields: Fields\n readonly indexes: Indexes\n readonly searchIndexes: SearchIndexes\n readonly vectorIndexes: VectorIndexes\n /**\n * The user-facing, parseable schema for the model — typed as exactly the\n * input the caller passed to `defineZodModel`:\n *\n * - For raw-shape input (overload 1): `z.object(model.fields)`, built\n * lazily on first access and cached. Equivalent to calling\n * `z.object(model.fields)` yourself, but typed precisely and shared.\n * - For pre-built schema input (overload 2): the exact schema you passed,\n * refinements / checks / wrappers preserved. Avoids the trap of\n * round-tripping through `fields` and dropping `.refine()` constraints.\n *\n * Designed for client-side validation use cases (TanStack Form, RHF,\n * standalone `.safeParse(...)`). See #56.\n */\n readonly validator: InsertSchema\n\n index<\n IndexName extends string,\n First extends ModelFieldPaths<InsertSchema>,\n Rest extends ModelFieldPaths<InsertSchema>[]\n >(\n name: IndexName,\n fields: readonly [First, ...Rest]\n ): ZodModelBase<\n Name,\n Fields,\n InsertSchema,\n Indexes & Record<IndexName, readonly [First, ...Rest, '_creationTime']>,\n SearchIndexes,\n VectorIndexes\n >\n\n searchIndex<IndexName extends string>(\n name: IndexName,\n config: SearchIndexConfig\n ): ZodModelBase<\n Name,\n Fields,\n InsertSchema,\n Indexes,\n SearchIndexes & Record<IndexName, SearchIndexConfig>,\n VectorIndexes\n >\n\n vectorIndex<IndexName extends string>(\n name: IndexName,\n config: VectorIndexConfig\n ): ZodModelBase<\n Name,\n Fields,\n InsertSchema,\n Indexes,\n SearchIndexes,\n VectorIndexes & Record<IndexName, VectorIndexConfig>\n >\n}\n\n/** Widened base type for internal constraints. */\nexport type AnyZodModelBase = ZodModelBase<string, $ZodShape, $ZodType>\n\n/** Options for defineZodModel. */\nexport type DefineZodModelOptions = {\n /**\n * When `true` (default), the model carries a full schema bundle with\n * `doc`, `base`, `insert`, `update`, `docArray`, `paginatedDoc`.\n *\n * When `false`, the model carries only `schema` (the base) and `doc`.\n * Use `zx.update(model)`, `zx.docArray(model)`, `zx.paginationResult(model.doc)`\n * to derive schemas on demand.\n *\n * @default true\n */\n schemaHelpers?: boolean\n}\n\n/**\n * Slim model for object shapes — produced when `schemaHelpers: false` with a raw shape.\n *\n * Carries only table name, fields, and index metadata — no pre-built Zod schemas.\n * Derive schemas on demand via cached `zx.*` helpers:\n * - `zx.doc(model)` — doc with system fields\n * - `zx.base(model)` — base object (user fields only)\n * - `zx.update(model)` — partial update schema\n * - `zx.docArray(model)` — array of docs\n * - `zx.paginationResult(zx.doc(model))` — paginated doc\n */\nexport type SlimObjectModel<\n Name extends string = string,\n Fields extends $ZodShape = $ZodShape,\n InsertSchema extends $ZodType = $ZodType,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = ZodModelBase<Name, Fields, InsertSchema, Indexes, SearchIndexes, VectorIndexes>\n\n/**\n * Slim model for union/discriminated union schemas — produced when `schemaHelpers: false`\n * with a pre-built schema.\n *\n * Retains the user-supplied `schema` since it can't be reconstructed from fields.\n * All other schemas derived on demand via `zx.*`.\n */\nexport type SlimUnionModel<\n Name extends string = string,\n Schema extends $ZodType = $ZodType,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = ZodModelBase<Name, $ZodShape, Schema, Indexes, SearchIndexes, VectorIndexes> & {\n readonly schema: Schema\n}\n\n// ============================================================================\n// defineZodModel\n// ============================================================================\n\n/**\n * Define a client-safe model with Zod schemas and type-safe index definitions.\n *\n * Accepts either a raw Zod shape (object mapping field names to Zod types) or\n * a pre-built Zod schema (union, discriminated union, or object).\n *\n * @param name - The table name (literal string type preserved)\n * @param fieldsOrSchema - Raw Zod shape or pre-built Zod schema\n * @returns A ZodModel with schemas, chainable index methods\n *\n * @example Raw shape (most common)\n * ```ts\n * const patients = defineZodModel('patients', {\n * clinicId: z.string(),\n * email: z.string().email().optional(),\n * createdAt: zx.date(),\n * })\n * .index('byClinic', ['clinicId'])\n * .index('byCreation', ['_creationTime'])\n * ```\n *\n * @example Discriminated union\n * ```ts\n * const visits = defineZodModel('visits', z.discriminatedUnion('type', [\n * z.object({ type: z.literal('phone'), duration: z.number() }),\n * z.object({ type: z.literal('in-person'), roomId: z.string() }),\n * ]))\n * .index('byType', ['type'])\n * ```\n */\n// Overload: raw shape with schemaHelpers: false → SlimObjectModel\nexport function defineZodModel<Name extends string, Fields extends $ZodShape>(\n name: Name,\n fields: Fields,\n options: { schemaHelpers: false }\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional\n): SlimObjectModel<Name, Fields, z.ZodObject<Fields>, {}, {}, {}> // zod-ok\n\n// Overload: pre-built schema with schemaHelpers: false → SlimUnionModel\nexport function defineZodModel<Name extends string, Schema extends $ZodType>(\n name: Name,\n schema: Schema,\n options: { schemaHelpers: false }\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional\n): SlimUnionModel<Name, Schema, {}, {}, {}>\n\n// Overload: raw shape (existing behavior)\nexport function defineZodModel<Name extends string, Fields extends $ZodShape>(\n name: Name,\n fields: Fields\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional — represents zero indexes/searchIndexes/vectorIndexes\n): ZodModel<Name, Fields, z.ZodObject<Fields>, FullZodModelSchemas<Name, Fields>, {}, {}, {}> // zod-ok\n\n// Overload: pre-built schema (union or object)\nexport function defineZodModel<Name extends string, Schema extends $ZodType>(\n name: Name,\n schema: Schema\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional — represents zero indexes/searchIndexes/vectorIndexes\n): ZodModel<Name, $ZodShape, Schema, UnionModelSchemas<Name, Schema>, {}, {}, {}>\n\n// Implementation\nexport function defineZodModel<Name extends string>(\n name: Name,\n fieldsOrSchema: $ZodShape | $ZodType,\n options?: DefineZodModelOptions\n): any {\n const slim = options?.schemaHelpers === false\n\n // Detect if input is a pre-built Zod schema (union, object, etc.) vs raw shape\n if (fieldsOrSchema instanceof $ZodType) {\n if (slim) {\n return createSlimModel(name, {}, fieldsOrSchema as $ZodType, 'schema')\n }\n return createModel(\n name,\n {},\n createSchemaBundle(name, fieldsOrSchema as $ZodType),\n 'schema',\n undefined,\n undefined,\n undefined,\n fieldsOrSchema as $ZodType\n )\n }\n\n const fields = fieldsOrSchema as $ZodShape\n if (slim) {\n // Object slim — no base schema retained; reconstructed from fields on demand.\n return createSlimModel(name, fields, null, 'shape')\n }\n return createModel(name, fields, createObjectSchemaBundle(name, fields), 'shape')\n}\n","import { z } from 'zod'\nimport {\n defineZodModel as _defineZodModel,\n type AnyZodModelBase,\n type DefineZodModelOptions,\n type SlimObjectModel,\n type SlimUnionModel,\n type ZodModelBase\n} from '../internal/model'\nimport type { AddSystemFieldsToUnion } from '../internal/schemaHelpers'\nimport { $ZodArray, type $ZodShape, $ZodType, type input as zinput } from '../internal/zod-core'\nimport type { ZxId } from './zx'\n\nexport type FieldPaths<T> = T extends any[]\n ? never\n : T extends Record<string, any>\n ? T extends T\n ? {\n [K in keyof T & string]:\n | K\n | (NonNullable<T[K]> extends any[]\n ? never\n : NonNullable<T[K]> extends Record<string, any>\n ? `${K}.${FieldPaths<NonNullable<T[K]>>}`\n : never)\n }[keyof T & string]\n : never\n : never\n\nexport type ModelFieldPaths<InsertSchema extends $ZodType> =\n | FieldPaths<zinput<InsertSchema>>\n | '_creationTime'\n\nexport type SearchIndexConfig = {\n searchField: string\n filterFields?: string[]\n}\n\nexport type VectorIndexConfig = {\n vectorField: string\n dimensions: number\n filterFields?: string[]\n}\n\nexport type ModelSchemas = {\n readonly doc: $ZodType\n readonly base: $ZodType\n readonly insert: $ZodType\n readonly update: $ZodType\n readonly docArray: $ZodType\n readonly paginatedDoc: $ZodType\n}\n\nexport type UnionModelSchemas<Name extends string, Schema extends $ZodType> = {\n readonly doc: AddSystemFieldsToUnion<Name, Schema>\n readonly base: Schema\n readonly insert: Schema\n readonly update: $ZodType\n readonly docArray: $ZodArray<AddSystemFieldsToUnion<Name, Schema>>\n readonly paginatedDoc: $ZodType\n}\n\ntype FullUpdateShape<Name extends string, Fields extends $ZodShape> = {\n _id: ZxId<Name>\n _creationTime: z.ZodOptional<z.ZodNumber>\n} & { [K in keyof Fields]: z.ZodOptional<Fields[K]> }\n\ntype FullDocShape<Name extends string, Fields extends $ZodShape> = Fields & {\n _id: ZxId<Name>\n _creationTime: z.ZodNumber\n}\n\ntype FullPaginatedShape<Name extends string, Fields extends $ZodShape> = {\n page: z.ZodArray<z.ZodObject<FullDocShape<Name, Fields>>>\n isDone: z.ZodBoolean\n continueCursor: z.ZodString\n splitCursor: z.ZodOptional<z.ZodNullable<z.ZodString>>\n pageStatus: z.ZodOptional<z.ZodNullable<z.ZodEnum>>\n}\n\nexport type FullZodModelSchemas<Name extends string, Fields extends $ZodShape> = {\n readonly doc: z.ZodObject<FullDocShape<Name, Fields>>\n readonly base: z.ZodObject<Fields>\n readonly insert: z.ZodObject<Fields>\n readonly update: z.ZodObject<FullUpdateShape<Name, Fields>>\n readonly docArray: z.ZodArray<z.ZodObject<FullDocShape<Name, Fields>>>\n readonly paginatedDoc: z.ZodObject<FullPaginatedShape<Name, Fields>>\n}\n\ntype DefaultFullModelSchemas<\n Name extends string,\n Fields extends $ZodShape,\n InsertSchema extends $ZodType\n> =\n InsertSchema extends z.ZodObject<Fields>\n ? FullZodModelSchemas<Name, Fields>\n : UnionModelSchemas<Name, InsertSchema>\n\nexport type ZodModel<\n Name extends string = string,\n Fields extends $ZodShape = $ZodShape,\n InsertSchema extends $ZodType = z.ZodObject<Fields>,\n Schemas extends ModelSchemas = DefaultFullModelSchemas<Name, Fields, InsertSchema>,\n Indexes extends Record<string, readonly string[]> = Record<string, readonly string[]>,\n SearchIndexes extends Record<string, SearchIndexConfig> = Record<string, SearchIndexConfig>,\n VectorIndexes extends Record<string, VectorIndexConfig> = Record<string, VectorIndexConfig>\n> = {\n readonly name: Name\n readonly fields: Fields\n readonly schema: Schemas\n readonly indexes: Indexes\n readonly searchIndexes: SearchIndexes\n readonly vectorIndexes: VectorIndexes\n /**\n * The user-facing, parseable validator for the model. For raw-shape input\n * this is `z.object(model.fields)`; for pre-built schema input this is the\n * exact schema the caller passed, refinements / checks preserved. See #56.\n */\n readonly validator: InsertSchema\n\n index<\n IndexName extends string,\n First extends ModelFieldPaths<InsertSchema>,\n Rest extends ModelFieldPaths<InsertSchema>[]\n >(\n name: IndexName,\n fields: readonly [First, ...Rest]\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes & Record<IndexName, readonly [First, ...Rest, '_creationTime']>,\n SearchIndexes,\n VectorIndexes\n >\n\n searchIndex<IndexName extends string>(\n name: IndexName,\n config: SearchIndexConfig\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes,\n SearchIndexes & Record<IndexName, SearchIndexConfig>,\n VectorIndexes\n >\n\n vectorIndex<IndexName extends string>(\n name: IndexName,\n config: VectorIndexConfig\n ): ZodModel<\n Name,\n Fields,\n InsertSchema,\n Schemas,\n Indexes,\n SearchIndexes,\n VectorIndexes & Record<IndexName, VectorIndexConfig>\n >\n}\n\n// Overload: raw shape with schemaHelpers: false → SlimObjectModel\nexport function defineZodModel<Name extends string, Fields extends $ZodShape>(\n name: Name,\n fields: Fields,\n options: { schemaHelpers: false }\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional\n): SlimObjectModel<Name, Fields, z.ZodObject<Fields>, {}, {}, {}>\n\n// Overload: pre-built schema with schemaHelpers: false → SlimUnionModel\nexport function defineZodModel<Name extends string, Schema extends $ZodType>(\n name: Name,\n schema: Schema,\n options: { schemaHelpers: false }\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional\n): SlimUnionModel<Name, Schema, {}, {}, {}>\n\nexport function defineZodModel<Name extends string, Fields extends $ZodShape>(\n name: Name,\n fields: Fields\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional — represents zero indexes/searchIndexes/vectorIndexes\n): ZodModel<Name, Fields, z.ZodObject<Fields>, FullZodModelSchemas<Name, Fields>, {}, {}, {}>\n\nexport function defineZodModel<Name extends string, Schema extends $ZodType>(\n name: Name,\n schema: Schema\n // biome-ignore lint/complexity/noBannedTypes: {} is intentional — represents zero indexes/searchIndexes/vectorIndexes\n): ZodModel<Name, $ZodShape, Schema, UnionModelSchemas<Name, Schema>, {}, {}, {}>\n\nexport function defineZodModel<Name extends string>(\n name: Name,\n fieldsOrSchema: $ZodShape | $ZodType,\n options?: DefineZodModelOptions\n): any {\n if (fieldsOrSchema instanceof $ZodType) {\n return (_defineZodModel as any)(name, fieldsOrSchema, options)\n }\n return (_defineZodModel as any)(name, fieldsOrSchema, options)\n}\n\nexport type {\n AnyZodModelBase,\n DefineZodModelOptions,\n SlimObjectModel,\n SlimUnionModel,\n ZodModelBase\n}\n","/**\n * zodvex - Client-safe full-Zod surface.\n *\n * This is the canonical entrypoint for standard full-Zod consumers.\n * Server-only APIs live under `zodvex/server`.\n *\n * @example\n * ```ts\n * import { zx, defineZodModel } from 'zodvex'\n * import { defineZodSchema, initZodvex } from 'zodvex/server'\n * ```\n */\n\nexport * from './public'\n\nconst legacyMigrationGuide = 'docs/migration/v0.6.md'\n\nfunction deprecatedRootExport(name: string): never {\n throw new Error(\n `[zodvex] \\`${name}\\` is deprecated and is no longer exported from \\`zodvex\\`.\\n` +\n `Import it from \\`zodvex/legacy\\` temporarily, or migrate away from the legacy API.\\n` +\n `Migration guide: ${legacyMigrationGuide}`\n )\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `defineZodModel` + `defineZodSchema`.\n */\nexport function zodTable(): never {\n return deprecatedRootExport('zodTable')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `defineZodModel`.\n */\nexport function zodDoc(): never {\n return deprecatedRootExport('zodDoc')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `defineZodModel`.\n */\nexport function zodDocOrNull(): never {\n return deprecatedRootExport('zodDocOrNull')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex()`.\n */\nexport function zQueryBuilder(): never {\n return deprecatedRootExport('zQueryBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex()`.\n */\nexport function zMutationBuilder(): never {\n return deprecatedRootExport('zMutationBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex()`.\n */\nexport function zActionBuilder(): never {\n return deprecatedRootExport('zActionBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex().zq.withContext()`.\n */\nexport function zCustomQueryBuilder(): never {\n return deprecatedRootExport('zCustomQueryBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex().zm.withContext()`.\n */\nexport function zCustomMutationBuilder(): never {\n return deprecatedRootExport('zCustomMutationBuilder')\n}\n\n/**\n * @deprecated Import from `zodvex/legacy` temporarily, or migrate to `initZodvex().za.withContext()`.\n */\nexport function zCustomActionBuilder(): never {\n return deprecatedRootExport('zCustomActionBuilder')\n}\n"]}