zodvex 0.7.9 → 0.7.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +3 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/client/index.js +84 -11
- package/dist/client/index.js.map +1 -1
- package/dist/codegen/index.js +2 -1
- package/dist/codegen/index.js.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internal/boundaryHelpers.d.ts +1 -0
- package/dist/internal/boundaryHelpers.d.ts.map +1 -1
- package/dist/internal/paginationCodec.d.ts +8 -0
- package/dist/internal/paginationCodec.d.ts.map +1 -0
- package/dist/mini/client/index.js +84 -11
- package/dist/mini/client/index.js.map +1 -1
- package/dist/mini/index.js.map +1 -1
- package/dist/mini/react/index.js +74 -3
- package/dist/mini/react/index.js.map +1 -1
- package/dist/mini/server/index.js.map +1 -1
- package/dist/public/cli/init.d.ts.map +1 -1
- package/dist/public/client/index.d.ts +1 -1
- package/dist/public/client/index.d.ts.map +1 -1
- package/dist/public/client/zodvexClient.d.ts +23 -9
- package/dist/public/client/zodvexClient.d.ts.map +1 -1
- package/dist/public/codegen/generate.d.ts.map +1 -1
- package/dist/public/react/hooks.d.ts +11 -2
- package/dist/public/react/hooks.d.ts.map +1 -1
- package/dist/react/index.js +74 -3
- package/dist/react/index.js.map +1 -1
- package/dist/server/index.js.map +1 -1
- package/package.json +7 -4
- package/src/internal/boundaryHelpers.ts +1 -1
- package/src/internal/paginationCodec.ts +60 -0
- package/src/public/cli/init.ts +1 -0
- package/src/public/client/index.ts +1 -1
- package/src/public/client/zodvexClient.ts +70 -21
- package/src/public/codegen/generate.ts +2 -1
- package/src/public/react/hooks.ts +55 -5
package/dist/mini/react/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as convexReact from 'convex/react';
|
|
2
|
-
import { ConvexReactClient, useQuery, useMutation } from 'convex/react';
|
|
3
|
-
import {
|
|
2
|
+
import { ConvexReactClient, usePaginatedQuery, useQuery, useMutation } from 'convex/react';
|
|
3
|
+
import { useMemo } from 'react';
|
|
4
|
+
import { safeParse, $ZodObject, $ZodArray, clone, $ZodError, encode, $ZodCodec, $ZodOptional, $ZodNullable, $ZodDefault } from 'zod/v4/core';
|
|
4
5
|
|
|
5
6
|
// src/public/react/hooks.ts
|
|
6
7
|
|
|
@@ -148,6 +149,55 @@ function createBoundaryHelpers(registry, options) {
|
|
|
148
149
|
return { encodeArgs, decodeResult };
|
|
149
150
|
}
|
|
150
151
|
|
|
152
|
+
// src/internal/paginationCodec.ts
|
|
153
|
+
function createPaginationCodec(registry) {
|
|
154
|
+
const argsRegistry = /* @__PURE__ */ Object.create(null);
|
|
155
|
+
const resultsRegistry = /* @__PURE__ */ Object.create(null);
|
|
156
|
+
const argsCodec = createBoundaryHelpers(argsRegistry, { onDecodeError: "throw" });
|
|
157
|
+
const resultsCodec = createBoundaryHelpers(resultsRegistry, { onDecodeError: "throw" });
|
|
158
|
+
function unsupported(path, boundary) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
`[zodvex] Unsupported pagination ${boundary} schema for "${path}". Use an unrefined argument object and an unrefined return object with an unrefined page array. Item schemas may contain codecs and refinements. For whole-page checks or transforms, use query or subscribe with explicit paginationOpts.`
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
function encodeArgs(ref, args) {
|
|
164
|
+
const path = resolveFunctionPath(ref);
|
|
165
|
+
if (path !== null && !Object.hasOwn(argsRegistry, path)) {
|
|
166
|
+
const schema = registry[path]?.args;
|
|
167
|
+
if (schema) {
|
|
168
|
+
if (!(schema instanceof $ZodObject) || schema._zod.def.checks?.length) {
|
|
169
|
+
unsupported(path, "argument");
|
|
170
|
+
}
|
|
171
|
+
const { paginationOpts: _paginationOpts, ...shape } = schema._zod.def.shape;
|
|
172
|
+
argsRegistry[path] = { args: clone(schema, { ...schema._zod.def, shape }) };
|
|
173
|
+
} else {
|
|
174
|
+
argsRegistry[path] = {};
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return argsCodec.encodeArgs(ref, args);
|
|
178
|
+
}
|
|
179
|
+
function decodeResults(ref, results) {
|
|
180
|
+
const path = resolveFunctionPath(ref);
|
|
181
|
+
if (path !== null && !Object.hasOwn(resultsRegistry, path)) {
|
|
182
|
+
const schema = registry[path]?.returns;
|
|
183
|
+
if (schema) {
|
|
184
|
+
if (!(schema instanceof $ZodObject) || schema._zod.def.checks?.length) {
|
|
185
|
+
unsupported(path, "return");
|
|
186
|
+
}
|
|
187
|
+
const page = schema._zod.def.shape.page;
|
|
188
|
+
if (!(page instanceof $ZodArray) || page._zod.def.checks?.length) {
|
|
189
|
+
unsupported(path, "page");
|
|
190
|
+
}
|
|
191
|
+
resultsRegistry[path] = { returns: page };
|
|
192
|
+
} else {
|
|
193
|
+
resultsRegistry[path] = {};
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return resultsCodec.decodeResult(ref, results);
|
|
197
|
+
}
|
|
198
|
+
return { encodeArgs, decodeResults };
|
|
199
|
+
}
|
|
200
|
+
|
|
151
201
|
// src/public/react/hooks.ts
|
|
152
202
|
function codecError(error, operation) {
|
|
153
203
|
return error instanceof Error ? error : new Error(`Failed to ${operation} query ${operation === "encode" ? "arguments" : "result"}`, {
|
|
@@ -156,10 +206,31 @@ function codecError(error, operation) {
|
|
|
156
206
|
}
|
|
157
207
|
function createZodvexHooks(registry, options) {
|
|
158
208
|
const codec = createBoundaryHelpers(registry, options);
|
|
209
|
+
const paginationCodec = createPaginationCodec(registry);
|
|
159
210
|
const experimentalCodec = createBoundaryHelpers(registry, {
|
|
160
211
|
...options,
|
|
161
212
|
onDecodeError: options?.onDecodeError ?? "throw"
|
|
162
213
|
});
|
|
214
|
+
function useZodPaginatedQuery(ref, args, paginationOptions) {
|
|
215
|
+
let wireArgs = "skip";
|
|
216
|
+
let encodeFailure;
|
|
217
|
+
if (args !== "skip") {
|
|
218
|
+
try {
|
|
219
|
+
wireArgs = paginationCodec.encodeArgs(ref, args);
|
|
220
|
+
} catch (error) {
|
|
221
|
+
encodeFailure = { error };
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const state = usePaginatedQuery(ref, wireArgs, paginationOptions);
|
|
225
|
+
const skipped = wireArgs === "skip";
|
|
226
|
+
const queryKey = resolveFunctionPath(ref) ?? ref;
|
|
227
|
+
const results = useMemo(
|
|
228
|
+
() => skipped ? state.results : paginationCodec.decodeResults(ref, state.results),
|
|
229
|
+
[queryKey, state.results, skipped]
|
|
230
|
+
);
|
|
231
|
+
if (encodeFailure) throw encodeFailure.error;
|
|
232
|
+
return { ...state, results };
|
|
233
|
+
}
|
|
163
234
|
function useQuery_experimental2(queryOptions) {
|
|
164
235
|
const nativeHook = convexReact.useQuery_experimental;
|
|
165
236
|
if (typeof nativeHook !== "function") {
|
|
@@ -218,7 +289,7 @@ function createZodvexHooks(registry, options) {
|
|
|
218
289
|
return codec.decodeResult(ref, wireResult);
|
|
219
290
|
};
|
|
220
291
|
}
|
|
221
|
-
return { useZodQuery, useZodMutation, useQuery_experimental: useQuery_experimental2 };
|
|
292
|
+
return { useZodQuery, useZodMutation, useZodPaginatedQuery, useQuery_experimental: useQuery_experimental2 };
|
|
222
293
|
}
|
|
223
294
|
var ZodvexReactClient = class {
|
|
224
295
|
codec;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/internal/normalizeCodecPaths.ts","../../../src/internal/stripUndefined.ts","../../../src/internal/boundaryHelpers.ts","../../../src/public/react/hooks.ts","../../../src/public/react/zodvexReactClient.ts"],"names":["useQuery_experimental"],"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,OAA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AA;AAChD","file":"index.js","sourcesContent":["import {\n $ZodArray,\n $ZodCodec,\n $ZodDefault,\n $ZodError,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodType,\n encode\n} from './zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable/ZodDefault wrappers to get the structural type.\n */\nfunction unwrapOuter(schema: $ZodType): $ZodType {\n let current: $ZodType = schema\n for (let i = 0; i < 10; i++) {\n if (\n current instanceof $ZodOptional ||\n current instanceof $ZodNullable ||\n current instanceof $ZodDefault\n ) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return current\n}\n\n/**\n * Walks a path through a schema tree, truncating at codec boundaries.\n * When a codec is encountered, the path is cut — any deeper segments\n * are wire-internal and should not be exposed to consumers.\n */\nfunction truncateAtCodecBoundary(path: (string | number)[], schema: $ZodType): (string | number)[] {\n const result: (string | number)[] = []\n let current: $ZodType = schema\n\n for (const segment of path) {\n current = unwrapOuter(current)\n\n // If we've landed on a codec, everything from here is wire-internal — stop\n if (current instanceof $ZodCodec) {\n break\n }\n\n // Descend into objects\n if (current instanceof $ZodObject && typeof segment === 'string') {\n const fieldSchema = current._zod.def.shape[segment] as $ZodType | undefined\n if (!fieldSchema) {\n // Unknown field — include segment and stop\n result.push(segment)\n break\n }\n\n result.push(segment)\n\n const unwrapped = unwrapOuter(fieldSchema)\n if (unwrapped instanceof $ZodCodec) {\n // Hit a codec boundary — truncate here\n break\n }\n\n current = fieldSchema\n continue\n }\n\n // Descend into arrays\n if (current instanceof $ZodArray && typeof segment === 'number') {\n result.push(segment)\n current = current._zod.def.element\n continue\n }\n\n // For anything else (unions, records, etc.), include segment and continue\n result.push(segment)\n }\n\n return result\n}\n\n/**\n * Normalizes ZodError paths by truncating at codec boundaries.\n *\n * When z.encode() throws a ZodError, the paths reflect the wire schema\n * structure (e.g., [\"email\", \"value\"] for a custom codec).\n * This function strips the wire-internal segments so consumers see\n * clean field-level paths (e.g., [\"email\"]).\n */\nexport function normalizeCodecPaths(error: $ZodError, schema: $ZodType): $ZodError {\n const normalized = error.issues.map(issue => ({\n ...issue,\n path: truncateAtCodecBoundary(issue.path as (string | number)[], schema)\n }))\n return new $ZodError(normalized)\n}\n\n/**\n * Encodes a value through a Zod schema, normalizing codec-internal\n * path segments in any ZodError before re-throwing.\n *\n * Drop-in replacement for `z.encode(schema, value)` at client boundaries.\n */\nexport function safeEncode(schema: $ZodType, value: unknown): unknown {\n try {\n return encode(schema, value)\n } catch (e) {\n if (e instanceof $ZodError) throw normalizeCodecPaths(e as $ZodError, schema)\n throw e\n }\n}\n","/**\n * Recursively strips `undefined` values from objects and arrays.\n * Used by codec encode/decode to clean wire data.\n *\n * Extracted to its own module so client-safe code (boundaryHelpers)\n * can import it without pulling in zod via utils.ts.\n */\nexport function stripUndefined<T>(value: T): T {\n if (value === null || value === undefined) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUndefined) as T\n }\n\n // Only process plain objects (not class instances, Dates, etc.)\n if (typeof value === 'object' && value.constructor === Object) {\n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n result[key] = stripUndefined(val)\n }\n }\n return result as T\n }\n\n return value\n}\n","import type { FunctionReference } from 'convex/server'\nimport type { $ZodIssue } from 'zod/v4/core'\nimport { safeEncode } from './normalizeCodecPaths'\nimport { stripUndefined } from './stripUndefined'\nimport type { AnyRegistry } from './types'\nimport { $ZodError, safeParse } from './zod-core'\n\n/**\n * Resolves a Convex FunctionReference to its string path.\n *\n * Mirrors `getFunctionName` from `convex/server` but without the server import.\n * Reads the well-known `Symbol.for('functionName')` that Convex attaches to all\n * function references — the same symbol used by Convex's own browser client.\n */\nconst functionNameSymbol = Symbol.for('functionName')\n\nfunction resolveFunctionPath(ref: FunctionReference<any, any, any, any>): string | null {\n if (typeof ref === 'string') return ref\n const name = (ref as any)[functionNameSymbol]\n if (!name) return null\n return name\n}\n\n/**\n * Options for codec helper behavior.\n */\nexport type BoundaryHelpersOptions = {\n /**\n * How to handle decode failures (schema validation errors on wire data).\n *\n * - `'warn'` (default): log a console.warn and return raw wire data untransformed.\n * - `'throw'`: throw a ZodvexDecodeError (extends z.ZodError). // zod-ok\n */\n onDecodeError?: 'warn' | 'throw'\n /**\n * Include a truncated preview of the raw wire data in the decode-failure\n * `warn` log (only relevant when `onDecodeError` is `'warn'`, the default).\n *\n * Off by default because wire values may be sensitive — the default warn\n * message only carries the function path and zod issue list. Enable only\n * when debugging a decode skew and you need to see the offending values.\n */\n warnWirePreview?: boolean\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 */\n/**\n * Module-scoped so the registry-miss note fires once per path per process.\n * A per-helpers set resets on every Convex invocation (ctx is wrapped per\n * call), which spammed hot paths on every request (#101).\n */\nconst warnedPaths = new Set<string>()\n\n/** @internal Test-only: clears the process-wide registry-miss dedup set. */\nexport function __resetRegistryMissWarnings(): void {\n warnedPaths.clear()\n}\n\nexport function createBoundaryHelpers(registry: AnyRegistry, options?: BoundaryHelpersOptions) {\n const onDecodeError = options?.onDecodeError ?? 'warn'\n const warnWirePreview = options?.warnWirePreview === true\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 if (path == null) return args\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/returns pass through unencoded. ` +\n 'This is expected when the target is a raw (non-zodvex) function; if it should be ' +\n 'codec-aware, run `zodvex generate` to update the registry.'\n )\n }\n return args\n }\n return stripUndefined(safeEncode(entry.args, args))\n }\n\n /**\n * Decode a wire result back to runtime types.\n *\n * Uses `.safeParse()` to decode. On failure:\n * - 'warn' (default): logs warning, returns raw wireResult\n * - 'throw': throws ZodvexDecodeError (extends z.ZodError) // zod-ok\n *\n * Passthrough when:\n * - function is not in the registry\n * - registry entry has no returns schema\n */\n function decodeResult(ref: FunctionReference<any, any, any, any>, wireResult: any): any {\n const path = resolveFunctionPath(ref)\n if (path == null) return wireResult\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 issueList = result.error.issues\n .map((i: $ZodIssue) => `${i.path.join('.')}: ${i.message}`)\n .join(', ')\n let message = `[zodvex] Decode failed for ${path}: ${issueList}. Returning raw wire data.`\n if (warnWirePreview) {\n let preview = '[unavailable]'\n try {\n preview = JSON.stringify(wireResult) ?? '[unavailable]'\n } catch {\n // Debug logging must not change warn-mode behavior for non-JSON values.\n }\n const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview\n message += ` Preview: ${truncated}`\n }\n console.warn(message)\n return wireResult\n }\n\n return { encodeArgs, decodeResult }\n}\n\nexport type BoundaryHelpers = ReturnType<typeof createBoundaryHelpers>\n","import type { OptionalRestArgsOrSkip } from 'convex/react'\nimport * as convexReact from 'convex/react'\nimport { useMutation, useQuery } from 'convex/react'\nimport type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'\nimport type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'\nimport { createBoundaryHelpers } from '../../internal/boundaryHelpers'\nimport type { AnyRegistry } from '../../internal/types'\n\n/** Query state, with failures omitted when throwOnError is enabled. */\nexport type UseQueryResult<Result, ThrowOnError extends boolean = false> =\n | { status: 'pending' }\n | { status: 'success'; data: Result }\n | (ThrowOnError extends true ? never : { status: 'error'; error: Error })\n\ntype UseQueryOptions<\n Query extends FunctionReference<'query', any, any, any>,\n ThrowOnError extends boolean\n> = {\n query: Query\n args: FunctionArgs<Query> | 'skip'\n throwOnError?: ThrowOnError\n}\n\nfunction codecError(error: unknown, operation: 'encode' | 'decode'): Error {\n return error instanceof Error\n ? error\n : new Error(`Failed to ${operation} query ${operation === 'encode' ? 'arguments' : 'result'}`, {\n cause: error\n })\n}\n\n/**\n * Creates zodvex-aware React hooks that automatically decode query results\n * and encode mutation arguments using the Zod schemas in the registry.\n *\n * Returned hooks are drop-in replacements for Convex's `useQuery` and\n * `useMutation` — they delegate to the real hooks, then apply codec\n * transforms so that runtime types (e.g. Date) are used instead of wire\n * types (e.g. number timestamps).\n *\n * @param registry - A map of function paths to `{ args?, returns? }` Zod schemas.\n * Typically generated by zodvex codegen into `_zodvex/client.ts`.\n *\n * @example\n * ```typescript\n * import { zodvexRegistry } from '../_zodvex/client'\n * export const { useZodQuery, useZodMutation } = createZodvexHooks(zodvexRegistry)\n *\n * // In a component:\n * const tasks = useZodQuery(api.tasks.list, { status: 'active' })\n * // ^? Task[] — createdAt is Date, not number\n * ```\n */\nexport function createZodvexHooks<R extends AnyRegistry>(\n registry: R,\n options?: BoundaryHelpersOptions\n) {\n const codec = createBoundaryHelpers(registry, options)\n const experimentalCodec = createBoundaryHelpers(registry, {\n ...options,\n onDecodeError: options?.onDecodeError ?? 'throw'\n })\n\n /**\n * Convex's object-form query hook with decoded arguments and results (Convex >=1.37).\n * Codec failures return an error state unless throwOnError is true. Decoding is\n * strict by default; explicit onDecodeError: 'warn' preserves the raw fallback.\n */\n function useQuery_experimental<\n Query extends FunctionReference<'query', any, any, any>,\n ThrowOnError extends boolean = false\n >(\n queryOptions: UseQueryOptions<Query, ThrowOnError>\n ): UseQueryResult<FunctionReturnType<Query>, ThrowOnError>\n function useQuery_experimental(\n queryOptions: UseQueryOptions<FunctionReference<'query', any, any, any>, boolean>\n ): UseQueryResult<any> {\n // Optional namespace access keeps older SDK imports valid and allows tree shaking.\n const nativeHook = (\n convexReact as unknown as {\n useQuery_experimental?: (\n options: UseQueryOptions<FunctionReference<'query', any, any, any>, boolean>\n ) => UseQueryResult<any>\n }\n ).useQuery_experimental\n if (typeof nativeHook !== 'function') {\n throw new Error(\n 'useQuery_experimental requires Convex >=1.37. Upgrade convex to use this hook.'\n )\n }\n const { query, args, throwOnError } = queryOptions\n let wireArgs: any = 'skip'\n let encodeFailure: Error | undefined\n if (args !== 'skip') {\n try {\n wireArgs = experimentalCodec.encodeArgs(query, args)\n } catch (error) {\n encodeFailure = codecError(error, 'encode')\n }\n }\n\n // Even failed encodes call the real hook; its own synchronous errors still propagate.\n const state = nativeHook({ query, args: wireArgs, throwOnError })\n if (encodeFailure) {\n if (throwOnError) throw encodeFailure\n return { status: 'error', error: encodeFailure }\n }\n if (state.status !== 'success') return state\n try {\n return { status: 'success', data: experimentalCodec.decodeResult(query, state.data) }\n } catch (error) {\n const failure = codecError(error, 'decode')\n if (throwOnError) throw failure\n return { status: 'error', error: failure }\n }\n }\n\n /**\n * Drop-in replacement for Convex's `useQuery` with automatic codec decode.\n *\n * Delegates to the real `useQuery` and then decodes the wire result through\n * the `returns` schema in the registry (if one exists for this function).\n *\n * Two overloads:\n * 1. Rest-args (Convex-compatible): `useZodQuery(ref, args)` or `useZodQuery(ref, 'skip')`\n * 2. Union args (composable): `useZodQuery(ref, args | 'skip')` — for wrappers\n * and conditional skip patterns where the decision is made upstream.\n *\n * - Invalid arguments throw during render; use a React error boundary to handle them.\n * - Loading state (`undefined`) passes through unchanged.\n * - Functions not in the registry return the raw wire result.\n */\n // Overload 1: drop-in compatible with Convex's useQuery\n function useZodQuery<Query extends FunctionReference<'query', any, any, any>>(\n ref: Query,\n ...args: OptionalRestArgsOrSkip<Query>\n ): FunctionReturnType<Query> | undefined\n // Overload 2: composable — accepts Args | 'skip' union for wrappers\n function useZodQuery<Query extends FunctionReference<'query', any, any, any>>(\n ref: Query,\n args: Query['_args'] | 'skip'\n ): FunctionReturnType<Query> | undefined\n // Implementation\n function useZodQuery(ref: FunctionReference<'query', any, any, any>, ...restArgs: any[]) {\n const args = restArgs[0]\n\n // Always call useQuery, including failed encodes, to preserve hook order.\n // Then surface the error to React's error boundary instead of appearing to load forever.\n let wireArgs: any = 'skip'\n let encodeFailure: { error: unknown } | undefined\n if (args !== 'skip') {\n try {\n wireArgs = codec.encodeArgs(ref, args)\n } catch (error) {\n encodeFailure = { error }\n }\n }\n\n const wireResult = useQuery(\n ref,\n ...((wireArgs === 'skip' ? ['skip'] : [wireArgs]) as OptionalRestArgsOrSkip<typeof ref>)\n )\n\n if (encodeFailure) throw encodeFailure.error\n\n // Loading state — Convex returns undefined while the subscription is pending\n if (wireResult === undefined) return undefined\n\n // Decode: wire format -> runtime types (e.g., timestamp number -> Date)\n return codec.decodeResult(ref, wireResult)\n }\n\n /**\n * Drop-in replacement for Convex's `useMutation`.\n *\n * Returns an async function that:\n * 1. Encodes the args through the `args` schema (runtime -> wire format)\n * 2. Calls the real mutation with the wire args\n * 3. Decodes the result through the `returns` schema (wire -> runtime format)\n *\n * Functions not in the registry pass args and results through unchanged.\n */\n function useZodMutation<Mutation extends FunctionReference<'mutation', any, any, any>>(\n ref: Mutation\n ) {\n const rawMutate = useMutation(ref)\n\n return async (args: FunctionArgs<Mutation>): Promise<FunctionReturnType<Mutation>> => {\n // Encode args: runtime types -> wire format (e.g., Date -> timestamp)\n const wireArgs = codec.encodeArgs(ref, args)\n\n const wireResult = await (rawMutate as any)(wireArgs)\n\n // Decode result: wire format -> runtime types\n return codec.decodeResult(ref, wireResult)\n }\n }\n\n return { useZodQuery, useZodMutation, useQuery_experimental }\n}\n\n/**\n * The return type of `createZodvexHooks` — useful for typing module-level\n * exports in generated client files.\n */\nexport type ZodvexHooks = ReturnType<typeof createZodvexHooks>\n","import type { AuthTokenFetcher, ConnectionState } from 'convex/browser'\nimport type { Watch, WatchQueryOptions } from 'convex/react'\nimport { ConvexReactClient } from 'convex/react'\nimport type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'\nimport type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'\nimport { createBoundaryHelpers } from '../../internal/boundaryHelpers'\nimport type { AnyRegistry } from '../../internal/types'\n\nexport type ZodvexReactClientOptions = ({ url: string } | { client: ConvexReactClient }) &\n BoundaryHelpersOptions\n\nexport class ZodvexReactClient<R extends AnyRegistry = AnyRegistry> {\n private codec: ReturnType<typeof createBoundaryHelpers>\n private innerClient?: ConvexReactClient\n private options: ZodvexReactClientOptions\n private pendingAuth?: {\n fetchToken: AuthTokenFetcher\n onChange?: (isAuthenticated: boolean) => void\n }\n\n constructor(registry: R, options: ZodvexReactClientOptions) {\n this.codec = createBoundaryHelpers(registry, {\n onDecodeError: options.onDecodeError,\n warnWirePreview: options.warnWirePreview\n })\n this.options = options\n if ('client' in options) {\n this.innerClient = options.client\n }\n }\n\n private getUrl(): string {\n if ('url' in this.options) return this.options.url\n if (this.innerClient) return this.innerClient.url\n throw new Error('[zodvex] ZodvexReactClient is missing a Convex URL.')\n }\n\n private getConvex(): ConvexReactClient {\n if (this.innerClient) return this.innerClient\n\n const client = new ConvexReactClient(this.getUrl())\n if (this.pendingAuth) {\n client.setAuth(this.pendingAuth.fetchToken, this.pendingAuth.onChange)\n }\n this.innerClient = client\n return client\n }\n\n get convex(): ConvexReactClient {\n return this.getConvex()\n }\n\n // ---------------------------------------------------------------------------\n // Data methods — codec-wrapped\n // ---------------------------------------------------------------------------\n\n async query<Q extends FunctionReference<'query', any, any, any>>(\n ref: Q,\n args: Q['_args']\n ): Promise<Q['_returnType']> {\n const wireResult = await this.getConvex().query(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<Q>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n async mutation<M extends FunctionReference<'mutation', any, any, any>>(\n ref: M,\n args: M['_args']\n ): Promise<M['_returnType']> {\n const wireResult = await this.getConvex().mutation(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<M>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n async action<A extends FunctionReference<'action', any, any, any>>(\n ref: A,\n args: A['_args']\n ): Promise<A['_returnType']> {\n const wireResult = await this.getConvex().action(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<A>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n /**\n * Indicates likely future interest in a query subscription. Encodes args to\n * wire before delegating, mirroring {@link watchQuery}.\n */\n prewarmQuery<Q extends FunctionReference<'query', any, any, any>>(queryOptions: {\n query: Q\n args: Q['_args']\n extendSubscriptionFor?: number\n }): void {\n const wireArgs = this.codec.encodeArgs(queryOptions.query, queryOptions.args) as FunctionArgs<Q>\n this.getConvex().prewarmQuery({ ...queryOptions, args: wireArgs })\n }\n\n watchQuery<Q extends FunctionReference<'query', any, any, any>>(\n ref: Q,\n args: Q['_args'],\n options?: WatchQueryOptions\n ): Watch<Q['_returnType']> {\n const wireArgs = this.codec.encodeArgs(ref, args) as FunctionArgs<Q>\n const innerWatch = this.getConvex().watchQuery(ref, wireArgs, options as any)\n\n // Memoize by wire reference identity to avoid redundant Zod parse.\n // Convex creates a new object per server transition via jsonToConvex()\n // in remote_query_set.ts, but returns the same reference for repeated\n // reads within a single transition window.\n // See: convex/src/browser/sync/optimistic_updates_impl.ts\n // TODO(CX-733) — Convex internal tracker for client-side result\n // memoization (not yet public).\n let lastWire: unknown\n let lastDecoded: unknown\n\n return {\n onUpdate: (cb: () => void) => innerWatch.onUpdate(cb),\n localQueryResult: () => {\n const wire = innerWatch.localQueryResult()\n if (wire === lastWire) return lastDecoded\n const decoded = wire === undefined ? undefined : this.codec.decodeResult(ref, wire)\n lastWire = wire\n lastDecoded = decoded\n return lastDecoded\n },\n journal: () => innerWatch.journal()\n }\n }\n\n // ---------------------------------------------------------------------------\n // Pass-through methods — no codec needed\n // ---------------------------------------------------------------------------\n\n setAuth(fetchToken: AuthTokenFetcher, onChange?: (isAuthenticated: boolean) => void): void {\n this.pendingAuth = { fetchToken, onChange }\n if (this.innerClient) {\n this.innerClient.setAuth(fetchToken, onChange)\n }\n }\n\n clearAuth(): void {\n this.pendingAuth = undefined\n this.innerClient?.clearAuth()\n }\n\n async close(): Promise<void> {\n await this.getConvex().close()\n }\n\n get url(): string {\n return this.getUrl()\n }\n\n get logger(): ConvexReactClient['logger'] {\n return this.getConvex().logger\n }\n\n connectionState() {\n return this.getConvex().connectionState()\n }\n\n subscribeToConnectionState(cb: (state: ConnectionState) => void): () => void {\n return this.getConvex().subscribeToConnectionState(cb)\n }\n}\n\nexport function createZodvexReactClient<R extends AnyRegistry>(\n registry: R,\n options: ZodvexReactClientOptions\n): ZodvexReactClient<R> {\n return new ZodvexReactClient(registry, options)\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/internal/normalizeCodecPaths.ts","../../../src/internal/stripUndefined.ts","../../../src/internal/boundaryHelpers.ts","../../../src/internal/paginationCodec.ts","../../../src/public/react/hooks.ts","../../../src/public/react/zodvexReactClient.ts"],"names":["useQuery_experimental"],"mappings":";;;;;;;;AAeA,SAAS,YAAY,MAAA,EAA4B;AAC/C,EAAA,IAAI,OAAA,GAAoB,MAAA;AACxB,EAAA,KA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A;AAAA,EAMA,OAAA,CAAQ,YAA8B,QAAA,EAAqD;AACzF,IAAA,IAAA,CAAK,WAAA,GAAc,EAAE,UAAA,EAAY,QAAA,EAAS;AAC1C,IAAA,IAAI,KAAK,WAAA,EAAa;AACpB,MAAA,IAAA,CAAK,WAAA,CAAY,OAAA,CAAQ,UAAA,EAAY,QAAQ,CAAA;AAAA,IAC/C;AAAA,EACF;AAAA,EAEA,SAAA,GAAkB;AAChB,IAAA,IAAA,CAAK,WAAA,GAAc,MAAA;AACnB,IAAA,IAAA,CAAK,aAAa,SAAA,EAAU;AAAA,EAC9B;AAAA,EAEA,MAAM,KAAA,GAAuB;AAC3B,IAAA,MAAM,IAAA,CAAK,SAAA,EAAU,CAAE,KAAA,EAAM;AAAA,EAC/B;AAAA,EAEA,IAAI,GAAA,GAAc;AAChB,IAAA,OAAO,KAAK,MAAA,EAAO;AAAA,EACrB;AAAA,EAEA,IAAI,MAAA,GAAsC;AACxC,IAAA,OAAO,IAAA,CAAK,WAAU,CAAE,MAAA;AAAA,EAC1B;AAAA,EAEA,eAAA,GAAkB;AAChB,IAAA,OAAO,IAAA,CAAK,SAAA,EAAU,CAAE,eAAA,EAAgB;AAAA,EAC1C;AAAA,EAEA,2BAA2B,EAAA,EAAkD;AAC3E,IAAA,OAAO,IAAA,CAAK,SAAA,EAAU,CAAE,0BAAA,CAA2B,EAAE,CAAA;AAAA,EACvD;AACF;AAEO,SAAS,uBAAA,CACd,UACA,OAAA,EACsB;AACtB,EAAA,OAAO,IAAI,iBAAA,CAAkB,QAAA,EAAU,OAAO,CAAA;AAChD","file":"index.js","sourcesContent":["import {\n $ZodArray,\n $ZodCodec,\n $ZodDefault,\n $ZodError,\n $ZodNullable,\n $ZodObject,\n $ZodOptional,\n $ZodType,\n encode\n} from './zod-core'\n\n/**\n * Unwraps ZodOptional/ZodNullable/ZodDefault wrappers to get the structural type.\n */\nfunction unwrapOuter(schema: $ZodType): $ZodType {\n let current: $ZodType = schema\n for (let i = 0; i < 10; i++) {\n if (\n current instanceof $ZodOptional ||\n current instanceof $ZodNullable ||\n current instanceof $ZodDefault\n ) {\n current = current._zod.def.innerType\n continue\n }\n break\n }\n return current\n}\n\n/**\n * Walks a path through a schema tree, truncating at codec boundaries.\n * When a codec is encountered, the path is cut — any deeper segments\n * are wire-internal and should not be exposed to consumers.\n */\nfunction truncateAtCodecBoundary(path: (string | number)[], schema: $ZodType): (string | number)[] {\n const result: (string | number)[] = []\n let current: $ZodType = schema\n\n for (const segment of path) {\n current = unwrapOuter(current)\n\n // If we've landed on a codec, everything from here is wire-internal — stop\n if (current instanceof $ZodCodec) {\n break\n }\n\n // Descend into objects\n if (current instanceof $ZodObject && typeof segment === 'string') {\n const fieldSchema = current._zod.def.shape[segment] as $ZodType | undefined\n if (!fieldSchema) {\n // Unknown field — include segment and stop\n result.push(segment)\n break\n }\n\n result.push(segment)\n\n const unwrapped = unwrapOuter(fieldSchema)\n if (unwrapped instanceof $ZodCodec) {\n // Hit a codec boundary — truncate here\n break\n }\n\n current = fieldSchema\n continue\n }\n\n // Descend into arrays\n if (current instanceof $ZodArray && typeof segment === 'number') {\n result.push(segment)\n current = current._zod.def.element\n continue\n }\n\n // For anything else (unions, records, etc.), include segment and continue\n result.push(segment)\n }\n\n return result\n}\n\n/**\n * Normalizes ZodError paths by truncating at codec boundaries.\n *\n * When z.encode() throws a ZodError, the paths reflect the wire schema\n * structure (e.g., [\"email\", \"value\"] for a custom codec).\n * This function strips the wire-internal segments so consumers see\n * clean field-level paths (e.g., [\"email\"]).\n */\nexport function normalizeCodecPaths(error: $ZodError, schema: $ZodType): $ZodError {\n const normalized = error.issues.map(issue => ({\n ...issue,\n path: truncateAtCodecBoundary(issue.path as (string | number)[], schema)\n }))\n return new $ZodError(normalized)\n}\n\n/**\n * Encodes a value through a Zod schema, normalizing codec-internal\n * path segments in any ZodError before re-throwing.\n *\n * Drop-in replacement for `z.encode(schema, value)` at client boundaries.\n */\nexport function safeEncode(schema: $ZodType, value: unknown): unknown {\n try {\n return encode(schema, value)\n } catch (e) {\n if (e instanceof $ZodError) throw normalizeCodecPaths(e as $ZodError, schema)\n throw e\n }\n}\n","/**\n * Recursively strips `undefined` values from objects and arrays.\n * Used by codec encode/decode to clean wire data.\n *\n * Extracted to its own module so client-safe code (boundaryHelpers)\n * can import it without pulling in zod via utils.ts.\n */\nexport function stripUndefined<T>(value: T): T {\n if (value === null || value === undefined) {\n return value\n }\n\n if (Array.isArray(value)) {\n return value.map(stripUndefined) as T\n }\n\n // Only process plain objects (not class instances, Dates, etc.)\n if (typeof value === 'object' && value.constructor === Object) {\n const result: Record<string, unknown> = {}\n for (const [key, val] of Object.entries(value)) {\n if (val !== undefined) {\n result[key] = stripUndefined(val)\n }\n }\n return result as T\n }\n\n return value\n}\n","import type { FunctionReference } from 'convex/server'\nimport type { $ZodIssue } from 'zod/v4/core'\nimport { safeEncode } from './normalizeCodecPaths'\nimport { stripUndefined } from './stripUndefined'\nimport type { AnyRegistry } from './types'\nimport { $ZodError, safeParse } from './zod-core'\n\n/**\n * Resolves a Convex FunctionReference to its string path.\n *\n * Mirrors `getFunctionName` from `convex/server` but without the server import.\n * Reads the well-known `Symbol.for('functionName')` that Convex attaches to all\n * function references — the same symbol used by Convex's own browser client.\n */\nconst functionNameSymbol = Symbol.for('functionName')\n\nexport function resolveFunctionPath(ref: FunctionReference<any, any, any, any>): string | null {\n if (typeof ref === 'string') return ref\n const name = (ref as any)[functionNameSymbol]\n if (!name) return null\n return name\n}\n\n/**\n * Options for codec helper behavior.\n */\nexport type BoundaryHelpersOptions = {\n /**\n * How to handle decode failures (schema validation errors on wire data).\n *\n * - `'warn'` (default): log a console.warn and return raw wire data untransformed.\n * - `'throw'`: throw a ZodvexDecodeError (extends z.ZodError). // zod-ok\n */\n onDecodeError?: 'warn' | 'throw'\n /**\n * Include a truncated preview of the raw wire data in the decode-failure\n * `warn` log (only relevant when `onDecodeError` is `'warn'`, the default).\n *\n * Off by default because wire values may be sensitive — the default warn\n * message only carries the function path and zod issue list. Enable only\n * when debugging a decode skew and you need to see the offending values.\n */\n warnWirePreview?: boolean\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 */\n/**\n * Module-scoped so the registry-miss note fires once per path per process.\n * A per-helpers set resets on every Convex invocation (ctx is wrapped per\n * call), which spammed hot paths on every request (#101).\n */\nconst warnedPaths = new Set<string>()\n\n/** @internal Test-only: clears the process-wide registry-miss dedup set. */\nexport function __resetRegistryMissWarnings(): void {\n warnedPaths.clear()\n}\n\nexport function createBoundaryHelpers(registry: AnyRegistry, options?: BoundaryHelpersOptions) {\n const onDecodeError = options?.onDecodeError ?? 'warn'\n const warnWirePreview = options?.warnWirePreview === true\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 if (path == null) return args\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/returns pass through unencoded. ` +\n 'This is expected when the target is a raw (non-zodvex) function; if it should be ' +\n 'codec-aware, run `zodvex generate` to update the registry.'\n )\n }\n return args\n }\n return stripUndefined(safeEncode(entry.args, args))\n }\n\n /**\n * Decode a wire result back to runtime types.\n *\n * Uses `.safeParse()` to decode. On failure:\n * - 'warn' (default): logs warning, returns raw wireResult\n * - 'throw': throws ZodvexDecodeError (extends z.ZodError) // zod-ok\n *\n * Passthrough when:\n * - function is not in the registry\n * - registry entry has no returns schema\n */\n function decodeResult(ref: FunctionReference<any, any, any, any>, wireResult: any): any {\n const path = resolveFunctionPath(ref)\n if (path == null) return wireResult\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 issueList = result.error.issues\n .map((i: $ZodIssue) => `${i.path.join('.')}: ${i.message}`)\n .join(', ')\n let message = `[zodvex] Decode failed for ${path}: ${issueList}. Returning raw wire data.`\n if (warnWirePreview) {\n let preview = '[unavailable]'\n try {\n preview = JSON.stringify(wireResult) ?? '[unavailable]'\n } catch {\n // Debug logging must not change warn-mode behavior for non-JSON values.\n }\n const truncated = preview.length > 200 ? `${preview.slice(0, 200)}...` : preview\n message += ` Preview: ${truncated}`\n }\n console.warn(message)\n return wireResult\n }\n\n return { encodeArgs, decodeResult }\n}\n\nexport type BoundaryHelpers = ReturnType<typeof createBoundaryHelpers>\n","import type { FunctionReference } from 'convex/server'\nimport { createBoundaryHelpers, resolveFunctionPath } from './boundaryHelpers'\nimport type { AnyRegistry } from './types'\nimport { $ZodArray, $ZodObject, clone } from './zod-core'\n\n/** Aggregate pagination only exposes items, not the original page envelopes. */\nexport function createPaginationCodec(registry: AnyRegistry) {\n const argsRegistry: AnyRegistry = Object.create(null)\n const resultsRegistry: AnyRegistry = Object.create(null)\n const argsCodec = createBoundaryHelpers(argsRegistry, { onDecodeError: 'throw' })\n const resultsCodec = createBoundaryHelpers(resultsRegistry, { onDecodeError: 'throw' })\n\n function unsupported(path: string, boundary: string): never {\n throw new Error(\n `[zodvex] Unsupported pagination ${boundary} schema for \"${path}\". ` +\n 'Use an unrefined argument object and an unrefined return object with an unrefined page array. ' +\n 'Item schemas may contain codecs and refinements. For whole-page checks or transforms, ' +\n 'use query or subscribe with explicit paginationOpts.'\n )\n }\n\n function encodeArgs(ref: FunctionReference<'query'>, args: unknown): any {\n const path = resolveFunctionPath(ref)\n if (path !== null && !Object.hasOwn(argsRegistry, path)) {\n const schema = registry[path]?.args\n if (schema) {\n if (!(schema instanceof $ZodObject) || schema._zod.def.checks?.length) {\n unsupported(path, 'argument')\n }\n const { paginationOpts: _paginationOpts, ...shape } = schema._zod.def.shape\n argsRegistry[path] = { args: clone(schema, { ...schema._zod.def, shape }) }\n } else {\n argsRegistry[path] = {}\n }\n }\n return argsCodec.encodeArgs(ref, args)\n }\n\n function decodeResults(ref: FunctionReference<'query'>, results: unknown[]): any[] {\n const path = resolveFunctionPath(ref)\n if (path !== null && !Object.hasOwn(resultsRegistry, path)) {\n const schema = registry[path]?.returns\n if (schema) {\n if (!(schema instanceof $ZodObject) || schema._zod.def.checks?.length) {\n unsupported(path, 'return')\n }\n const page = schema._zod.def.shape.page\n if (!(page instanceof $ZodArray) || page._zod.def.checks?.length) {\n unsupported(path, 'page')\n }\n resultsRegistry[path] = { returns: page }\n } else {\n resultsRegistry[path] = {}\n }\n }\n return resultsCodec.decodeResult(ref, results)\n }\n\n return { encodeArgs, decodeResults }\n}\n","import type {\n OptionalRestArgsOrSkip,\n PaginatedQueryReference,\n UsePaginatedQueryResult\n} from 'convex/react'\nimport * as convexReact from 'convex/react'\nimport { useMutation, usePaginatedQuery, useQuery } from 'convex/react'\nimport type {\n FunctionArgs,\n FunctionReference,\n FunctionReturnType,\n PaginationOptions\n} from 'convex/server'\nimport { useMemo } from 'react'\nimport type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'\nimport { createBoundaryHelpers, resolveFunctionPath } from '../../internal/boundaryHelpers'\nimport { createPaginationCodec } from '../../internal/paginationCodec'\nimport type { AnyRegistry } from '../../internal/types'\n\n/** Query state, with failures omitted when throwOnError is enabled. */\nexport type UseQueryResult<Result, ThrowOnError extends boolean = false> =\n | { status: 'pending' }\n | { status: 'success'; data: Result }\n | (ThrowOnError extends true ? never : { status: 'error'; error: Error })\n\ntype UseQueryOptions<\n Query extends FunctionReference<'query', any, any, any>,\n ThrowOnError extends boolean\n> = {\n query: Query\n args: FunctionArgs<Query> | 'skip'\n throwOnError?: ThrowOnError\n}\n\nfunction codecError(error: unknown, operation: 'encode' | 'decode'): Error {\n return error instanceof Error\n ? error\n : new Error(`Failed to ${operation} query ${operation === 'encode' ? 'arguments' : 'result'}`, {\n cause: error\n })\n}\n\n/**\n * Creates zodvex-aware React hooks that automatically decode query results\n * and encode mutation arguments using the Zod schemas in the registry.\n *\n * Returned hooks are drop-in replacements for Convex's `useQuery` and\n * `useMutation` — they delegate to the real hooks, then apply codec\n * transforms so that runtime types (e.g. Date) are used instead of wire\n * types (e.g. number timestamps).\n *\n * @param registry - A map of function paths to `{ args?, returns? }` Zod schemas.\n * Typically generated by zodvex codegen into `_zodvex/client.ts`.\n *\n * @example\n * ```typescript\n * import { zodvexRegistry } from '../_zodvex/client'\n * export const { useZodQuery, useZodMutation } = createZodvexHooks(zodvexRegistry)\n *\n * // In a component:\n * const tasks = useZodQuery(api.tasks.list, { status: 'active' })\n * // ^? Task[] — createdAt is Date, not number\n * ```\n */\nexport function createZodvexHooks<R extends AnyRegistry>(\n registry: R,\n options?: BoundaryHelpersOptions\n) {\n const codec = createBoundaryHelpers(registry, options)\n const paginationCodec = createPaginationCodec(registry)\n const experimentalCodec = createBoundaryHelpers(registry, {\n ...options,\n onDecodeError: options?.onDecodeError ?? 'throw'\n })\n\n /**\n * Convex pagination with encoded filters and decoded items. Pagination metadata\n * stays under Convex's control. Codec errors throw, including in warn mode.\n * Outer object/array refinements and transforms require explicit page queries.\n */\n function useZodPaginatedQuery<\n Query extends FunctionReference<\n 'query',\n 'public',\n { paginationOpts?: PaginationOptions },\n { page: any[]; isDone: boolean; continueCursor: string }\n >\n >(\n ref: Query,\n args: Omit<FunctionArgs<Query>, 'paginationOpts'> | 'skip',\n paginationOptions: { initialNumItems: number }\n ): UsePaginatedQueryResult<FunctionReturnType<Query>['page'][number]> {\n let wireArgs: any = 'skip'\n let encodeFailure: { error: unknown } | undefined\n if (args !== 'skip') {\n try {\n wireArgs = paginationCodec.encodeArgs(ref, args)\n } catch (error) {\n encodeFailure = { error }\n }\n }\n const state = usePaginatedQuery(ref as PaginatedQueryReference, wireArgs, paginationOptions)\n const skipped = wireArgs === 'skip'\n const queryKey = resolveFunctionPath(ref) ?? ref\n const results = useMemo(\n () => (skipped ? state.results : paginationCodec.decodeResults(ref, state.results)),\n [queryKey, state.results, skipped]\n )\n // Call both hooks on failed encodes too, so a failure never changes hook order.\n if (encodeFailure) throw encodeFailure.error\n return { ...state, results }\n }\n\n /**\n * Convex's object-form query hook with decoded arguments and results (Convex >=1.37).\n * Codec failures return an error state unless throwOnError is true. Decoding is\n * strict by default; explicit onDecodeError: 'warn' preserves the raw fallback.\n */\n function useQuery_experimental<\n Query extends FunctionReference<'query', any, any, any>,\n ThrowOnError extends boolean = false\n >(\n queryOptions: UseQueryOptions<Query, ThrowOnError>\n ): UseQueryResult<FunctionReturnType<Query>, ThrowOnError>\n function useQuery_experimental(\n queryOptions: UseQueryOptions<FunctionReference<'query', any, any, any>, boolean>\n ): UseQueryResult<any> {\n // Optional namespace access keeps older SDK imports valid and allows tree shaking.\n const nativeHook = (\n convexReact as unknown as {\n useQuery_experimental?: (\n options: UseQueryOptions<FunctionReference<'query', any, any, any>, boolean>\n ) => UseQueryResult<any>\n }\n ).useQuery_experimental\n if (typeof nativeHook !== 'function') {\n throw new Error(\n 'useQuery_experimental requires Convex >=1.37. Upgrade convex to use this hook.'\n )\n }\n const { query, args, throwOnError } = queryOptions\n let wireArgs: any = 'skip'\n let encodeFailure: Error | undefined\n if (args !== 'skip') {\n try {\n wireArgs = experimentalCodec.encodeArgs(query, args)\n } catch (error) {\n encodeFailure = codecError(error, 'encode')\n }\n }\n\n // Even failed encodes call the real hook; its own synchronous errors still propagate.\n const state = nativeHook({ query, args: wireArgs, throwOnError })\n if (encodeFailure) {\n if (throwOnError) throw encodeFailure\n return { status: 'error', error: encodeFailure }\n }\n if (state.status !== 'success') return state\n try {\n return { status: 'success', data: experimentalCodec.decodeResult(query, state.data) }\n } catch (error) {\n const failure = codecError(error, 'decode')\n if (throwOnError) throw failure\n return { status: 'error', error: failure }\n }\n }\n\n /**\n * Drop-in replacement for Convex's `useQuery` with automatic codec decode.\n *\n * Delegates to the real `useQuery` and then decodes the wire result through\n * the `returns` schema in the registry (if one exists for this function).\n *\n * Two overloads:\n * 1. Rest-args (Convex-compatible): `useZodQuery(ref, args)` or `useZodQuery(ref, 'skip')`\n * 2. Union args (composable): `useZodQuery(ref, args | 'skip')` — for wrappers\n * and conditional skip patterns where the decision is made upstream.\n *\n * - Invalid arguments throw during render; use a React error boundary to handle them.\n * - Loading state (`undefined`) passes through unchanged.\n * - Functions not in the registry return the raw wire result.\n */\n // Overload 1: drop-in compatible with Convex's useQuery\n function useZodQuery<Query extends FunctionReference<'query', any, any, any>>(\n ref: Query,\n ...args: OptionalRestArgsOrSkip<Query>\n ): FunctionReturnType<Query> | undefined\n // Overload 2: composable — accepts Args | 'skip' union for wrappers\n function useZodQuery<Query extends FunctionReference<'query', any, any, any>>(\n ref: Query,\n args: Query['_args'] | 'skip'\n ): FunctionReturnType<Query> | undefined\n // Implementation\n function useZodQuery(ref: FunctionReference<'query', any, any, any>, ...restArgs: any[]) {\n const args = restArgs[0]\n\n // Always call useQuery, including failed encodes, to preserve hook order.\n // Then surface the error to React's error boundary instead of appearing to load forever.\n let wireArgs: any = 'skip'\n let encodeFailure: { error: unknown } | undefined\n if (args !== 'skip') {\n try {\n wireArgs = codec.encodeArgs(ref, args)\n } catch (error) {\n encodeFailure = { error }\n }\n }\n\n const wireResult = useQuery(\n ref,\n ...((wireArgs === 'skip' ? ['skip'] : [wireArgs]) as OptionalRestArgsOrSkip<typeof ref>)\n )\n\n if (encodeFailure) throw encodeFailure.error\n\n // Loading state — Convex returns undefined while the subscription is pending\n if (wireResult === undefined) return undefined\n\n // Decode: wire format -> runtime types (e.g., timestamp number -> Date)\n return codec.decodeResult(ref, wireResult)\n }\n\n /**\n * Drop-in replacement for Convex's `useMutation`.\n *\n * Returns an async function that:\n * 1. Encodes the args through the `args` schema (runtime -> wire format)\n * 2. Calls the real mutation with the wire args\n * 3. Decodes the result through the `returns` schema (wire -> runtime format)\n *\n * Functions not in the registry pass args and results through unchanged.\n */\n function useZodMutation<Mutation extends FunctionReference<'mutation', any, any, any>>(\n ref: Mutation\n ) {\n const rawMutate = useMutation(ref)\n\n return async (args: FunctionArgs<Mutation>): Promise<FunctionReturnType<Mutation>> => {\n // Encode args: runtime types -> wire format (e.g., Date -> timestamp)\n const wireArgs = codec.encodeArgs(ref, args)\n\n const wireResult = await (rawMutate as any)(wireArgs)\n\n // Decode result: wire format -> runtime types\n return codec.decodeResult(ref, wireResult)\n }\n }\n\n return { useZodQuery, useZodMutation, useZodPaginatedQuery, useQuery_experimental }\n}\n\n/**\n * The return type of `createZodvexHooks` — useful for typing module-level\n * exports in generated client files.\n */\nexport type ZodvexHooks = ReturnType<typeof createZodvexHooks>\n","import type { AuthTokenFetcher, ConnectionState } from 'convex/browser'\nimport type { Watch, WatchQueryOptions } from 'convex/react'\nimport { ConvexReactClient } from 'convex/react'\nimport type { FunctionArgs, FunctionReference, FunctionReturnType } from 'convex/server'\nimport type { BoundaryHelpersOptions } from '../../internal/boundaryHelpers'\nimport { createBoundaryHelpers } from '../../internal/boundaryHelpers'\nimport type { AnyRegistry } from '../../internal/types'\n\nexport type ZodvexReactClientOptions = ({ url: string } | { client: ConvexReactClient }) &\n BoundaryHelpersOptions\n\nexport class ZodvexReactClient<R extends AnyRegistry = AnyRegistry> {\n private codec: ReturnType<typeof createBoundaryHelpers>\n private innerClient?: ConvexReactClient\n private options: ZodvexReactClientOptions\n private pendingAuth?: {\n fetchToken: AuthTokenFetcher\n onChange?: (isAuthenticated: boolean) => void\n }\n\n constructor(registry: R, options: ZodvexReactClientOptions) {\n this.codec = createBoundaryHelpers(registry, {\n onDecodeError: options.onDecodeError,\n warnWirePreview: options.warnWirePreview\n })\n this.options = options\n if ('client' in options) {\n this.innerClient = options.client\n }\n }\n\n private getUrl(): string {\n if ('url' in this.options) return this.options.url\n if (this.innerClient) return this.innerClient.url\n throw new Error('[zodvex] ZodvexReactClient is missing a Convex URL.')\n }\n\n private getConvex(): ConvexReactClient {\n if (this.innerClient) return this.innerClient\n\n const client = new ConvexReactClient(this.getUrl())\n if (this.pendingAuth) {\n client.setAuth(this.pendingAuth.fetchToken, this.pendingAuth.onChange)\n }\n this.innerClient = client\n return client\n }\n\n get convex(): ConvexReactClient {\n return this.getConvex()\n }\n\n // ---------------------------------------------------------------------------\n // Data methods — codec-wrapped\n // ---------------------------------------------------------------------------\n\n async query<Q extends FunctionReference<'query', any, any, any>>(\n ref: Q,\n args: Q['_args']\n ): Promise<Q['_returnType']> {\n const wireResult = await this.getConvex().query(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<Q>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n async mutation<M extends FunctionReference<'mutation', any, any, any>>(\n ref: M,\n args: M['_args']\n ): Promise<M['_returnType']> {\n const wireResult = await this.getConvex().mutation(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<M>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n async action<A extends FunctionReference<'action', any, any, any>>(\n ref: A,\n args: A['_args']\n ): Promise<A['_returnType']> {\n const wireResult = await this.getConvex().action(\n ref,\n this.codec.encodeArgs(ref, args) as FunctionArgs<A>\n )\n return this.codec.decodeResult(ref, wireResult)\n }\n\n /**\n * Indicates likely future interest in a query subscription. Encodes args to\n * wire before delegating, mirroring {@link watchQuery}.\n */\n prewarmQuery<Q extends FunctionReference<'query', any, any, any>>(queryOptions: {\n query: Q\n args: Q['_args']\n extendSubscriptionFor?: number\n }): void {\n const wireArgs = this.codec.encodeArgs(queryOptions.query, queryOptions.args) as FunctionArgs<Q>\n this.getConvex().prewarmQuery({ ...queryOptions, args: wireArgs })\n }\n\n watchQuery<Q extends FunctionReference<'query', any, any, any>>(\n ref: Q,\n args: Q['_args'],\n options?: WatchQueryOptions\n ): Watch<Q['_returnType']> {\n const wireArgs = this.codec.encodeArgs(ref, args) as FunctionArgs<Q>\n const innerWatch = this.getConvex().watchQuery(ref, wireArgs, options as any)\n\n // Memoize by wire reference identity to avoid redundant Zod parse.\n // Convex creates a new object per server transition via jsonToConvex()\n // in remote_query_set.ts, but returns the same reference for repeated\n // reads within a single transition window.\n // See: convex/src/browser/sync/optimistic_updates_impl.ts\n // TODO(CX-733) — Convex internal tracker for client-side result\n // memoization (not yet public).\n let lastWire: unknown\n let lastDecoded: unknown\n\n return {\n onUpdate: (cb: () => void) => innerWatch.onUpdate(cb),\n localQueryResult: () => {\n const wire = innerWatch.localQueryResult()\n if (wire === lastWire) return lastDecoded\n const decoded = wire === undefined ? undefined : this.codec.decodeResult(ref, wire)\n lastWire = wire\n lastDecoded = decoded\n return lastDecoded\n },\n journal: () => innerWatch.journal()\n }\n }\n\n // ---------------------------------------------------------------------------\n // Pass-through methods — no codec needed\n // ---------------------------------------------------------------------------\n\n setAuth(fetchToken: AuthTokenFetcher, onChange?: (isAuthenticated: boolean) => void): void {\n this.pendingAuth = { fetchToken, onChange }\n if (this.innerClient) {\n this.innerClient.setAuth(fetchToken, onChange)\n }\n }\n\n clearAuth(): void {\n this.pendingAuth = undefined\n this.innerClient?.clearAuth()\n }\n\n async close(): Promise<void> {\n await this.getConvex().close()\n }\n\n get url(): string {\n return this.getUrl()\n }\n\n get logger(): ConvexReactClient['logger'] {\n return this.getConvex().logger\n }\n\n connectionState() {\n return this.getConvex().connectionState()\n }\n\n subscribeToConnectionState(cb: (state: ConnectionState) => void): () => void {\n return this.getConvex().subscribeToConnectionState(cb)\n }\n}\n\nexport function createZodvexReactClient<R extends AnyRegistry>(\n registry: R,\n options: ZodvexReactClientOptions\n): ZodvexReactClient<R> {\n return new ZodvexReactClient(registry, options)\n}\n"]}
|