zodvex 0.7.1-beta.6 → 0.7.1-beta.7

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/normalizeCodecPaths.ts","../../src/utils.ts","../../src/boundaryHelpers.ts","../../src/ids.ts","../../src/mapping/handlers/enum.ts","../../src/mapping/handlers/nullable.ts","../../src/mapping/handlers/record.ts","../../src/mapping/handlers/union.ts","../../src/mapping/utils.ts","../../src/mapping/core.ts","../../src/codec.ts","../../src/meta.ts","../../src/codegen/extractCodec.ts","../../src/zx.ts","../../src/schemaHelpers.ts","../../src/model.ts","../../src/registry.ts","../../src/results.ts"],"names":["v","z","zodToConvexInternal","metadata","getObjectShape","codec","date"],"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,KAAA,MAAW,WAAW,IAAA,EAAM;AAC1B,IAAA,OAAA,GAAU,YAAY,OAAO,CAAA;AAG7B,IAAA,IAAI,mBAAmB,SAAA,EAAW;AAChC,MAAA;AAAA,IACF;AAGA,IAAA,IAAI,OAAA,YAAmB,UAAA,IAAc,OAAO,OAAA,KAAY,QAAA,EAAU;AAChE,MAAA,MA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AG;AAC3D,CAAC;AAOI,IAAM,mBAAA,GAAsBA,CAAAA,CAAE,kBAAA,CAAmB,SAAA,EAAW;AAAA,EACjEA,CAAAA,CAAE,OAAO,EAAE,OAAA,EAASA,EAAE,OAAA,CAAQ,IAAI,GAAG,CAAA;AAAA,EACrCA,CAAAA,CAAE,MAAA,CAAO,EAAE,OAAA,EAASA,CAAAA,CAAE,OAAA,CAAQ,KAAK,CAAA,EAAG,KAAA,EAAOA,CAAAA,CAAE,MAAA,EAAO,EAAG;AAC3D,CAAC;AAKM,IAAM,UAAA,GAAaA,EAAE,MAAA,CAAO;AAAA,EACjC,UAAA,EAAYA,CAAAA,CAAE,KAAA,CAAMA,CAAAA,CAAE,QAAQ,CAAA;AAAA,EAC9B,WAAA,EAAaA,CAAAA,CAAE,MAAA,CAAOA,CAAAA,CAAE,MAAA,EAAO,EAAGA,CAAAA,CAAE,KAAA,CAAMA,CAAAA,CAAE,MAAA,EAAQ,CAAC;AACvD,CAAC;AAOM,IAAM,WAAA,GAAc,CAAqB,UAAA,KAC9CA,CAAAA,CAAE,mBAAmB,SAAA,EAAW;AAAA,EAC9BA,CAAAA,CAAE,MAAA,CAAO,EAAE,OAAA,EAASA,CAAAA,CAAE,QAAQ,IAAI,CAAA,EAAG,IAAA,EAAM,UAAA,EAAY,CAAA;AAAA,EACvDA,CAAAA,CAAE,MAAA,CAAO,EAAE,OAAA,EAASA,CAAAA,CAAE,OAAA,CAAQ,KAAK,CAAA,EAAG,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,UAAA,EAAY;AAC7E,CAAC","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","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 type input as zinput\n} from './zod-core'\n\n// Private copy — importing from ./mapping pulls convex/values into client bundles\n// (mapping/utils.ts imports `v` from convex/values which is server-only).\nfunction getObjectShape(obj: any): Record<string, any> {\n if (obj instanceof $ZodObject) return obj._zod.def.shape as Record<string, any>\n if (obj && typeof obj === 'object' && typeof obj.shape === 'object')\n return obj.shape as Record<string, any>\n return {}\n}\n\nexport function pick<T extends Record<string, any>, K extends keyof T>(\n obj: T,\n keys: K[]\n): Pick<T, K> {\n const result = {} as Pick<T, K>\n for (const key of keys) {\n if (key in obj) result[key] = obj[key]\n }\n return result\n}\n\n// Typed identity helper for returns schemas\nexport function returnsAs<R extends $ZodType>() {\n return <T extends zinput<R>>(v: T) => v\n}\n\n/**\n * Recursively strips undefined values from objects for Convex serialization.\n * Convex rejects objects with explicit undefined properties, so we need to\n * remove them before returning from handlers.\n *\n * Only processes plain objects (Object.prototype). Class instances, Dates,\n * and other non-plain objects are passed through unchanged.\n *\n * @param value - The value to strip undefined from\n * @returns The value with undefined properties removed from plain objects\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\n// Helper: standard Convex paginate() result schema\nexport function zPaginated<T extends $ZodType>(item: T) {\n return z.object({\n page: z.array(item),\n isDone: z.boolean(),\n continueCursor: z.optional(z.nullable(z.string()))\n })\n}\n\n/**\n * Maps Date fields to number fields for docSchema generation.\n * Handles Date, Date.optional(), Date.nullable(), and Date.default() cases.\n * Returns the original field for non-Date types.\n *\n * @deprecated Use `zx.date()` instead for automatic Date ↔ timestamp conversion.\n */\nexport function mapDateFieldToNumber(field: $ZodType): $ZodType {\n // Direct Date field\n if (field instanceof $ZodDate) {\n return z.number()\n }\n\n // Optional Date field\n if (field instanceof $ZodOptional && field._zod.def.innerType instanceof $ZodDate) {\n return z.optional(z.number())\n }\n\n // Nullable Date field\n if (field instanceof $ZodNullable && field._zod.def.innerType instanceof $ZodDate) {\n return z.nullable(z.number())\n }\n\n // Date with default value\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\n // Non-Date field - return as-is\n return field\n}\n\n// Schema picking utilities (moved from pick.ts for consolidation)\ntype Mask = readonly string[] | Record<string, boolean | 1 | true>\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\n/**\n * Returns a plain shape object containing only the selected fields.\n * Accepts either a ZodObject or a raw shape object.\n */\nexport function pickShape(\n schemaOrShape: z.ZodObject<any> | Record<string, any>,\n mask: Mask\n): Record<string, any> {\n const keys = toKeys(mask)\n const shape =\n schemaOrShape instanceof $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\n// Builds a fresh Zod object from the selected fields (avoids Zod's .pick())\nexport function safePick(schema: z.ZodObject<any>, mask: Mask): z.ZodObject<any> {\n return z.object(pickShape(schema, mask))\n}\n\n/**\n * Convenience: omit a set of keys by building the complement.\n * Avoids using Zod's .omit() which can cause type depth issues.\n */\nexport function safeOmit(schema: z.ZodObject<any>, mask: Mask): z.ZodObject<any> {\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\n/**\n * Recursively checks if a schema contains native z.date().\n * Stops recursion at ZodCodec boundaries since codecs handle their own transforms.\n */\nfunction containsNativeZodDate(schema: $ZodType): boolean {\n // Check if this is a native ZodDate (not our codec)\n if (schema instanceof $ZodDate) {\n return true\n }\n\n // Codecs handle their own transforms - don't recurse into them\n if (schema instanceof $ZodCodec) {\n return false\n }\n\n // Recurse into wrappers - cast unwrap result to ZodTypeAny for Zod v4 compatibility\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 // Recurse into objects\n if (schema instanceof $ZodObject) {\n return Object.values(schema._zod.def.shape).some(field => containsNativeZodDate(field))\n }\n\n // Recurse into arrays\n if (schema instanceof $ZodArray) {\n return containsNativeZodDate(schema._zod.def.element)\n }\n\n // Recurse into unions\n if (schema instanceof $ZodUnion) {\n return schema._zod.def.options.some(opt => containsNativeZodDate(opt))\n }\n\n // Recurse into records\n if (schema instanceof $ZodRecord) {\n return containsNativeZodDate(schema._zod.def.valueType)\n }\n\n // Recurse into tuples\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\n/**\n * Throws if schema contains native z.date() which isn't compatible with Convex.\n * Guides users to use zx.date() instead.\n *\n * @param schema - The Zod schema to check\n * @param context - Context for the error message (args, returns, schema)\n * @throws Error with migration guidance if z.date() is found\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 type { FunctionReference } from 'convex/server'\nimport type { z } from 'zod'\nimport type { $ZodIssue } from 'zod/v4/core'\nimport { safeEncode } from './normalizeCodecPaths'\nimport type { AnyRegistry } from './types'\nimport { stripUndefined } from './utils'\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).\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)\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 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 { $ZodObject, $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 function getObjectShape(obj: any): Record<string, any> {\n if (obj instanceof $ZodObject) {\n return obj._zod.def.shape as Record<string, any>\n }\n // Fallback for plain shape objects\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, 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 { getObjectShape, isZid } from './utils'\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 // 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 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 { zodToConvex } from './mapping'\nimport { type ZodvexCodec } from './types'\nimport { assertNoNativeZodDate, stripUndefined } from './utils'\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>>\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 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 ZodvexModelMeta = {\n type: 'model'\n tableName: string\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 '../meta'\nimport {\n $ZodCodec,\n $ZodCustom,\n $ZodNullable,\n $ZodNumber,\n $ZodOptional,\n $ZodType\n} from '../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 type { ZodvexCodec } from './types'\nimport { type $ZodType, type output as zoutput } from './zod-core'\n\n/**\n * Date codec type for explicit type annotations\n */\nexport type ZxDate = ZodvexCodec<z.ZodNumber, z.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 )\n}\n\n/**\n * ID type for explicit type annotations\n */\nexport type ZxId<TableName extends string> = 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): ZodvexCodec<W, R> {\n return zodvexCodec(wire, runtime, transforms)\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} 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/core (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 $ZodDiscriminatedUnion,\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: z.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>\n ? z.ZodObject<Shape & SystemFields<TableName>>\n : Options[K]\n}\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/**\n * Type guard to check if a schema is a union type (ZodUnion or ZodDiscriminatedUnion).\n */\nexport function isZodUnion(\n schema: $ZodType\n): schema is\n | z.ZodUnion<readonly $ZodType[]>\n | z.ZodDiscriminatedUnion<readonly z.ZodObject<$ZodShape>[], string> {\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(\n schema:\n | z.ZodUnion<readonly $ZodType[]>\n | z.ZodDiscriminatedUnion<readonly z.ZodObject<$ZodShape>[], string>\n): 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 */\nexport function createUnionFromOptions<T extends $ZodType>(\n options: readonly T[]\n): z.ZodUnion<UnionTuple<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>\n): z.ZodObject<Shape & SystemFields<TableName>>\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>\n): z.ZodUnion<MapSystemFields<TableName, Options>>\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>[],\n Discriminator extends string\n>(\n tableName: TableName,\n schema: z.ZodDiscriminatedUnion<Options, Discriminator>\n): z.ZodDiscriminatedUnion<MapSystemFields<TableName, Options>, Discriminator>\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","/**\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/core (no server imports).\n */\n\nimport type { GenericId } from 'convex/values'\nimport { z } from 'zod'\nimport { attachMeta } from './meta'\nimport {\n addSystemFields,\n createUnionFromOptions,\n getUnionOptions,\n isZodUnion\n} from './schemaHelpers'\nimport {\n $ZodArray,\n $ZodBoolean,\n $ZodNullable,\n $ZodNumber,\n $ZodObject,\n $ZodOptional,\n type $ZodShape,\n $ZodString,\n $ZodType,\n type input as zinput\n} from './zod-core'\nimport { zx } from './zx'\n\n/** Core-typed Convex ID — uses $ZodType for zod/mini compatibility */\ntype $ZxId<TableName extends string> = $ZodType<GenericId<TableName>> & {\n _tableName: TableName\n}\n\n/** Wrap in .optional() only if not already optional. Uses core constructor for zod-mini compat. */\nfunction ensureOptional(schema: $ZodType): z.ZodOptional<any> {\n if (schema instanceof $ZodOptional) return schema as z.ZodOptional<any>\n return new $ZodOptional({ type: 'optional', innerType: schema }) as z.ZodOptional<any>\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 * 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 * 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 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: {\n readonly doc: $ZodObject<Fields & { _id: $ZxId<Name>; _creationTime: $ZodNumber }>\n /** User fields only — alias for insert */\n readonly base: $ZodObject<Fields>\n readonly insert: $ZodObject<Fields>\n readonly update: $ZodObject<\n { _id: $ZxId<Name>; _creationTime: $ZodOptional<$ZodNumber> } & {\n [K in keyof Fields]: $ZodOptional<Fields[K]>\n }\n >\n readonly docArray: $ZodArray<\n $ZodObject<Fields & { _id: $ZxId<Name>; _creationTime: $ZodNumber }>\n >\n readonly paginatedDoc: $ZodObject<{\n page: $ZodArray<$ZodObject<Fields & { _id: $ZxId<Name>; _creationTime: $ZodNumber }>>\n isDone: $ZodBoolean\n continueCursor: $ZodOptional<$ZodNullable<$ZodString>>\n }>\n }\n readonly indexes: Indexes\n readonly searchIndexes: SearchIndexes\n readonly vectorIndexes: VectorIndexes\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 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 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 Indexes,\n SearchIndexes,\n VectorIndexes & Record<IndexName, VectorIndexConfig>\n >\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 1: 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, $ZodObject<Fields>, {}, {}, {}>\n\n// Overload 2: 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, {}, {}, {}>\n\n// Implementation\nexport function defineZodModel<Name extends string>(\n name: Name,\n fieldsOrSchema: $ZodShape | $ZodType\n): any {\n // Detect if input is a pre-built Zod schema (union, object, etc.) vs raw shape\n if (fieldsOrSchema instanceof $ZodType) {\n return createUnionModel(name, fieldsOrSchema as $ZodType)\n }\n\n // Existing raw-shape path\n const fields = fieldsOrSchema as $ZodShape\n\n const insertSchema = z.object(fields)\n const docSchema = z.object({ ...fields, _id: zx.id(name), _creationTime: z.number() })\n\n // Create partial shape for update: _id required, _creationTime optional, user fields partial\n const partialShape: Record<string, $ZodType> = {}\n for (const [key, value] of Object.entries(fields)) {\n partialShape[key] = ensureOptional(value as $ZodType)\n }\n const updateSchema = z.object({\n _id: zx.id(name),\n _creationTime: z.optional(z.number()),\n ...partialShape\n })\n\n const docArraySchema = z.array(docSchema)\n\n const paginatedDocSchema = z.object({\n page: z.array(docSchema),\n isDone: z.boolean(),\n continueCursor: z.optional(z.nullable(z.string()))\n })\n\n const schema = {\n doc: docSchema,\n base: insertSchema,\n insert: insertSchema,\n update: updateSchema,\n docArray: docArraySchema,\n paginatedDoc: paginatedDocSchema\n }\n\n function createModel(\n indexes: Record<string, readonly string[]>,\n searchIndexes: Record<string, SearchIndexConfig>,\n vectorIndexes: Record<string, VectorIndexConfig>\n ): any {\n const model = {\n name,\n fields,\n schema,\n indexes,\n searchIndexes,\n vectorIndexes,\n index(indexName: string, indexFields: readonly string[]) {\n return createModel(\n { ...indexes, [indexName]: [...indexFields, '_creationTime'] },\n searchIndexes,\n vectorIndexes\n )\n },\n searchIndex(indexName: string, config: SearchIndexConfig) {\n return createModel(indexes, { ...searchIndexes, [indexName]: config }, vectorIndexes)\n },\n vectorIndex(indexName: string, config: VectorIndexConfig) {\n return createModel(indexes, searchIndexes, { ...vectorIndexes, [indexName]: config })\n }\n }\n attachMeta(model, { type: 'model', tableName: name, schemas: schema })\n return model\n }\n\n return createModel({}, {}, {})\n}\n\n// ============================================================================\n// createUnionModel — Internal helper for union/schema path\n// ============================================================================\n\n/**\n * Creates a ZodModel from a pre-built Zod schema (union, discriminated union, or object).\n * Mirrors the union path logic from zodTable() in tables.ts.\n *\n * @internal\n */\nfunction createUnionModel<Name extends string>(name: Name, inputSchema: $ZodType): any {\n const insertSchema = inputSchema\n const docSchema = addSystemFields(name, inputSchema)\n const docArraySchema = z.array(docSchema)\n const paginatedDocSchema = z.object({\n page: z.array(docSchema),\n isDone: z.boolean(),\n continueCursor: z.optional(z.nullable(z.string()))\n })\n\n // Build update schema: _id required, _creationTime optional, user fields partial\n let updateSchema: $ZodType\n if (isZodUnion(inputSchema)) {\n const originalOptions = getUnionOptions(inputSchema)\n const updateOptions = originalOptions.map((variant: $ZodType) => {\n if (variant instanceof $ZodObject) {\n const partialShape: Record<string, $ZodType> = {}\n for (const [key, value] of Object.entries(variant._zod.def.shape)) {\n partialShape[key] = ensureOptional(value as $ZodType)\n }\n return z.object({\n _id: zx.id(name),\n _creationTime: z.optional(z.number()),\n ...partialShape\n })\n }\n return variant\n })\n updateSchema = createUnionFromOptions(updateOptions)\n } else if (inputSchema instanceof $ZodObject) {\n const partialShape: Record<string, $ZodType> = {}\n for (const [key, value] of Object.entries(inputSchema._zod.def.shape)) {\n partialShape[key] = ensureOptional(value as $ZodType)\n }\n updateSchema = z.object({\n _id: zx.id(name),\n _creationTime: z.optional(z.number()),\n ...partialShape\n })\n } else {\n updateSchema = inputSchema\n }\n\n const schema = {\n doc: docSchema,\n base: insertSchema,\n insert: insertSchema,\n update: updateSchema,\n docArray: docArraySchema,\n paginatedDoc: paginatedDocSchema\n }\n\n // For union models, fields is an empty shape (field paths come from InsertSchema generic)\n const fields: $ZodShape = {}\n\n function createModel(\n indexes: Record<string, readonly string[]>,\n searchIndexes: Record<string, SearchIndexConfig>,\n vectorIndexes: Record<string, VectorIndexConfig>\n ): any {\n const model = {\n name,\n fields,\n schema,\n indexes,\n searchIndexes,\n vectorIndexes,\n index(indexName: string, indexFields: readonly string[]) {\n return createModel(\n { ...indexes, [indexName]: [...indexFields, '_creationTime'] },\n searchIndexes,\n vectorIndexes\n )\n },\n searchIndex(indexName: string, config: SearchIndexConfig) {\n return createModel(indexes, { ...searchIndexes, [indexName]: config }, vectorIndexes)\n },\n vectorIndex(indexName: string, config: VectorIndexConfig) {\n return createModel(indexes, searchIndexes, { ...vectorIndexes, [indexName]: config })\n }\n }\n attachMeta(model, { type: 'model', tableName: name, schemas: schema })\n return model\n }\n\n return createModel({}, {}, {})\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"]}
1
+ {"version":3,"sources":["../../src/normalizeCodecPaths.ts","../../src/utils.ts","../../src/boundaryHelpers.ts","../../src/ids.ts","../../src/mapping/handlers/enum.ts","../../src/mapping/handlers/nullable.ts","../../src/mapping/handlers/record.ts","../../src/mapping/handlers/union.ts","../../src/mapping/utils.ts","../../src/mapping/core.ts","../../src/codec.ts","../../src/meta.ts","../../src/codegen/extractCodec.ts","../../src/zx.ts","../../src/schemaHelpers.ts","../../src/model.ts","../../src/registry.ts","../../src/results.ts"],"names":["v","z","zodToConvexInternal","metadata","getObjectShape","codec","date"],"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,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EAASA,CAAAA,CAAE,OAAA,CAAQ,KAAK,CAAA,EAAG,IAAA,EAAM,UAAA,EAAY,KAAA,EAAO,UAAA,EAAY;AAC7E,CAAC","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","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 type input as zinput\n} from './zod-core'\n\n// Private copy — importing from ./mapping pulls convex/values into client bundles\n// (mapping/utils.ts imports `v` from convex/values which is server-only).\nfunction getObjectShape(obj: any): Record<string, any> {\n if (obj instanceof $ZodObject) return obj._zod.def.shape as Record<string, any>\n if (obj && typeof obj === 'object' && typeof obj.shape === 'object')\n return obj.shape as Record<string, any>\n return {}\n}\n\nexport function pick<T extends Record<string, any>, K extends keyof T>(\n obj: T,\n keys: K[]\n): Pick<T, K> {\n const result = {} as Pick<T, K>\n for (const key of keys) {\n if (key in obj) result[key] = obj[key]\n }\n return result\n}\n\n// Typed identity helper for returns schemas\nexport function returnsAs<R extends $ZodType>() {\n return <T extends zinput<R>>(v: T) => v\n}\n\n/**\n * Recursively strips undefined values from objects for Convex serialization.\n * Convex rejects objects with explicit undefined properties, so we need to\n * remove them before returning from handlers.\n *\n * Only processes plain objects (Object.prototype). Class instances, Dates,\n * and other non-plain objects are passed through unchanged.\n *\n * @param value - The value to strip undefined from\n * @returns The value with undefined properties removed from plain objects\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\n// Helper: standard Convex paginate() result schema\nexport function zPaginated<T extends $ZodType>(item: T) {\n return z.object({\n page: z.array(item),\n isDone: z.boolean(),\n continueCursor: z.optional(z.nullable(z.string()))\n })\n}\n\n/**\n * Maps Date fields to number fields for docSchema generation.\n * Handles Date, Date.optional(), Date.nullable(), and Date.default() cases.\n * Returns the original field for non-Date types.\n *\n * @deprecated Use `zx.date()` instead for automatic Date ↔ timestamp conversion.\n */\nexport function mapDateFieldToNumber(field: $ZodType): $ZodType {\n // Direct Date field\n if (field instanceof $ZodDate) {\n return z.number()\n }\n\n // Optional Date field\n if (field instanceof $ZodOptional && field._zod.def.innerType instanceof $ZodDate) {\n return z.optional(z.number())\n }\n\n // Nullable Date field\n if (field instanceof $ZodNullable && field._zod.def.innerType instanceof $ZodDate) {\n return z.nullable(z.number())\n }\n\n // Date with default value\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\n // Non-Date field - return as-is\n return field\n}\n\n// Schema picking utilities (moved from pick.ts for consolidation)\ntype Mask = readonly string[] | Record<string, boolean | 1 | true>\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\n/**\n * Returns a plain shape object containing only the selected fields.\n * Accepts either a ZodObject or a raw shape object.\n */\nexport function pickShape(\n schemaOrShape: z.ZodObject<any> | Record<string, any>,\n mask: Mask\n): Record<string, any> {\n const keys = toKeys(mask)\n const shape =\n schemaOrShape instanceof $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\n// Builds a fresh Zod object from the selected fields (avoids Zod's .pick())\nexport function safePick(schema: z.ZodObject<any>, mask: Mask): z.ZodObject<any> {\n return z.object(pickShape(schema, mask))\n}\n\n/**\n * Convenience: omit a set of keys by building the complement.\n * Avoids using Zod's .omit() which can cause type depth issues.\n */\nexport function safeOmit(schema: z.ZodObject<any>, mask: Mask): z.ZodObject<any> {\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\n/**\n * Recursively checks if a schema contains native z.date().\n * Stops recursion at ZodCodec boundaries since codecs handle their own transforms.\n */\nfunction containsNativeZodDate(schema: $ZodType): boolean {\n // Check if this is a native ZodDate (not our codec)\n if (schema instanceof $ZodDate) {\n return true\n }\n\n // Codecs handle their own transforms - don't recurse into them\n if (schema instanceof $ZodCodec) {\n return false\n }\n\n // Recurse into wrappers - cast unwrap result to ZodTypeAny for Zod v4 compatibility\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 // Recurse into objects\n if (schema instanceof $ZodObject) {\n return Object.values(schema._zod.def.shape).some(field => containsNativeZodDate(field))\n }\n\n // Recurse into arrays\n if (schema instanceof $ZodArray) {\n return containsNativeZodDate(schema._zod.def.element)\n }\n\n // Recurse into unions\n if (schema instanceof $ZodUnion) {\n return schema._zod.def.options.some(opt => containsNativeZodDate(opt))\n }\n\n // Recurse into records\n if (schema instanceof $ZodRecord) {\n return containsNativeZodDate(schema._zod.def.valueType)\n }\n\n // Recurse into tuples\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\n/**\n * Throws if schema contains native z.date() which isn't compatible with Convex.\n * Guides users to use zx.date() instead.\n *\n * @param schema - The Zod schema to check\n * @param context - Context for the error message (args, returns, schema)\n * @throws Error with migration guidance if z.date() is found\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 type { FunctionReference } from 'convex/server'\nimport type { z } from 'zod'\nimport type { $ZodIssue } from 'zod/v4/core'\nimport { safeEncode } from './normalizeCodecPaths'\nimport type { AnyRegistry } from './types'\nimport { stripUndefined } from './utils'\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).\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)\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 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 { $ZodObject, $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 function getObjectShape(obj: any): Record<string, any> {\n if (obj instanceof $ZodObject) {\n return obj._zod.def.shape as Record<string, any>\n }\n // Fallback for plain shape objects\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, 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 { getObjectShape, isZid } from './utils'\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 // 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 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 { zodToConvex } from './mapping'\nimport { type ZodvexCodec } from './types'\nimport { assertNoNativeZodDate, stripUndefined } from './utils'\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>>\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 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 ZodvexModelMeta = {\n type: 'model'\n tableName: string\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 '../meta'\nimport {\n $ZodCodec,\n $ZodCustom,\n $ZodNullable,\n $ZodNumber,\n $ZodOptional,\n $ZodType\n} from '../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 type { ZodvexCodec } from './types'\nimport { type $ZodType, type output as zoutput } from './zod-core'\n\n/**\n * Date codec type for explicit type annotations\n */\nexport type ZxDate = ZodvexCodec<z.ZodNumber, z.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 )\n}\n\n/**\n * ID type for explicit type annotations\n */\nexport type ZxId<TableName extends string> = 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): ZodvexCodec<W, R> {\n return zodvexCodec(wire, runtime, transforms)\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} 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/core (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 $ZodDiscriminatedUnion,\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: z.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>\n ? z.ZodObject<Shape & SystemFields<TableName>>\n : Options[K]\n}\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/**\n * Type guard to check if a schema is a union type (ZodUnion or ZodDiscriminatedUnion).\n */\nexport function isZodUnion(\n schema: $ZodType\n): schema is\n | z.ZodUnion<readonly $ZodType[]>\n | z.ZodDiscriminatedUnion<readonly z.ZodObject<$ZodShape>[], string> {\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(\n schema:\n | z.ZodUnion<readonly $ZodType[]>\n | z.ZodDiscriminatedUnion<readonly z.ZodObject<$ZodShape>[], string>\n): 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 */\nexport function createUnionFromOptions<T extends $ZodType>(\n options: readonly T[]\n): z.ZodUnion<UnionTuple<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>\n): z.ZodObject<Shape & SystemFields<TableName>>\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>\n): z.ZodUnion<MapSystemFields<TableName, Options>>\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>[],\n Discriminator extends string\n>(\n tableName: TableName,\n schema: z.ZodDiscriminatedUnion<Options, Discriminator>\n): z.ZodDiscriminatedUnion<MapSystemFields<TableName, Options>, Discriminator>\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","/**\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/core (no server imports).\n */\n\nimport { z } from 'zod'\nimport { attachMeta } from './meta'\nimport {\n addSystemFields,\n createUnionFromOptions,\n getUnionOptions,\n isZodUnion\n} from './schemaHelpers'\nimport {\n $ZodObject,\n $ZodOptional,\n type $ZodShape,\n $ZodType,\n type input as zinput\n} from './zod-core'\nimport { type ZxId, zx } from './zx'\n\n/** Wrap in .optional() only if not already optional. Uses core constructor for zod-mini compat. */\nfunction ensureOptional(schema: $ZodType): z.ZodOptional<any> {\n if (schema instanceof $ZodOptional) return schema as z.ZodOptional<any>\n return new $ZodOptional({ type: 'optional', innerType: schema }) as z.ZodOptional<any>\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 * Full-zod schema types — the default for zodvex/core consumers.\n * Each property uses z.ZodObject / z.ZodArray etc. from full zod,\n * providing method chaining (.parse(), .shape, .nullable(), etc.).\n */\nexport type FullZodModelSchemas<Name extends string, Fields extends $ZodShape> = {\n readonly doc: z.ZodObject<Fields & { _id: ZxId<Name>; _creationTime: z.ZodNumber }>\n readonly base: z.ZodObject<Fields>\n readonly insert: z.ZodObject<Fields>\n readonly update: z.ZodObject<\n { _id: ZxId<Name>; _creationTime: z.ZodOptional<z.ZodNumber> } & {\n [K in keyof Fields]: z.ZodOptional<Fields[K]>\n }\n >\n readonly docArray: z.ZodArray<\n z.ZodObject<Fields & { _id: ZxId<Name>; _creationTime: z.ZodNumber }>\n >\n readonly paginatedDoc: z.ZodObject<{\n page: z.ZodArray<z.ZodObject<Fields & { _id: ZxId<Name>; _creationTime: z.ZodNumber }>>\n isDone: z.ZodBoolean\n continueCursor: z.ZodOptional<z.ZodNullable<z.ZodString>>\n }>\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/core, 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 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// ============================================================================\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 1: 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>, {}, {}, {}>\n\n// Overload 2: 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, ModelSchemas, {}, {}, {}>\n\n// Implementation\nexport function defineZodModel<Name extends string>(\n name: Name,\n fieldsOrSchema: $ZodShape | $ZodType\n): any {\n // Detect if input is a pre-built Zod schema (union, object, etc.) vs raw shape\n if (fieldsOrSchema instanceof $ZodType) {\n return createUnionModel(name, fieldsOrSchema as $ZodType)\n }\n\n // Existing raw-shape path\n const fields = fieldsOrSchema as $ZodShape\n\n const insertSchema = z.object(fields)\n const docSchema = z.object({ ...fields, _id: zx.id(name), _creationTime: z.number() })\n\n // Create partial shape for update: _id required, _creationTime optional, user fields partial\n const partialShape: Record<string, $ZodType> = {}\n for (const [key, value] of Object.entries(fields)) {\n partialShape[key] = ensureOptional(value as $ZodType)\n }\n const updateSchema = z.object({\n _id: zx.id(name),\n _creationTime: z.optional(z.number()),\n ...partialShape\n })\n\n const docArraySchema = z.array(docSchema)\n\n const paginatedDocSchema = z.object({\n page: z.array(docSchema),\n isDone: z.boolean(),\n continueCursor: z.optional(z.nullable(z.string()))\n })\n\n const schema = {\n doc: docSchema,\n base: insertSchema,\n insert: insertSchema,\n update: updateSchema,\n docArray: docArraySchema,\n paginatedDoc: paginatedDocSchema\n }\n\n function createModel(\n indexes: Record<string, readonly string[]>,\n searchIndexes: Record<string, SearchIndexConfig>,\n vectorIndexes: Record<string, VectorIndexConfig>\n ): any {\n const model = {\n name,\n fields,\n schema,\n indexes,\n searchIndexes,\n vectorIndexes,\n index(indexName: string, indexFields: readonly string[]) {\n return createModel(\n { ...indexes, [indexName]: [...indexFields, '_creationTime'] },\n searchIndexes,\n vectorIndexes\n )\n },\n searchIndex(indexName: string, config: SearchIndexConfig) {\n return createModel(indexes, { ...searchIndexes, [indexName]: config }, vectorIndexes)\n },\n vectorIndex(indexName: string, config: VectorIndexConfig) {\n return createModel(indexes, searchIndexes, { ...vectorIndexes, [indexName]: config })\n }\n }\n attachMeta(model, { type: 'model', tableName: name, schemas: schema })\n return model\n }\n\n return createModel({}, {}, {})\n}\n\n// ============================================================================\n// createUnionModel — Internal helper for union/schema path\n// ============================================================================\n\n/**\n * Creates a ZodModel from a pre-built Zod schema (union, discriminated union, or object).\n * Mirrors the union path logic from zodTable() in tables.ts.\n *\n * @internal\n */\nfunction createUnionModel<Name extends string>(name: Name, inputSchema: $ZodType): any {\n const insertSchema = inputSchema\n const docSchema = addSystemFields(name, inputSchema)\n const docArraySchema = z.array(docSchema)\n const paginatedDocSchema = z.object({\n page: z.array(docSchema),\n isDone: z.boolean(),\n continueCursor: z.optional(z.nullable(z.string()))\n })\n\n // Build update schema: _id required, _creationTime optional, user fields partial\n let updateSchema: $ZodType\n if (isZodUnion(inputSchema)) {\n const originalOptions = getUnionOptions(inputSchema)\n const updateOptions = originalOptions.map((variant: $ZodType) => {\n if (variant instanceof $ZodObject) {\n const partialShape: Record<string, $ZodType> = {}\n for (const [key, value] of Object.entries(variant._zod.def.shape)) {\n partialShape[key] = ensureOptional(value as $ZodType)\n }\n return z.object({\n _id: zx.id(name),\n _creationTime: z.optional(z.number()),\n ...partialShape\n })\n }\n return variant\n })\n updateSchema = createUnionFromOptions(updateOptions)\n } else if (inputSchema instanceof $ZodObject) {\n const partialShape: Record<string, $ZodType> = {}\n for (const [key, value] of Object.entries(inputSchema._zod.def.shape)) {\n partialShape[key] = ensureOptional(value as $ZodType)\n }\n updateSchema = z.object({\n _id: zx.id(name),\n _creationTime: z.optional(z.number()),\n ...partialShape\n })\n } else {\n updateSchema = inputSchema\n }\n\n const schema = {\n doc: docSchema,\n base: insertSchema,\n insert: insertSchema,\n update: updateSchema,\n docArray: docArraySchema,\n paginatedDoc: paginatedDocSchema\n }\n\n // For union models, fields is an empty shape (field paths come from InsertSchema generic)\n const fields: $ZodShape = {}\n\n function createModel(\n indexes: Record<string, readonly string[]>,\n searchIndexes: Record<string, SearchIndexConfig>,\n vectorIndexes: Record<string, VectorIndexConfig>\n ): any {\n const model = {\n name,\n fields,\n schema,\n indexes,\n searchIndexes,\n vectorIndexes,\n index(indexName: string, indexFields: readonly string[]) {\n return createModel(\n { ...indexes, [indexName]: [...indexFields, '_creationTime'] },\n searchIndexes,\n vectorIndexes\n )\n },\n searchIndex(indexName: string, config: SearchIndexConfig) {\n return createModel(indexes, { ...searchIndexes, [indexName]: config }, vectorIndexes)\n },\n vectorIndex(indexName: string, config: VectorIndexConfig) {\n return createModel(indexes, searchIndexes, { ...vectorIndexes, [indexName]: config })\n }\n }\n attachMeta(model, { type: 'model', tableName: name, schemas: schema })\n return model\n }\n\n return createModel({}, {}, {})\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"]}