convex 1.35.0 → 1.35.1
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/browser.bundle.js +2 -8
- package/dist/browser.bundle.js.map +3 -3
- package/dist/cjs/browser/index-node.js +1 -3
- package/dist/cjs/browser/index.js +1 -3
- package/dist/cjs/browser/index.js.map +2 -2
- package/dist/cjs/browser/query_options.js.map +2 -2
- package/dist/cjs/cli/codegen_templates/readme.js +1 -14
- package/dist/cjs/cli/codegen_templates/readme.js.map +2 -2
- package/dist/cjs/cli/deploy.js +1 -1
- package/dist/cjs/cli/deploy.js.map +1 -1
- package/dist/cjs/cli/lib/envvars.js +8 -1
- package/dist/cjs/cli/lib/envvars.js.map +2 -2
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/react/client.js +6 -43
- package/dist/cjs/react/client.js.map +2 -2
- package/dist/cjs/react/index.js +0 -2
- package/dist/cjs/react/index.js.map +2 -2
- package/dist/cjs/server/api.js.map +2 -2
- package/dist/cjs-types/browser/index.d.ts +0 -1
- package/dist/cjs-types/browser/index.d.ts.map +1 -1
- package/dist/cjs-types/browser/query_options.d.ts +9 -12
- package/dist/cjs-types/browser/query_options.d.ts.map +1 -1
- package/dist/cjs-types/cli/codegen_templates/readme.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deployApi/definitionConfig.d.ts +24 -24
- package/dist/cjs-types/cli/lib/deployApi/modules.d.ts +2 -2
- package/dist/cjs-types/cli/lib/deployApi/startPush.d.ts +36 -36
- package/dist/cjs-types/cli/lib/envvars.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/mcp/tools/insights.d.ts +2 -2
- package/dist/cjs-types/index.d.ts +1 -1
- package/dist/cjs-types/react/client.d.ts +2 -54
- package/dist/cjs-types/react/client.d.ts.map +1 -1
- package/dist/cjs-types/react/index.d.ts +2 -7
- package/dist/cjs-types/react/index.d.ts.map +1 -1
- package/dist/cjs-types/server/api.d.ts +1 -5
- package/dist/cjs-types/server/api.d.ts.map +1 -1
- package/dist/cli.bundle.cjs +11 -17
- package/dist/cli.bundle.cjs.map +2 -2
- package/dist/esm/browser/index-node.js +0 -1
- package/dist/esm/browser/index.js +0 -1
- package/dist/esm/browser/index.js.map +2 -2
- package/dist/esm/browser/query_options.js.map +2 -2
- package/dist/esm/cli/codegen_templates/readme.js +1 -14
- package/dist/esm/cli/codegen_templates/readme.js.map +2 -2
- package/dist/esm/cli/deploy.js +1 -1
- package/dist/esm/cli/deploy.js.map +1 -1
- package/dist/esm/cli/lib/envvars.js +8 -1
- package/dist/esm/cli/lib/envvars.js.map +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/react/client.js +6 -43
- package/dist/esm/react/client.js.map +2 -2
- package/dist/esm/react/index.js +0 -1
- package/dist/esm/react/index.js.map +2 -2
- package/dist/esm/server/api.js.map +2 -2
- package/dist/esm-types/browser/index.d.ts +0 -1
- package/dist/esm-types/browser/index.d.ts.map +1 -1
- package/dist/esm-types/browser/query_options.d.ts +9 -12
- package/dist/esm-types/browser/query_options.d.ts.map +1 -1
- package/dist/esm-types/cli/codegen_templates/readme.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deployApi/definitionConfig.d.ts +24 -24
- package/dist/esm-types/cli/lib/deployApi/modules.d.ts +2 -2
- package/dist/esm-types/cli/lib/deployApi/startPush.d.ts +36 -36
- package/dist/esm-types/cli/lib/envvars.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/mcp/tools/insights.d.ts +2 -2
- package/dist/esm-types/index.d.ts +1 -1
- package/dist/esm-types/react/client.d.ts +2 -54
- package/dist/esm-types/react/client.d.ts.map +1 -1
- package/dist/esm-types/react/index.d.ts +2 -7
- package/dist/esm-types/react/index.d.ts.map +1 -1
- package/dist/esm-types/server/api.d.ts +1 -5
- package/dist/esm-types/server/api.d.ts.map +1 -1
- package/dist/react.bundle.js +7 -50
- package/dist/react.bundle.js.map +3 -3
- package/package.json +1 -1
- package/src/browser/index.ts +0 -3
- package/src/browser/query_options.test.ts +9 -0
- package/src/browser/query_options.ts +15 -36
- package/src/cli/codegen_templates/readme.ts +1 -14
- package/src/cli/deploy.ts +1 -1
- package/src/cli/lib/envvars.ts +16 -1
- package/src/index.ts +1 -1
- package/src/react/client.test.tsx +0 -65
- package/src/react/client.ts +13 -129
- package/src/react/index.ts +1 -9
- package/src/server/api.ts +1 -5
- package/dist/cjs-types/react/use_query_object_options.test.d.ts +0 -5
- package/dist/cjs-types/react/use_query_object_options.test.d.ts.map +0 -1
- package/dist/cjs-types/react/use_query_result.test.d.ts +0 -5
- package/dist/cjs-types/react/use_query_result.test.d.ts.map +0 -1
- package/dist/esm-types/react/use_query_object_options.test.d.ts +0 -5
- package/dist/esm-types/react/use_query_object_options.test.d.ts.map +0 -1
- package/dist/esm-types/react/use_query_result.test.d.ts +0 -5
- package/dist/esm-types/react/use_query_result.test.d.ts.map +0 -1
- package/src/react/use_query_object_options.test.ts +0 -50
- package/src/react/use_query_result.test.ts +0 -41
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/react/client.ts"],
|
|
4
|
-
"sourcesContent": ["import { BaseConvexClient } from \"../browser/index.js\";\nimport type {\n OptimisticUpdate,\n PaginatedQueryToken,\n QueryToken,\n PaginationStatus,\n} from \"../browser/index.js\";\nimport React, { useCallback, useContext, useMemo } from \"react\";\nimport { convexToJson, Value } from \"../values/index.js\";\nimport { QueryJournal } from \"../browser/sync/protocol.js\";\nimport {\n AuthTokenFetcher,\n BaseConvexClientOptions,\n ConnectionState,\n} from \"../browser/sync/client.js\";\nimport type { UserIdentityAttributes } from \"../browser/sync/protocol.js\";\nimport { RequestForQueries, useQueries } from \"./use_queries.js\";\nimport { useSubscription } from \"./use_subscription.js\";\nimport { parseArgs } from \"../common/index.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n makeFunctionReference,\n} from \"../server/api.js\";\nimport { EmptyObject } from \"../server/registration.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n Logger,\n} from \"../browser/logging.js\";\nimport type { QueryOptions } from \"../browser/query_options.js\";\nimport { LoadMoreOfPaginatedQuery } from \"../browser/sync/pagination.js\";\nimport {\n PaginatedQueryClient,\n ExtendedTransition,\n} from \"../browser/sync/paginated_query_client.js\";\n\n// When no arguments are passed, extend subscriptions (for APIs that do this by default)\n// for this amount after the subscription would otherwise be dropped.\nconst DEFAULT_EXTEND_SUBSCRIPTION_FOR = 5_000;\n\nif (typeof React === \"undefined\") {\n throw new Error(\"Required dependency 'react' not found\");\n}\n\n// TODO Typedoc doesn't generate documentation for the comment below perhaps\n// because it's a callable interface.\n/**\n * An interface to execute a Convex mutation function on the server.\n *\n * @public\n */\nexport interface ReactMutation<Mutation extends FunctionReference<\"mutation\">> {\n /**\n * Execute the mutation on the server, returning a `Promise` of its return value.\n *\n * @param args - Arguments for the mutation to pass up to the server.\n * @returns The return value of the server-side function call.\n */\n (...args: OptionalRestArgs<Mutation>): Promise<FunctionReturnType<Mutation>>;\n\n /**\n * Define an optimistic update to apply as part of this mutation.\n *\n * This is a temporary update to the local query results to facilitate a\n * fast, interactive UI. It enables query results to update before a mutation\n * executed on the server.\n *\n * When the mutation is invoked, the optimistic update will be applied.\n *\n * Optimistic updates can also be used to temporarily remove queries from the\n * client and create loading experiences until a mutation completes and the\n * new query results are synced.\n *\n * The update will be automatically rolled back when the mutation is fully\n * completed and queries have been updated.\n *\n * @param optimisticUpdate - The optimistic update to apply.\n * @returns A new `ReactMutation` with the update configured.\n *\n * @public\n */\n withOptimisticUpdate<T extends OptimisticUpdate<FunctionArgs<Mutation>>>(\n optimisticUpdate: T &\n (ReturnType<T> extends Promise<any>\n ? \"Optimistic update handlers must be synchronous\"\n : {}),\n ): ReactMutation<Mutation>;\n}\n\n// Exported only for testing.\nexport function createMutation(\n mutationReference: FunctionReference<\"mutation\">,\n client: ConvexReactClient,\n update?: OptimisticUpdate<any>,\n): ReactMutation<any> {\n function mutation(args?: Record<string, Value>): Promise<unknown> {\n assertNotAccidentalArgument(args);\n\n return client.mutation(mutationReference, args, {\n optimisticUpdate: update,\n });\n }\n mutation.withOptimisticUpdate = function withOptimisticUpdate(\n optimisticUpdate: OptimisticUpdate<any>,\n ): ReactMutation<any> {\n if (update !== undefined) {\n throw new Error(\n `Already specified optimistic update for mutation ${getFunctionName(\n mutationReference,\n )}`,\n );\n }\n return createMutation(mutationReference, client, optimisticUpdate);\n };\n return mutation as ReactMutation<any>;\n}\n\n/**\n * An interface to execute a Convex action on the server.\n *\n * @public\n */\nexport interface ReactAction<Action extends FunctionReference<\"action\">> {\n /**\n * Execute the function on the server, returning a `Promise` of its return value.\n *\n * @param args - Arguments for the function to pass up to the server.\n * @returns The return value of the server-side function call.\n * @public\n */\n (...args: OptionalRestArgs<Action>): Promise<FunctionReturnType<Action>>;\n}\n\nfunction createAction(\n actionReference: FunctionReference<\"action\">,\n client: ConvexReactClient,\n): ReactAction<any> {\n return function (args?: Record<string, Value>): Promise<unknown> {\n return client.action(actionReference, args);\n } as ReactAction<any>;\n}\n\n// Watches should be stateless: in QueriesObserver we create a watch just to get\n// the current value.\n/**\n * A watch on the output of a Convex query function.\n *\n * @public\n */\nexport interface Watch<T> {\n /**\n * Initiate a watch on the output of a query.\n *\n * This will subscribe to this query and call\n * the callback whenever the query result changes.\n *\n * **Important: If the client is already subscribed to this query with the\n * same arguments this callback will not be invoked until the query result is\n * updated.** To get the current, local result call\n * {@link react.Watch.localQueryResult}.\n *\n * @param callback - Function that is called whenever the query result changes.\n * @returns - A function that disposes of the subscription.\n */\n onUpdate(callback: () => void): () => void;\n\n /**\n * Get the current result of a query.\n *\n * This will only return a result if we're already subscribed to the query\n * and have received a result from the server or the query value has been set\n * optimistically.\n *\n * @returns The result of the query or `undefined` if it isn't known.\n * @throws An error if the query encountered an error on the server.\n */\n localQueryResult(): T | undefined;\n\n /**\n * @internal\n */\n localQueryLogs(): string[] | undefined;\n\n /**\n * Get the current {@link browser.QueryJournal} for this query.\n *\n * If we have not yet received a result for this query, this will be `undefined`.\n */\n journal(): QueryJournal | undefined;\n}\n\n/**\n * A watch on the output of a paginated Convex query function.\n *\n * @public\n */\nexport interface PaginatedWatch<T> {\n /**\n * Initiate a watch on the output of a paginated query.\n *\n * This will subscribe to this query and call\n * the callback whenever the query result changes.\n *\n * @param callback - Function that is called whenever the query result changes.\n * @returns - A function that disposes of the subscription.\n */\n onUpdate(callback: () => void): () => void;\n\n /**\n * Get the current result of a paginated query.\n *\n * @returns The current results, status, and loadMore function, or `undefined` if not loaded.\n */\n localQueryResult():\n | {\n results: T[];\n status: PaginationStatus;\n loadMore: LoadMoreOfPaginatedQuery;\n }\n | undefined;\n}\n\n/**\n * Options for {@link ConvexReactClient.watchQuery}.\n *\n * @public\n */\nexport interface WatchQueryOptions {\n /**\n * An (optional) journal produced from a previous execution of this query\n * function.\n *\n * If there is an existing subscription to a query function with the same\n * name and arguments, this journal will have no effect.\n */\n journal?: QueryJournal;\n\n /**\n * @internal\n */\n componentPath?: string;\n}\n\n/**\n * Options for {@link ConvexReactClient.watchPaginatedQuery}.\n *\n * @internal\n */\nexport interface WatchPaginatedQueryOptions {\n /**\n * The initial number of items to load.\n */\n initialNumItems: number;\n\n // We may be able to remove this in the future, but to preserve the existing behavior of\n // usePaginatedQuery() it's still here.\n id: number;\n\n /**\n * @internal\n */\n componentPath?: string;\n}\n\n/**\n * Options for {@link ConvexReactClient.mutation}.\n *\n * @public\n */\nexport interface MutationOptions<Args extends Record<string, Value>> {\n /**\n * An optimistic update to apply along with this mutation.\n *\n * An optimistic update locally updates queries while a mutation is pending.\n * Once the mutation completes, the update will be rolled back.\n */\n optimisticUpdate?: OptimisticUpdate<Args> | undefined;\n}\n\n/**\n * Options for {@link ConvexReactClient}.\n *\n * @public\n */\nexport interface ConvexReactClientOptions extends BaseConvexClientOptions {}\n\n/**\n * A Convex client for use within React.\n *\n * This loads reactive queries and executes mutations over a WebSocket.\n *\n * @public\n */\nexport class ConvexReactClient {\n private address: string;\n private cachedSync?: BaseConvexClient | undefined;\n private cachedPaginatedQueryClient?: PaginatedQueryClient | undefined;\n private listeners: Map<QueryToken | PaginatedQueryToken, Set<() => void>>;\n private options: ConvexReactClientOptions;\n // \"closed\" means this client is done, not just that the underlying WS connection is closed.\n private closed = false;\n private _logger: Logger;\n\n private adminAuth?: string;\n private fakeUserIdentity?: UserIdentityAttributes | undefined;\n\n /**\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - See {@link ConvexReactClientOptions} for a full description.\n */\n constructor(address: string, options?: ConvexReactClientOptions) {\n // Validate address immediately since validation by the lazily-instantiated\n // internal client does not occur synchronously.\n if (address === undefined) {\n throw new Error(\n \"No address provided to ConvexReactClient.\\n\" +\n \"If trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\\n\" +\n \"If running locally, make sure to run `convex dev` and ensure the .env.local file is populated.\",\n );\n }\n if (typeof address !== \"string\") {\n throw new Error(\n `ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof address} instead.`,\n );\n }\n if (!address.includes(\"://\")) {\n throw new Error(\"Provided address was not an absolute URL.\");\n }\n this.address = address;\n this.listeners = new Map();\n this._logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: options?.verbose ?? false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: options?.verbose ?? false });\n this.options = { ...options, logger: this._logger };\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Lazily instantiate the `BaseConvexClient` so we don't create the WebSocket\n * when server-side rendering.\n *\n * @internal\n */\n get sync() {\n if (this.closed) {\n throw new Error(\"ConvexReactClient has already been closed.\");\n }\n if (this.cachedSync) {\n return this.cachedSync;\n }\n // BaseConvexClient and paginated query client are always created together.\n this.cachedSync = new BaseConvexClient(\n this.address,\n () => {}, // Use the PaginatedQueryClient's transition instead.\n this.options,\n );\n if (this.adminAuth) {\n this.cachedSync.setAdminAuth(this.adminAuth, this.fakeUserIdentity);\n }\n this.cachedPaginatedQueryClient = new PaginatedQueryClient(\n this.cachedSync,\n (transition) => this.handleTransition(transition),\n );\n return this.cachedSync;\n }\n\n /**\n * Lazily instantiate the `PaginatedQueryClient` so we don't create it\n * when server-side rendering.\n *\n * @internal\n */\n get paginatedQueryClient() {\n // access sync to instantiate the clients\n this.sync;\n if (this.cachedPaginatedQueryClient) {\n return this.cachedPaginatedQueryClient;\n }\n throw new Error(\"Should already be instantiated\");\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT-encoded OpenID Connect Identity Token\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n ) {\n if (typeof fetchToken === \"string\") {\n throw new Error(\n \"Passing a string to ConvexReactClient.setAuth is no longer supported, \" +\n \"please upgrade to passing in an async function to handle reauthentication.\",\n );\n }\n this.sync.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n );\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.sync.clearAuth();\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n this.adminAuth = token;\n this.fakeUserIdentity = identity;\n if (this.closed) {\n throw new Error(\"ConvexReactClient has already been closed.\");\n }\n if (this.cachedSync) {\n this.sync.setAdminAuth(token, identity);\n }\n }\n\n /**\n * Construct a new {@link Watch} on a Convex query function.\n *\n * **Most application code should not call this method directly. Instead use\n * the {@link useQuery} hook.**\n *\n * The act of creating a watch does nothing, a Watch is stateless.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link WatchQueryOptions} options object for this query.\n *\n * @returns The {@link Watch} object.\n */\n watchQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...argsAndOptions: ArgsAndOptions<Query, WatchQueryOptions>\n ): Watch<FunctionReturnType<Query>> {\n const [args, options] = argsAndOptions;\n const name = getFunctionName(query);\n\n return {\n onUpdate: (callback) => {\n const { queryToken, unsubscribe } = this.sync.subscribe(\n name as string,\n args,\n options,\n );\n\n const currentListeners = this.listeners.get(queryToken);\n if (currentListeners !== undefined) {\n currentListeners.add(callback);\n } else {\n this.listeners.set(queryToken, new Set([callback]));\n }\n\n return () => {\n if (this.closed) {\n return;\n }\n\n const currentListeners = this.listeners.get(queryToken)!;\n currentListeners.delete(callback);\n if (currentListeners.size === 0) {\n this.listeners.delete(queryToken);\n }\n unsubscribe();\n };\n },\n\n localQueryResult: () => {\n // Use the cached client because we can't have a query result if we don't\n // even have a client yet!\n if (this.cachedSync) {\n return this.cachedSync.localQueryResult(name, args);\n }\n return undefined;\n },\n\n localQueryLogs: () => {\n if (this.cachedSync) {\n return this.cachedSync.localQueryLogs(name, args);\n }\n return undefined;\n },\n\n journal: () => {\n if (this.cachedSync) {\n return this.cachedSync.queryJournal(name, args);\n }\n return undefined;\n },\n };\n }\n\n // Let's try out a queryOptions-style API.\n // This method is similar to the React Query API `queryClient.prefetchQuery()`.\n // In the future an ensureQueryData(): Promise<Data> method could exist.\n /**\n * Indicates likely future interest in a query subscription.\n *\n * The implementation currently immediately subscribes to a query. In the future this method\n * may prioritize some queries over others, fetch the query result without subscribing, or\n * do nothing in slow network connections or high load scenarios.\n *\n * To use this in a React component, call useQuery() and ignore the return value.\n *\n * @param queryOptions - A query (function reference from an api object) and its args, plus\n * an optional extendSubscriptionFor for how long to subscribe to the query.\n */\n prewarmQuery<Query extends FunctionReference<\"query\">>(\n queryOptions: QueryOptions<Query> & { extendSubscriptionFor?: number },\n ) {\n const extendSubscriptionFor =\n queryOptions.extendSubscriptionFor ?? DEFAULT_EXTEND_SUBSCRIPTION_FOR;\n const watch = this.watchQuery(queryOptions.query, queryOptions.args || {});\n const unsubscribe = watch.onUpdate(() => {});\n setTimeout(unsubscribe, extendSubscriptionFor);\n }\n\n /**\n * Construct a new {@link PaginatedWatch} on a Convex paginated query function.\n *\n * **Most application code should not call this method directly. Instead use\n * the {@link usePaginatedQuery} hook.**\n *\n * The act of creating a watch does nothing, a Watch is stateless.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link WatchPaginatedQueryOptions} options object for this query.\n *\n * @returns The {@link PaginatedWatch} object.\n *\n * @internal\n */\n watchPaginatedQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: Query[\"_args\"],\n options: WatchPaginatedQueryOptions,\n ): PaginatedWatch<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n\n return {\n onUpdate: (callback) => {\n const { paginatedQueryToken, unsubscribe } =\n this.paginatedQueryClient.subscribe(name, args || {}, options);\n\n const currentListeners = this.listeners.get(paginatedQueryToken);\n if (currentListeners !== undefined) {\n currentListeners.add(callback);\n } else {\n this.listeners.set(paginatedQueryToken, new Set([callback]));\n }\n\n return () => {\n if (this.closed) {\n return;\n }\n\n const currentListeners = this.listeners.get(paginatedQueryToken)!;\n currentListeners.delete(callback);\n if (currentListeners.size === 0) {\n this.listeners.delete(paginatedQueryToken);\n }\n unsubscribe();\n };\n },\n\n localQueryResult: () => {\n // Use our new paginated query client\n return this.paginatedQueryClient.localQueryResult(name, args, options);\n },\n };\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n ...argsAndOptions: ArgsAndOptions<\n Mutation,\n MutationOptions<FunctionArgs<Mutation>>\n >\n ): Promise<FunctionReturnType<Mutation>> {\n const [args, options] = argsAndOptions;\n const name = getFunctionName(mutation);\n return this.sync.mutation(name, args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n action<Action extends FunctionReference<\"action\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const name = getFunctionName(action);\n return this.sync.action(name, ...args);\n }\n\n /**\n * Fetch a query result once.\n *\n * **Most application code should subscribe to queries instead, using\n * the {@link useQuery} hook.**\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n query<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const watch = this.watchQuery(query, ...args);\n const existingResult = watch.localQueryResult();\n if (existingResult !== undefined) {\n return Promise.resolve(existingResult);\n }\n return new Promise((resolve, reject) => {\n const unsubscribe = watch.onUpdate(() => {\n unsubscribe();\n try {\n resolve(watch.localQueryResult());\n } catch (e) {\n reject(e);\n }\n });\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n return this.sync.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n * ConnectionState may also *lose* properties in future versions as we figure\n * out what information is most useful. As such this API is considered unstable.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n return this.sync.subscribeToConnectionState(cb);\n }\n\n /**\n * Get the logger for this client.\n *\n * @returns The {@link Logger} for this client.\n */\n get logger(): Logger {\n return this._logger;\n }\n\n /**\n * Close any network handles associated with this client and stop all subscriptions.\n *\n * Call this method when you're done with a {@link ConvexReactClient} to\n * dispose of its sockets and resources.\n *\n * @returns A `Promise` fulfilled when the connection has been completely closed.\n */\n async close(): Promise<void> {\n this.closed = true;\n // Prevent outstanding React batched updates from invoking listeners.\n this.listeners = new Map();\n if (this.cachedPaginatedQueryClient) {\n this.cachedPaginatedQueryClient = undefined;\n }\n if (this.cachedSync) {\n const sync = this.cachedSync;\n this.cachedSync = undefined;\n await sync.close();\n }\n }\n\n /**\n * Handle transitions from both base client and paginated client.\n * This ensures all transitions are processed synchronously and in order.\n */\n private handleTransition(transition: ExtendedTransition) {\n const simple = transition.queries.map((q) => q.token);\n const paginated = transition.paginatedQueries.map((q) => q.token);\n this.transition([...simple, ...paginated]);\n }\n\n private transition(updatedQueries: (QueryToken | PaginatedQueryToken)[]) {\n for (const queryToken of updatedQueries) {\n const callbacks = this.listeners.get(queryToken);\n if (callbacks) {\n for (const callback of callbacks) {\n callback();\n }\n }\n }\n }\n}\n\nconst ConvexContext = React.createContext<ConvexReactClient>(\n undefined as unknown as ConvexReactClient, // in the future this will be a mocked client for testing\n);\n\n/**\n * Get the {@link ConvexReactClient} within a React component.\n *\n * This relies on the {@link ConvexProvider} being above in the React component tree.\n *\n * @returns The active {@link ConvexReactClient} object, or `undefined`.\n *\n * @public\n */\nexport function useConvex(): ConvexReactClient {\n return useContext(ConvexContext);\n}\n\n/**\n * Provides an active Convex {@link ConvexReactClient} to descendants of this component.\n *\n * Wrap your app in this component to use Convex hooks `useQuery`,\n * `useMutation`, and `useConvex`.\n *\n * @param props - an object with a `client` property that refers to a {@link ConvexReactClient}.\n *\n * @public\n */\nexport const ConvexProvider: React.FC<{\n client: ConvexReactClient;\n children?: React.ReactNode;\n}> = ({ client, children }) => {\n return React.createElement(\n ConvexContext.Provider,\n { value: client },\n children,\n );\n};\n\nexport type OptionalRestArgsOrSkip<FuncRef extends FunctionReference<any>> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject | \"skip\"]\n : [args: FuncRef[\"_args\"] | \"skip\"];\n\n/**\n * Result returned by object-form {@link useQuery}.\n *\n * @public\n */\nexport type UseQueryResult<QueryResult> =\n | {\n data: QueryResult;\n error: undefined;\n status: \"success\";\n }\n | {\n data: undefined;\n error: Error;\n status: \"error\";\n }\n | {\n data: undefined;\n error: undefined;\n status: \"pending\";\n };\n\ntype UseQueryOptions<Query extends FunctionReference<\"query\">> = {\n query: Query;\n args: FunctionArgs<Query> | \"skip\";\n throwOnError?: boolean;\n};\n\n/**\n * Load a reactive query within a React component.\n *\n * This React hook subscribes to a Convex query and causes a rerender whenever\n * the query result changes. The subscription is managed automatically --\n * it starts when the component mounts and stops when it unmounts.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useQuery } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function TaskList() {\n * // Reactively loads tasks, re-renders when data changes:\n * const tasks = useQuery(api.tasks.list, { completed: false });\n *\n * // Returns `undefined` while loading:\n * if (tasks === undefined) return <div>Loading...</div>;\n *\n * return tasks.map((task) => <div key={task._id}>{task.text}</div>);\n * }\n *\n * // Pass \"skip\" to conditionally disable the query:\n * function MaybeProfile({ userId }: { userId?: Id<\"users\"> }) {\n * const profile = useQuery(\n * api.users.get,\n * userId ? { userId } : \"skip\",\n * );\n * // ...\n * }\n * ```\n *\n * @param query - a {@link server.FunctionReference} for the public query to run\n * like `api.dir1.dir2.filename.func`.\n * @param args - The arguments to the query function or the string `\"skip\"` if the\n * query should not be loaded.\n * @returns the result of the query. Returns `undefined` while loading.\n *\n * @see https://docs.convex.dev/client/react#fetching-data\n * @public\n */\nexport function useQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgsOrSkip<Query>\n): Query[\"_returnType\"] | undefined;\n\n/**\n * Load a reactive query within a React component using an options object.\n *\n * This is an alternative form of {@link useQuery} that accepts a single\n * {@link UseQueryOptions} object instead of positional arguments.\n * Errors are returned in the result object unless `throwOnError` is set.\n *\n * @example\n * ```tsx\n * import { useQuery } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function TaskList() {\n * const state = useQuery({ query: api.tasks.list, args: { completed: false } });\n *\n * if (state.status === \"pending\") return <div>Loading...</div>;\n * if (state.status === \"error\") return <div>Error: {state.error.message}</div>;\n * return state.data.map((task) => <div key={task._id}>{task.text}</div>);\n * }\n * ```\n *\n * @param options - Query options. Pass `args: \"skip\"` to disable the query.\n * @returns the current query state as a {@link UseQueryResult} object.\n *\n * @see https://docs.convex.dev/client/react#fetching-data\n * @public\n */\nexport function useQuery<Query extends FunctionReference<\"query\">>(\n options: UseQueryOptions<Query>,\n): UseQueryResult<Query[\"_returnType\"]>;\n\nexport function useQuery<Query extends FunctionReference<\"query\">>(\n queryOrOptions: Query | UseQueryOptions<Query>,\n ...args: OptionalRestArgsOrSkip<Query>\n): Query[\"_returnType\"] | undefined | UseQueryResult<Query[\"_returnType\"]> {\n const isObjectOptions =\n typeof queryOrOptions === \"object\" &&\n queryOrOptions !== null &&\n \"query\" in queryOrOptions;\n const throwOnError = isObjectOptions\n ? (queryOrOptions.throwOnError ?? false)\n : true;\n\n let queryReference: Query | undefined;\n let argsObject: Record<string, Value> = {};\n\n if (isObjectOptions) {\n const query = queryOrOptions.query;\n queryReference =\n typeof query === \"string\"\n ? (makeFunctionReference<\"query\", any, any>(query) as Query)\n : query;\n if (queryOrOptions.args !== \"skip\") {\n argsObject = parseArgs(queryOrOptions.args as Record<string, Value>);\n }\n } else {\n const query = queryOrOptions;\n queryReference =\n typeof query === \"string\"\n ? (makeFunctionReference<\"query\", any, any>(query) as Query)\n : query;\n argsObject = args[0] === \"skip\" ? {} : parseArgs(args[0] as Query[\"_args\"]);\n }\n\n const queryName = queryReference\n ? getFunctionName(queryReference)\n : undefined;\n const skip =\n (isObjectOptions && queryOrOptions.args === \"skip\") ||\n (!isObjectOptions && args[0] === \"skip\");\n\n const queries = useMemo(\n () =>\n skip || !queryReference\n ? ({} as RequestForQueries)\n : { query: { query: queryReference, args: argsObject } },\n // Stringify args so args that are semantically the same don't trigger a\n // rerender. Saves developers from adding `useMemo` on every args usage.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(convexToJson(argsObject)), queryName, skip],\n );\n\n const results = useQueries(queries);\n const result = results[\"query\"];\n\n if (isObjectOptions) {\n if (result instanceof Error) {\n if (throwOnError) {\n throw result;\n }\n return {\n data: undefined,\n error: result,\n status: \"error\",\n };\n }\n\n if (result === undefined) {\n return {\n data: undefined,\n error: undefined,\n status: \"pending\",\n };\n }\n\n return {\n data: result,\n error: undefined,\n status: \"success\",\n };\n }\n\n if (result instanceof Error) {\n throw result;\n }\n return result;\n}\n\n/**\n * Construct a new {@link ReactMutation}.\n *\n * Returns a function that you can call to execute a Convex mutation. The\n * returned function is stable across renders (same reference identity), so\n * it can be safely used in dependency arrays and memoization.\n *\n * Mutations can optionally be configured with\n * [optimistic updates](https://docs.convex.dev/client/react/optimistic-updates)\n * for instant UI feedback.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useMutation } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function CreateTask() {\n * const createTask = useMutation(api.tasks.create);\n *\n * const handleClick = async () => {\n * await createTask({ text: \"New task\" });\n * };\n *\n * return <button onClick={handleClick}>Add Task</button>;\n * }\n * ```\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run like `api.dir1.dir2.filename.func`.\n * @returns The {@link ReactMutation} object with that name.\n *\n * @see https://docs.convex.dev/client/react#editing-data\n * @public\n */\nexport function useMutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n): ReactMutation<Mutation> {\n const mutationReference =\n typeof mutation === \"string\"\n ? makeFunctionReference<\"mutation\", any, any>(mutation)\n : mutation;\n\n const convex = useContext(ConvexContext);\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useMutation` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n return useMemo(\n () => createMutation(mutationReference, convex),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [convex, getFunctionName(mutationReference)],\n );\n}\n\n/**\n * Construct a new {@link ReactAction}.\n *\n * Returns a function that you can call to execute a Convex action. Actions\n * can call third-party APIs and perform side effects. The returned function\n * is stable across renders (same reference identity).\n *\n * **Error handling:** Actions can fail (e.g., if an external API is down).\n * Always wrap action calls in try/catch or handle the rejected promise.\n *\n * **Note:** In most cases, calling an action directly from a client is an\n * anti-pattern. Prefer having the client call a mutation that captures the\n * user's intent (by writing to the database) and then schedules the action\n * via `ctx.scheduler.runAfter`. This ensures the intent is durably recorded\n * even if the client disconnects.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useAction } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function GenerateSummary() {\n * const generate = useAction(api.ai.generateSummary);\n *\n * const handleClick = async () => {\n * try {\n * const summary = await generate({ text: \"Some long text...\" });\n * console.log(summary);\n * } catch (error) {\n * console.error(\"Action failed:\", error);\n * }\n * };\n *\n * return <button onClick={handleClick}>Generate</button>;\n * }\n * ```\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run like `api.dir1.dir2.filename.func`.\n * @returns The {@link ReactAction} object with that name.\n *\n * @see https://docs.convex.dev/functions/actions#calling-actions-from-clients\n * @public\n */\nexport function useAction<Action extends FunctionReference<\"action\">>(\n action: Action,\n): ReactAction<Action> {\n const convex = useContext(ConvexContext);\n const actionReference =\n typeof action === \"string\"\n ? makeFunctionReference<\"action\", any, any>(action)\n : action;\n\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useAction` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n return useMemo(\n () => createAction(actionReference, convex),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [convex, getFunctionName(actionReference)],\n );\n}\n\n/**\n * React hook to get the current {@link ConnectionState} and subscribe to changes.\n *\n * This hook returns the current connection state and automatically rerenders\n * when any part of the connection state changes (e.g., when going online/offline,\n * when requests start/complete, etc.).\n *\n * The shape of ConnectionState may change in the future which may cause this\n * hook to rerender more frequently.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @returns The current {@link ConnectionState} with the Convex backend.\n *\n * @public\n */\nexport function useConvexConnectionState(): ConnectionState {\n const convex = useContext(ConvexContext);\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useConvexConnectionState` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n\n const getCurrentValue = useCallback(() => {\n return convex.connectionState();\n }, [convex]);\n\n const subscribe = useCallback(\n (callback: () => void) => {\n return convex.subscribeToConnectionState(() => {\n callback();\n });\n },\n [convex],\n );\n\n return useSubscription({ getCurrentValue, subscribe });\n}\n\n// When a function is called with a single argument that looks like a\n// React SyntheticEvent it was likely called as an event handler.\nfunction assertNotAccidentalArgument(value: any) {\n // these are properties of a React.SyntheticEvent\n // https://reactjs.org/docs/events.html\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"bubbles\" in value &&\n \"persist\" in value &&\n \"isDefaultPrevented\" in value\n ) {\n throw new Error(\n `Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like \\`const handler = () => myMutation();\\` and using \\`handler\\` in the event handler.`,\n );\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;AAAA,SAAS,wBAAwB;AAOjC,OAAO,SAAS,aAAa,YAAY,eAAe;AACxD,SAAS,oBAA2B;AAQpC,SAA4B,kBAAkB;AAC9C,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B;AAAA,EAME;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAGP;AAAA,EACE;AAAA,OAEK;AAIP,MAAM,kCAAkC;AAExC,IAAI,OAAO,UAAU,aAAa;AAChC,QAAM,IAAI,MAAM,uCAAuC;AACzD;AAgDO,gBAAS,eACd,mBACA,QACA,QACoB;AACpB,WAAS,SAAS,MAAgD;AAChE,gCAA4B,IAAI;AAEhC,WAAO,OAAO,SAAS,mBAAmB,MAAM;AAAA,MAC9C,kBAAkB;AAAA,IACpB,CAAC;AAAA,EACH;AACA,WAAS,uBAAuB,SAAS,qBACvC,kBACoB;AACpB,QAAI,WAAW,QAAW;AACxB,YAAM,IAAI;AAAA,QACR,oDAAoD;AAAA,UAClD;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AACA,WAAO,eAAe,mBAAmB,QAAQ,gBAAgB;AAAA,EACnE;AACA,SAAO;AACT;AAkBA,SAAS,aACP,iBACA,QACkB;AAClB,SAAO,SAAU,MAAgD;AAC/D,WAAO,OAAO,OAAO,iBAAiB,IAAI;AAAA,EAC5C;AACF;AAyJO,aAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkB7B,YAAY,SAAiB,SAAoC;AAjBjE,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AAER;AAAA,wBAAQ,UAAS;AACjB,wBAAQ;AAER,wBAAQ;AACR,wBAAQ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,oBAAmB,KAAK,UAAU,IAAI,UAAU;AACtD,UAAAA,kBAAiB,OAAO,QAAQ;AAChC,cAAIA,kBAAiB,SAAS,GAAG;AAC/B,iBAAK,UAAU,OAAO,UAAU;AAAA,UAClC;AACA,sBAAY;AAAA,QACd;AAAA,MACF;AAAA,MAEA,kBAAkB,MAAM;AAGtB,YAAI,KAAK,YAAY;AACnB,iBAAO,KAAK,WAAW,iBAAiB,MAAM,IAAI;AAAA,QACpD;AACA,eAAO;AAAA,MACT;AAAA,MAEA,gBAAgB,MAAM;AACpB,YAAI,KAAK,YAAY;AACnB,iBAAO,KAAK,WAAW,eAAe,MAAM,IAAI;AAAA,QAClD;AACA,eAAO;AAAA,MACT;AAAA,MAEA,SAAS,MAAM;AACb,YAAI,KAAK,YAAY;AACnB,iBAAO,KAAK,WAAW,aAAa,MAAM,IAAI;AAAA,QAChD;AACA,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,aACE,
|
|
4
|
+
"sourcesContent": ["import { BaseConvexClient } from \"../browser/index.js\";\nimport type {\n OptimisticUpdate,\n PaginatedQueryToken,\n QueryToken,\n PaginationStatus,\n} from \"../browser/index.js\";\nimport React, { useCallback, useContext, useMemo } from \"react\";\nimport { convexToJson, Value } from \"../values/index.js\";\nimport { QueryJournal } from \"../browser/sync/protocol.js\";\nimport {\n AuthTokenFetcher,\n BaseConvexClientOptions,\n ConnectionState,\n} from \"../browser/sync/client.js\";\nimport type { UserIdentityAttributes } from \"../browser/sync/protocol.js\";\nimport { RequestForQueries, useQueries } from \"./use_queries.js\";\nimport { useSubscription } from \"./use_subscription.js\";\nimport { parseArgs } from \"../common/index.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n makeFunctionReference,\n} from \"../server/api.js\";\nimport { EmptyObject } from \"../server/registration.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n Logger,\n} from \"../browser/logging.js\";\nimport { ConvexQueryOptions } from \"../browser/query_options.js\";\nimport { LoadMoreOfPaginatedQuery } from \"../browser/sync/pagination.js\";\nimport {\n PaginatedQueryClient,\n ExtendedTransition,\n} from \"../browser/sync/paginated_query_client.js\";\n\n// When no arguments are passed, extend subscriptions (for APIs that do this by default)\n// for this amount after the subscription would otherwise be dropped.\nconst DEFAULT_EXTEND_SUBSCRIPTION_FOR = 5_000;\n\nif (typeof React === \"undefined\") {\n throw new Error(\"Required dependency 'react' not found\");\n}\n\n// TODO Typedoc doesn't generate documentation for the comment below perhaps\n// because it's a callable interface.\n/**\n * An interface to execute a Convex mutation function on the server.\n *\n * @public\n */\nexport interface ReactMutation<Mutation extends FunctionReference<\"mutation\">> {\n /**\n * Execute the mutation on the server, returning a `Promise` of its return value.\n *\n * @param args - Arguments for the mutation to pass up to the server.\n * @returns The return value of the server-side function call.\n */\n (...args: OptionalRestArgs<Mutation>): Promise<FunctionReturnType<Mutation>>;\n\n /**\n * Define an optimistic update to apply as part of this mutation.\n *\n * This is a temporary update to the local query results to facilitate a\n * fast, interactive UI. It enables query results to update before a mutation\n * executed on the server.\n *\n * When the mutation is invoked, the optimistic update will be applied.\n *\n * Optimistic updates can also be used to temporarily remove queries from the\n * client and create loading experiences until a mutation completes and the\n * new query results are synced.\n *\n * The update will be automatically rolled back when the mutation is fully\n * completed and queries have been updated.\n *\n * @param optimisticUpdate - The optimistic update to apply.\n * @returns A new `ReactMutation` with the update configured.\n *\n * @public\n */\n withOptimisticUpdate<T extends OptimisticUpdate<FunctionArgs<Mutation>>>(\n optimisticUpdate: T &\n (ReturnType<T> extends Promise<any>\n ? \"Optimistic update handlers must be synchronous\"\n : {}),\n ): ReactMutation<Mutation>;\n}\n\n// Exported only for testing.\nexport function createMutation(\n mutationReference: FunctionReference<\"mutation\">,\n client: ConvexReactClient,\n update?: OptimisticUpdate<any>,\n): ReactMutation<any> {\n function mutation(args?: Record<string, Value>): Promise<unknown> {\n assertNotAccidentalArgument(args);\n\n return client.mutation(mutationReference, args, {\n optimisticUpdate: update,\n });\n }\n mutation.withOptimisticUpdate = function withOptimisticUpdate(\n optimisticUpdate: OptimisticUpdate<any>,\n ): ReactMutation<any> {\n if (update !== undefined) {\n throw new Error(\n `Already specified optimistic update for mutation ${getFunctionName(\n mutationReference,\n )}`,\n );\n }\n return createMutation(mutationReference, client, optimisticUpdate);\n };\n return mutation as ReactMutation<any>;\n}\n\n/**\n * An interface to execute a Convex action on the server.\n *\n * @public\n */\nexport interface ReactAction<Action extends FunctionReference<\"action\">> {\n /**\n * Execute the function on the server, returning a `Promise` of its return value.\n *\n * @param args - Arguments for the function to pass up to the server.\n * @returns The return value of the server-side function call.\n * @public\n */\n (...args: OptionalRestArgs<Action>): Promise<FunctionReturnType<Action>>;\n}\n\nfunction createAction(\n actionReference: FunctionReference<\"action\">,\n client: ConvexReactClient,\n): ReactAction<any> {\n return function (args?: Record<string, Value>): Promise<unknown> {\n return client.action(actionReference, args);\n } as ReactAction<any>;\n}\n\n// Watches should be stateless: in QueriesObserver we create a watch just to get\n// the current value.\n/**\n * A watch on the output of a Convex query function.\n *\n * @public\n */\nexport interface Watch<T> {\n /**\n * Initiate a watch on the output of a query.\n *\n * This will subscribe to this query and call\n * the callback whenever the query result changes.\n *\n * **Important: If the client is already subscribed to this query with the\n * same arguments this callback will not be invoked until the query result is\n * updated.** To get the current, local result call\n * {@link react.Watch.localQueryResult}.\n *\n * @param callback - Function that is called whenever the query result changes.\n * @returns - A function that disposes of the subscription.\n */\n onUpdate(callback: () => void): () => void;\n\n /**\n * Get the current result of a query.\n *\n * This will only return a result if we're already subscribed to the query\n * and have received a result from the server or the query value has been set\n * optimistically.\n *\n * @returns The result of the query or `undefined` if it isn't known.\n * @throws An error if the query encountered an error on the server.\n */\n localQueryResult(): T | undefined;\n\n /**\n * @internal\n */\n localQueryLogs(): string[] | undefined;\n\n /**\n * Get the current {@link browser.QueryJournal} for this query.\n *\n * If we have not yet received a result for this query, this will be `undefined`.\n */\n journal(): QueryJournal | undefined;\n}\n\n/**\n * A watch on the output of a paginated Convex query function.\n *\n * @public\n */\nexport interface PaginatedWatch<T> {\n /**\n * Initiate a watch on the output of a paginated query.\n *\n * This will subscribe to this query and call\n * the callback whenever the query result changes.\n *\n * @param callback - Function that is called whenever the query result changes.\n * @returns - A function that disposes of the subscription.\n */\n onUpdate(callback: () => void): () => void;\n\n /**\n * Get the current result of a paginated query.\n *\n * @returns The current results, status, and loadMore function, or `undefined` if not loaded.\n */\n localQueryResult():\n | {\n results: T[];\n status: PaginationStatus;\n loadMore: LoadMoreOfPaginatedQuery;\n }\n | undefined;\n}\n\n/**\n * Options for {@link ConvexReactClient.watchQuery}.\n *\n * @public\n */\nexport interface WatchQueryOptions {\n /**\n * An (optional) journal produced from a previous execution of this query\n * function.\n *\n * If there is an existing subscription to a query function with the same\n * name and arguments, this journal will have no effect.\n */\n journal?: QueryJournal;\n\n /**\n * @internal\n */\n componentPath?: string;\n}\n\n/**\n * Options for {@link ConvexReactClient.watchPaginatedQuery}.\n *\n * @internal\n */\nexport interface WatchPaginatedQueryOptions {\n /**\n * The initial number of items to load.\n */\n initialNumItems: number;\n\n // We may be able to remove this in the future, but to preserve the existing behavior of\n // usePaginatedQuery() it's still here.\n id: number;\n\n /**\n * @internal\n */\n componentPath?: string;\n}\n\n/**\n * Options for {@link ConvexReactClient.mutation}.\n *\n * @public\n */\nexport interface MutationOptions<Args extends Record<string, Value>> {\n /**\n * An optimistic update to apply along with this mutation.\n *\n * An optimistic update locally updates queries while a mutation is pending.\n * Once the mutation completes, the update will be rolled back.\n */\n optimisticUpdate?: OptimisticUpdate<Args> | undefined;\n}\n\n/**\n * Options for {@link ConvexReactClient}.\n *\n * @public\n */\nexport interface ConvexReactClientOptions extends BaseConvexClientOptions {}\n\n/**\n * A Convex client for use within React.\n *\n * This loads reactive queries and executes mutations over a WebSocket.\n *\n * @public\n */\nexport class ConvexReactClient {\n private address: string;\n private cachedSync?: BaseConvexClient | undefined;\n private cachedPaginatedQueryClient?: PaginatedQueryClient | undefined;\n private listeners: Map<QueryToken | PaginatedQueryToken, Set<() => void>>;\n private options: ConvexReactClientOptions;\n // \"closed\" means this client is done, not just that the underlying WS connection is closed.\n private closed = false;\n private _logger: Logger;\n\n private adminAuth?: string;\n private fakeUserIdentity?: UserIdentityAttributes | undefined;\n\n /**\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - See {@link ConvexReactClientOptions} for a full description.\n */\n constructor(address: string, options?: ConvexReactClientOptions) {\n // Validate address immediately since validation by the lazily-instantiated\n // internal client does not occur synchronously.\n if (address === undefined) {\n throw new Error(\n \"No address provided to ConvexReactClient.\\n\" +\n \"If trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\\n\" +\n \"If running locally, make sure to run `convex dev` and ensure the .env.local file is populated.\",\n );\n }\n if (typeof address !== \"string\") {\n throw new Error(\n `ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof address} instead.`,\n );\n }\n if (!address.includes(\"://\")) {\n throw new Error(\"Provided address was not an absolute URL.\");\n }\n this.address = address;\n this.listeners = new Map();\n this._logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: options?.verbose ?? false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: options?.verbose ?? false });\n this.options = { ...options, logger: this._logger };\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Lazily instantiate the `BaseConvexClient` so we don't create the WebSocket\n * when server-side rendering.\n *\n * @internal\n */\n get sync() {\n if (this.closed) {\n throw new Error(\"ConvexReactClient has already been closed.\");\n }\n if (this.cachedSync) {\n return this.cachedSync;\n }\n // BaseConvexClient and paginated query client are always created together.\n this.cachedSync = new BaseConvexClient(\n this.address,\n () => {}, // Use the PaginatedQueryClient's transition instead.\n this.options,\n );\n if (this.adminAuth) {\n this.cachedSync.setAdminAuth(this.adminAuth, this.fakeUserIdentity);\n }\n this.cachedPaginatedQueryClient = new PaginatedQueryClient(\n this.cachedSync,\n (transition) => this.handleTransition(transition),\n );\n return this.cachedSync;\n }\n\n /**\n * Lazily instantiate the `PaginatedQueryClient` so we don't create it\n * when server-side rendering.\n *\n * @internal\n */\n get paginatedQueryClient() {\n // access sync to instantiate the clients\n this.sync;\n if (this.cachedPaginatedQueryClient) {\n return this.cachedPaginatedQueryClient;\n }\n throw new Error(\"Should already be instantiated\");\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT-encoded OpenID Connect Identity Token\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n ) {\n if (typeof fetchToken === \"string\") {\n throw new Error(\n \"Passing a string to ConvexReactClient.setAuth is no longer supported, \" +\n \"please upgrade to passing in an async function to handle reauthentication.\",\n );\n }\n this.sync.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n );\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.sync.clearAuth();\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n this.adminAuth = token;\n this.fakeUserIdentity = identity;\n if (this.closed) {\n throw new Error(\"ConvexReactClient has already been closed.\");\n }\n if (this.cachedSync) {\n this.sync.setAdminAuth(token, identity);\n }\n }\n\n /**\n * Construct a new {@link Watch} on a Convex query function.\n *\n * **Most application code should not call this method directly. Instead use\n * the {@link useQuery} hook.**\n *\n * The act of creating a watch does nothing, a Watch is stateless.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link WatchQueryOptions} options object for this query.\n *\n * @returns The {@link Watch} object.\n */\n watchQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...argsAndOptions: ArgsAndOptions<Query, WatchQueryOptions>\n ): Watch<FunctionReturnType<Query>> {\n const [args, options] = argsAndOptions;\n const name = getFunctionName(query);\n\n return {\n onUpdate: (callback) => {\n const { queryToken, unsubscribe } = this.sync.subscribe(\n name as string,\n args,\n options,\n );\n\n const currentListeners = this.listeners.get(queryToken);\n if (currentListeners !== undefined) {\n currentListeners.add(callback);\n } else {\n this.listeners.set(queryToken, new Set([callback]));\n }\n\n return () => {\n if (this.closed) {\n return;\n }\n\n const currentListeners = this.listeners.get(queryToken)!;\n currentListeners.delete(callback);\n if (currentListeners.size === 0) {\n this.listeners.delete(queryToken);\n }\n unsubscribe();\n };\n },\n\n localQueryResult: () => {\n // Use the cached client because we can't have a query result if we don't\n // even have a client yet!\n if (this.cachedSync) {\n return this.cachedSync.localQueryResult(name, args);\n }\n return undefined;\n },\n\n localQueryLogs: () => {\n if (this.cachedSync) {\n return this.cachedSync.localQueryLogs(name, args);\n }\n return undefined;\n },\n\n journal: () => {\n if (this.cachedSync) {\n return this.cachedSync.queryJournal(name, args);\n }\n return undefined;\n },\n };\n }\n\n // Let's try out a queryOptions-style API.\n // This method is similar to the React Query API `queryClient.prefetchQuery()`.\n // In the future an ensureQueryData(): Promise<Data> method could exist.\n /**\n * Indicates likely future interest in a query subscription.\n *\n * The implementation currently immediately subscribes to a query. In the future this method\n * may prioritize some queries over others, fetch the query result without subscribing, or\n * do nothing in slow network connections or high load scenarios.\n *\n * To use this in a React component, call useQuery() and ignore the return value.\n *\n * @param queryOptions - A query (function reference from an api object) and its args, plus\n * an optional extendSubscriptionFor for how long to subscribe to the query.\n */\n prewarmQuery<Query extends FunctionReference<\"query\">>(\n queryOptions: ConvexQueryOptions<Query> & {\n extendSubscriptionFor?: number;\n },\n ) {\n const extendSubscriptionFor =\n queryOptions.extendSubscriptionFor ?? DEFAULT_EXTEND_SUBSCRIPTION_FOR;\n const watch = this.watchQuery(queryOptions.query, queryOptions.args || {});\n const unsubscribe = watch.onUpdate(() => {});\n setTimeout(unsubscribe, extendSubscriptionFor);\n }\n\n /**\n * Construct a new {@link PaginatedWatch} on a Convex paginated query function.\n *\n * **Most application code should not call this method directly. Instead use\n * the {@link usePaginatedQuery} hook.**\n *\n * The act of creating a watch does nothing, a Watch is stateless.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link WatchPaginatedQueryOptions} options object for this query.\n *\n * @returns The {@link PaginatedWatch} object.\n *\n * @internal\n */\n watchPaginatedQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: Query[\"_args\"],\n options: WatchPaginatedQueryOptions,\n ): PaginatedWatch<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n\n return {\n onUpdate: (callback) => {\n const { paginatedQueryToken, unsubscribe } =\n this.paginatedQueryClient.subscribe(name, args || {}, options);\n\n const currentListeners = this.listeners.get(paginatedQueryToken);\n if (currentListeners !== undefined) {\n currentListeners.add(callback);\n } else {\n this.listeners.set(paginatedQueryToken, new Set([callback]));\n }\n\n return () => {\n if (this.closed) {\n return;\n }\n\n const currentListeners = this.listeners.get(paginatedQueryToken)!;\n currentListeners.delete(callback);\n if (currentListeners.size === 0) {\n this.listeners.delete(paginatedQueryToken);\n }\n unsubscribe();\n };\n },\n\n localQueryResult: () => {\n // Use our new paginated query client\n return this.paginatedQueryClient.localQueryResult(name, args, options);\n },\n };\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n ...argsAndOptions: ArgsAndOptions<\n Mutation,\n MutationOptions<FunctionArgs<Mutation>>\n >\n ): Promise<FunctionReturnType<Mutation>> {\n const [args, options] = argsAndOptions;\n const name = getFunctionName(mutation);\n return this.sync.mutation(name, args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n action<Action extends FunctionReference<\"action\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const name = getFunctionName(action);\n return this.sync.action(name, ...args);\n }\n\n /**\n * Fetch a query result once.\n *\n * **Most application code should subscribe to queries instead, using\n * the {@link useQuery} hook.**\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n query<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const watch = this.watchQuery(query, ...args);\n const existingResult = watch.localQueryResult();\n if (existingResult !== undefined) {\n return Promise.resolve(existingResult);\n }\n return new Promise((resolve, reject) => {\n const unsubscribe = watch.onUpdate(() => {\n unsubscribe();\n try {\n resolve(watch.localQueryResult());\n } catch (e) {\n reject(e);\n }\n });\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n return this.sync.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n * ConnectionState may also *lose* properties in future versions as we figure\n * out what information is most useful. As such this API is considered unstable.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n return this.sync.subscribeToConnectionState(cb);\n }\n\n /**\n * Get the logger for this client.\n *\n * @returns The {@link Logger} for this client.\n */\n get logger(): Logger {\n return this._logger;\n }\n\n /**\n * Close any network handles associated with this client and stop all subscriptions.\n *\n * Call this method when you're done with a {@link ConvexReactClient} to\n * dispose of its sockets and resources.\n *\n * @returns A `Promise` fulfilled when the connection has been completely closed.\n */\n async close(): Promise<void> {\n this.closed = true;\n // Prevent outstanding React batched updates from invoking listeners.\n this.listeners = new Map();\n if (this.cachedPaginatedQueryClient) {\n this.cachedPaginatedQueryClient = undefined;\n }\n if (this.cachedSync) {\n const sync = this.cachedSync;\n this.cachedSync = undefined;\n await sync.close();\n }\n }\n\n /**\n * Handle transitions from both base client and paginated client.\n * This ensures all transitions are processed synchronously and in order.\n */\n private handleTransition(transition: ExtendedTransition) {\n const simple = transition.queries.map((q) => q.token);\n const paginated = transition.paginatedQueries.map((q) => q.token);\n this.transition([...simple, ...paginated]);\n }\n\n private transition(updatedQueries: (QueryToken | PaginatedQueryToken)[]) {\n for (const queryToken of updatedQueries) {\n const callbacks = this.listeners.get(queryToken);\n if (callbacks) {\n for (const callback of callbacks) {\n callback();\n }\n }\n }\n }\n}\n\nconst ConvexContext = React.createContext<ConvexReactClient>(\n undefined as unknown as ConvexReactClient, // in the future this will be a mocked client for testing\n);\n\n/**\n * Get the {@link ConvexReactClient} within a React component.\n *\n * This relies on the {@link ConvexProvider} being above in the React component tree.\n *\n * @returns The active {@link ConvexReactClient} object, or `undefined`.\n *\n * @public\n */\nexport function useConvex(): ConvexReactClient {\n return useContext(ConvexContext);\n}\n\n/**\n * Provides an active Convex {@link ConvexReactClient} to descendants of this component.\n *\n * Wrap your app in this component to use Convex hooks `useQuery`,\n * `useMutation`, and `useConvex`.\n *\n * @param props - an object with a `client` property that refers to a {@link ConvexReactClient}.\n *\n * @public\n */\nexport const ConvexProvider: React.FC<{\n client: ConvexReactClient;\n children?: React.ReactNode;\n}> = ({ client, children }) => {\n return React.createElement(\n ConvexContext.Provider,\n { value: client },\n children,\n );\n};\n\nexport type OptionalRestArgsOrSkip<FuncRef extends FunctionReference<any>> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject | \"skip\"]\n : [args: FuncRef[\"_args\"] | \"skip\"];\n\n/**\n * Load a reactive query within a React component.\n *\n * This React hook subscribes to a Convex query and causes a rerender whenever\n * the query result changes. The subscription is managed automatically --\n * it starts when the component mounts and stops when it unmounts.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useQuery } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function TaskList() {\n * // Reactively loads tasks, re-renders when data changes:\n * const tasks = useQuery(api.tasks.list, { completed: false });\n *\n * // Returns `undefined` while loading:\n * if (tasks === undefined) return <div>Loading...</div>;\n *\n * return tasks.map((task) => <div key={task._id}>{task.text}</div>);\n * }\n *\n * // Pass \"skip\" to conditionally disable the query:\n * function MaybeProfile({ userId }: { userId?: Id<\"users\"> }) {\n * const profile = useQuery(\n * api.users.get,\n * userId ? { userId } : \"skip\",\n * );\n * // ...\n * }\n * ```\n *\n * @param query - a {@link server.FunctionReference} for the public query to run\n * like `api.dir1.dir2.filename.func`.\n * @param args - The arguments to the query function or the string `\"skip\"` if the\n * query should not be loaded.\n * @returns the result of the query. Returns `undefined` while loading.\n *\n * @see https://docs.convex.dev/client/react#fetching-data\n * @public\n */\nexport function useQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgsOrSkip<Query>\n): Query[\"_returnType\"] | undefined {\n const skip = args[0] === \"skip\";\n const argsObject = args[0] === \"skip\" ? {} : parseArgs(args[0]);\n\n const queryReference =\n typeof query === \"string\"\n ? makeFunctionReference<\"query\", any, any>(query)\n : query;\n\n const queryName = getFunctionName(queryReference);\n\n const queries = useMemo(\n () =>\n skip\n ? ({} as RequestForQueries)\n : { query: { query: queryReference, args: argsObject } },\n // Stringify args so args that are semantically the same don't trigger a\n // rerender. Saves developers from adding `useMemo` on every args usage.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(convexToJson(argsObject)), queryName, skip],\n );\n\n const results = useQueries(queries);\n const result = results[\"query\"];\n if (result instanceof Error) {\n throw result;\n }\n return result;\n}\n\n/**\n * Construct a new {@link ReactMutation}.\n *\n * Returns a function that you can call to execute a Convex mutation. The\n * returned function is stable across renders (same reference identity), so\n * it can be safely used in dependency arrays and memoization.\n *\n * Mutations can optionally be configured with\n * [optimistic updates](https://docs.convex.dev/client/react/optimistic-updates)\n * for instant UI feedback.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useMutation } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function CreateTask() {\n * const createTask = useMutation(api.tasks.create);\n *\n * const handleClick = async () => {\n * await createTask({ text: \"New task\" });\n * };\n *\n * return <button onClick={handleClick}>Add Task</button>;\n * }\n * ```\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run like `api.dir1.dir2.filename.func`.\n * @returns The {@link ReactMutation} object with that name.\n *\n * @see https://docs.convex.dev/client/react#editing-data\n * @public\n */\nexport function useMutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n): ReactMutation<Mutation> {\n const mutationReference =\n typeof mutation === \"string\"\n ? makeFunctionReference<\"mutation\", any, any>(mutation)\n : mutation;\n\n const convex = useContext(ConvexContext);\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useMutation` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n return useMemo(\n () => createMutation(mutationReference, convex),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [convex, getFunctionName(mutationReference)],\n );\n}\n\n/**\n * Construct a new {@link ReactAction}.\n *\n * Returns a function that you can call to execute a Convex action. Actions\n * can call third-party APIs and perform side effects. The returned function\n * is stable across renders (same reference identity).\n *\n * **Error handling:** Actions can fail (e.g., if an external API is down).\n * Always wrap action calls in try/catch or handle the rejected promise.\n *\n * **Note:** In most cases, calling an action directly from a client is an\n * anti-pattern. Prefer having the client call a mutation that captures the\n * user's intent (by writing to the database) and then schedules the action\n * via `ctx.scheduler.runAfter`. This ensures the intent is durably recorded\n * even if the client disconnects.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @example\n * ```tsx\n * import { useAction } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function GenerateSummary() {\n * const generate = useAction(api.ai.generateSummary);\n *\n * const handleClick = async () => {\n * try {\n * const summary = await generate({ text: \"Some long text...\" });\n * console.log(summary);\n * } catch (error) {\n * console.error(\"Action failed:\", error);\n * }\n * };\n *\n * return <button onClick={handleClick}>Generate</button>;\n * }\n * ```\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run like `api.dir1.dir2.filename.func`.\n * @returns The {@link ReactAction} object with that name.\n *\n * @see https://docs.convex.dev/functions/actions#calling-actions-from-clients\n * @public\n */\nexport function useAction<Action extends FunctionReference<\"action\">>(\n action: Action,\n): ReactAction<Action> {\n const convex = useContext(ConvexContext);\n const actionReference =\n typeof action === \"string\"\n ? makeFunctionReference<\"action\", any, any>(action)\n : action;\n\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useAction` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n return useMemo(\n () => createAction(actionReference, convex),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [convex, getFunctionName(actionReference)],\n );\n}\n\n/**\n * React hook to get the current {@link ConnectionState} and subscribe to changes.\n *\n * This hook returns the current connection state and automatically rerenders\n * when any part of the connection state changes (e.g., when going online/offline,\n * when requests start/complete, etc.).\n *\n * The shape of ConnectionState may change in the future which may cause this\n * hook to rerender more frequently.\n *\n * Throws an error if not used under {@link ConvexProvider}.\n *\n * @returns The current {@link ConnectionState} with the Convex backend.\n *\n * @public\n */\nexport function useConvexConnectionState(): ConnectionState {\n const convex = useContext(ConvexContext);\n if (convex === undefined) {\n throw new Error(\n \"Could not find Convex client! `useConvexConnectionState` must be used in the React component \" +\n \"tree under `ConvexProvider`. Did you forget it? \" +\n \"See https://docs.convex.dev/quick-start#set-up-convex-in-your-react-app\",\n );\n }\n\n const getCurrentValue = useCallback(() => {\n return convex.connectionState();\n }, [convex]);\n\n const subscribe = useCallback(\n (callback: () => void) => {\n return convex.subscribeToConnectionState(() => {\n callback();\n });\n },\n [convex],\n );\n\n return useSubscription({ getCurrentValue, subscribe });\n}\n\n// When a function is called with a single argument that looks like a\n// React SyntheticEvent it was likely called as an event handler.\nfunction assertNotAccidentalArgument(value: any) {\n // these are properties of a React.SyntheticEvent\n // https://reactjs.org/docs/events.html\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"bubbles\" in value &&\n \"persist\" in value &&\n \"isDefaultPrevented\" in value\n ) {\n throw new Error(\n `Convex function called with SyntheticEvent object. Did you use a Convex function as an event handler directly? Event handlers like onClick receive an event object as their first argument. These SyntheticEvent objects are not valid Convex values. Try wrapping the function like \\`const handler = () => myMutation();\\` and using \\`handler\\` in the event handler.`,\n );\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;AAAA,SAAS,wBAAwB;AAOjC,OAAO,SAAS,aAAa,YAAY,eAAe;AACxD,SAAS,oBAA2B;AAQpC,SAA4B,kBAAkB;AAC9C,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B;AAAA,EAME;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAGP;AAAA,EACE;AAAA,OAEK;AAIP,MAAM,kCAAkC;AAExC,IAAI,OAAO,UAAU,aAAa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X,QAAM,YAAY;AAAA,IAChB,CAAC,aAAyB;AACxB,aAAO,OAAO,2BAA2B,MAAM;AAC7C,iBAAS;AAAA,MACX,CAAC;AAAA,IACH;AAAA,IACA,CAAC,MAAM;AAAA,EACT;AAEA,SAAO,gBAAgB,EAAE,iBAAiB,UAAU,CAAC;AACvD;AAIA,SAAS,4BAA4B,OAAY;AAG/C,MACE,OAAO,UAAU,YACjB,UAAU,QACV,aAAa,SACb,aAAa,SACb,wBAAwB,OACxB;AACA,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["currentListeners"]
|
|
7
7
|
}
|
package/dist/esm/react/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/react/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Tools to integrate Convex into React applications.\n *\n * This module contains:\n * 1. {@link ConvexReactClient}, a client for using Convex in React.\n * 2. {@link ConvexProvider}, a component that stores this client in React context.\n * 3. {@link Authenticated}, {@link Unauthenticated} and {@link AuthLoading} helper auth components.\n * 4. Hooks {@link useQuery}, {@link useMutation}, {@link useAction} and more for accessing this\n * client from your React components.\n *\n * ## Usage\n *\n * ### Creating the client\n *\n * ```typescript\n * import { ConvexReactClient } from \"convex/react\";\n *\n * // typically loaded from an environment variable\n * const address = \"https://small-mouse-123.convex.cloud\"\n * const convex = new ConvexReactClient(address);\n * ```\n *\n * ### Storing the client in React Context\n *\n * ```typescript\n * import { ConvexProvider } from \"convex/react\";\n *\n * <ConvexProvider client={convex}>\n * <App />\n * </ConvexProvider>\n * ```\n *\n * ### Using the auth helpers\n *\n * ```typescript\n * import { Authenticated, Unauthenticated, AuthLoading } from \"convex/react\";\n *\n * <Authenticated>\n * Logged in\n * </Authenticated>\n * <Unauthenticated>\n * Logged out\n * </Unauthenticated>\n * <AuthLoading>\n * Still loading\n * </AuthLoading>\n * ```\n *\n * ### Using React hooks\n *\n * ```typescript\n * import { useQuery, useMutation } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function App() {\n * const counter = useQuery(
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["/**\n * Tools to integrate Convex into React applications.\n *\n * This module contains:\n * 1. {@link ConvexReactClient}, a client for using Convex in React.\n * 2. {@link ConvexProvider}, a component that stores this client in React context.\n * 3. {@link Authenticated}, {@link Unauthenticated} and {@link AuthLoading} helper auth components.\n * 4. Hooks {@link useQuery}, {@link useMutation}, {@link useAction} and more for accessing this\n * client from your React components.\n *\n * ## Usage\n *\n * ### Creating the client\n *\n * ```typescript\n * import { ConvexReactClient } from \"convex/react\";\n *\n * // typically loaded from an environment variable\n * const address = \"https://small-mouse-123.convex.cloud\"\n * const convex = new ConvexReactClient(address);\n * ```\n *\n * ### Storing the client in React Context\n *\n * ```typescript\n * import { ConvexProvider } from \"convex/react\";\n *\n * <ConvexProvider client={convex}>\n * <App />\n * </ConvexProvider>\n * ```\n *\n * ### Using the auth helpers\n *\n * ```typescript\n * import { Authenticated, Unauthenticated, AuthLoading } from \"convex/react\";\n *\n * <Authenticated>\n * Logged in\n * </Authenticated>\n * <Unauthenticated>\n * Logged out\n * </Unauthenticated>\n * <AuthLoading>\n * Still loading\n * </AuthLoading>\n * ```\n *\n * ### Using React hooks\n *\n * ```typescript\n * import { useQuery, useMutation } from \"convex/react\";\n * import { api } from \"../convex/_generated/api\";\n *\n * function App() {\n * const counter = useQuery(api.getCounter.default);\n * const increment = useMutation(api.incrementCounter.default);\n * // Your component here!\n * }\n * ```\n * @module\n */\nexport * from \"./use_paginated_query.js\";\nexport { usePaginatedQuery_experimental } from \"./use_paginated_query2.js\";\nexport { usePaginatedQuery } from \"./use_paginated_query.js\";\nexport { useQueries, type RequestForQueries } from \"./use_queries.js\";\nexport type { AuthTokenFetcher } from \"../browser/sync/client.js\";\nexport * from \"./auth_helpers.js\";\nexport * from \"./ConvexAuthState.js\";\nexport * from \"./hydration.js\";\n/* @internal */\nexport { useSubscription } from \"./use_subscription.js\";\nexport {\n type ReactMutation,\n type ReactAction,\n type Watch,\n type WatchQueryOptions,\n type MutationOptions,\n type ConvexReactClientOptions,\n type OptionalRestArgsOrSkip,\n ConvexReactClient,\n useConvex,\n ConvexProvider,\n useQuery,\n useMutation,\n useAction,\n useConvexConnectionState,\n} from \"./client.js\";\n"],
|
|
5
|
+
"mappings": ";AA8DA,cAAc;AACd,SAAS,sCAAsC;AAC/C,SAAS,yBAAyB;AAClC,SAAS,kBAA0C;AAEnD,cAAc;AACd,cAAc;AACd,cAAc;AAEd,SAAS,uBAAuB;AAChC;AAAA,EAQE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/server/api.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n EmptyObject,\n DefaultFunctionArgs,\n FunctionVisibility,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"./registration.js\";\nimport { Expand, UnionToIntersection } from \"../type_utils.js\";\nimport { PaginationOptions, PaginationResult } from \"./pagination.js\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\n\n/**\n * The type of a Convex function.\n *\n * @public\n */\nexport type FunctionType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * A reference to a registered Convex function.\n *\n * You can create a {@link FunctionReference} using the generated `api` utility:\n * ```js\n * import { api } from \"../convex/_generated/api\";\n *\n * const reference = api.myModule.myFunction;\n * ```\n *\n * If you aren't using code generation, you can create references using\n * {@link anyApi}:\n * ```js\n * import { anyApi } from \"convex/server\";\n *\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * Function references can be used to invoke functions from the client. For\n * example, in React you can pass references to the {@link react.useQuery} hook:\n * ```js\n * const result = useQuery({\n * query: api.myModule.myFunction,\n * args: {},\n * throwOnError: true,\n * }).data;\n * ```\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments to this function. This is an object mapping\n * argument names to their types.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n _args: Args;\n _returnType: ReturnType;\n _componentPath: ComponentPath;\n};\n\n/**\n * Get the name of a function from a {@link FunctionReference}.\n *\n * The name is a string like \"myDir/myModule:myFunction\". If the exported name\n * of the function is `\"default\"`, the function name is omitted\n * (e.g. \"myDir/myModule\").\n *\n * @param functionReference - A {@link FunctionReference} to get the name of.\n * @returns A string of the function's name.\n *\n * @public\n */\nexport function getFunctionName(\n functionReference: AnyFunctionReference,\n): string {\n const address = getFunctionAddress(functionReference);\n\n if (address.name === undefined) {\n if (address.functionHandle !== undefined) {\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`,\n );\n } else if (address.reference !== undefined) {\n throw new Error(\n `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`,\n );\n }\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`,\n );\n }\n // Both a legacy thing and also a convenience for interactive use:\n // the types won't check but a string is always allowed at runtime.\n if (typeof functionReference === \"string\") return functionReference;\n\n // Two different runtime values for FunctionReference implement this\n // interface: api objects returned from `createApi()` and standalone\n // function reference objects returned from makeFunctionReference.\n const name = (functionReference as any)[functionName];\n if (!name) {\n throw new Error(`${functionReference as any} is not a functionReference`);\n }\n return name;\n}\n\n/**\n * FunctionReferences generally come from generated code, but in custom clients\n * it may be useful to be able to build one manually.\n *\n * Real function references are empty objects at runtime, but the same interface\n * can be implemented with an object for tests and clients which don't use\n * code generation.\n *\n * @param name - The identifier of the function. E.g. `path/to/file:functionName`\n * @public\n */\nexport function makeFunctionReference<\n type extends FunctionType,\n args extends DefaultFunctionArgs = any,\n ret = any,\n>(name: string): FunctionReference<type, \"public\", args, ret> {\n return { [functionName]: name } as unknown as FunctionReference<\n type,\n \"public\",\n args,\n ret\n >;\n}\n\n/**\n * Create a runtime API object that implements {@link AnyApi}.\n *\n * This allows accessing any path regardless of what directories, modules,\n * or functions are defined.\n *\n * @param pathParts - The path to the current node in the API.\n * @returns An {@link AnyApi}\n * @public\n */\nfunction createApi(pathParts: string[] = []): AnyApi {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createApi(newParts);\n } else if (prop === functionName) {\n if (pathParts.length < 2) {\n const found = [\"api\", ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``,\n );\n }\n const path = pathParts.slice(0, -1).join(\"/\");\n const exportName = pathParts[pathParts.length - 1];\n if (exportName === \"default\") {\n return path;\n } else {\n return path + \":\" + exportName;\n }\n } else if (prop === Symbol.toStringTag) {\n return \"FunctionReference\";\n } else {\n return undefined;\n }\n },\n };\n\n return new Proxy({}, handler);\n}\n\n/**\n * Given an export from a module, convert it to a {@link FunctionReference}\n * if it is a Convex function.\n */\nexport type FunctionReferenceFromExport<Export> =\n Export extends RegisteredQuery<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"query\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredMutation<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"mutation\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredAction<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"action\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : never;\n\n/**\n * Given a module, convert all the Convex functions into\n * {@link FunctionReference}s and remove the other exports.\n *\n * BE CAREFUL WHEN EDITING THIS!\n *\n * This is written carefully to preserve jumping to function definitions using\n * cmd+click. If you edit it, please test that cmd+click still works.\n */\ntype FunctionReferencesInModule<Module extends Record<string, any>> = {\n -readonly [ExportName in keyof Module as Module[ExportName][\"isConvexFunction\"] extends true\n ? ExportName\n : never]: FunctionReferenceFromExport<Module[ExportName]>;\n};\n\n/**\n * Given a path to a module and it's type, generate an API type for this module.\n *\n * This is a nested object according to the module's path.\n */\ntype ApiForModule<\n ModulePath extends string,\n Module extends object,\n> = ModulePath extends `${infer First}/${infer Second}`\n ? {\n [_ in First]: ApiForModule<Second, Module>;\n }\n : { [_ in ModulePath]: FunctionReferencesInModule<Module> };\n\n/**\n * Given the types of all modules in the `convex/` directory, construct the type\n * of `api`.\n *\n * `api` is a utility for constructing {@link FunctionReference}s.\n *\n * @typeParam AllModules - A type mapping module paths (like `\"dir/myModule\"`) to\n * the types of the modules.\n * @public\n */\nexport type ApiFromModules<AllModules extends Record<string, object>> =\n FilterApi<\n ApiFromModulesAllowEmptyNodes<AllModules>,\n FunctionReference<any, any, any, any>\n >;\n\ntype ApiFromModulesAllowEmptyNodes<AllModules extends Record<string, object>> =\n ExpandModulesAndDirs<\n UnionToIntersection<\n {\n [ModulePath in keyof AllModules]: ApiForModule<\n ModulePath & string,\n AllModules[ModulePath]\n >;\n }[keyof AllModules]\n >\n >;\n\ntype FilterKeysInApi<key, API, Predicate> = API extends Predicate\n ? key\n : API extends FunctionReference<any, any, any, any>\n ? never\n : FilterApi<API, Predicate> extends Record<string, never>\n ? never\n : key;\n\n/**\n * @public\n *\n * Filter a Convex deployment api object for functions which meet criteria,\n * for example all public queries.\n */\nexport type FilterApi<API, Predicate> = Expand<{\n [mod in keyof API as FilterKeysInApi<\n mod,\n API[mod],\n Predicate\n >]: API[mod] extends Predicate ? API[mod] : FilterApi<API[mod], Predicate>;\n}>;\n\n/**\n * Given an api of type API and a FunctionReference subtype, return an api object\n * containing only the function references that match.\n *\n * ```ts\n * const q = filterApi<typeof api, FunctionReference<\"query\">>(api)\n * ```\n *\n * @public\n */\nexport function filterApi<API, Predicate>(api: API): FilterApi<API, Predicate> {\n return api as any;\n}\n\n// These just* API filter helpers require no type parameters so are useable from JavaScript.\n/** @public */\nexport function justInternal<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"internal\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPublic<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"public\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justQueries<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"query\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justMutations<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justActions<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"action\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPaginatedQueries<API>(\n api: API,\n): FilterApi<\n API,\n FunctionReference<\n \"query\",\n any,\n { paginationOpts: PaginationOptions },\n PaginationResult<any>\n >\n> {\n return api as any;\n}\n\n/** @public */\nexport function justSchedulable<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\" | \"action\", any, any, any>> {\n return api as any;\n}\n\n/**\n * Like {@link Expand}, this simplifies how TypeScript displays object types.\n * The differences are:\n * 1. This version is recursive.\n * 2. This stops recursing when it hits a {@link FunctionReference}.\n */\ntype ExpandModulesAndDirs<ObjectType> = ObjectType extends AnyFunctionReference\n ? ObjectType\n : {\n [Key in keyof ObjectType]: ExpandModulesAndDirs<ObjectType[Key]>;\n };\n\n/**\n * A {@link FunctionReference} of any type and any visibility with any\n * arguments and any return type.\n *\n * @public\n */\nexport type AnyFunctionReference = FunctionReference<any, any>;\n\ntype AnyModuleDirOrFunc = {\n [key: string]: AnyModuleDirOrFunc;\n} & AnyFunctionReference;\n\n/**\n * The type that Convex api objects extend. If you were writing an api from\n * scratch it should extend this type.\n *\n * @public\n */\nexport type AnyApi = Record<string, Record<string, AnyModuleDirOrFunc>>;\n\n/**\n * Recursive partial API, useful for defining a subset of an API when mocking\n * or building custom api objects.\n *\n * @public\n */\nexport type PartialApi<API> = {\n [mod in keyof API]?: API[mod] extends FunctionReference<any, any, any, any>\n ? API[mod]\n : PartialApi<API[mod]>;\n};\n\n/**\n * A utility for constructing {@link FunctionReference}s in projects that\n * are not using code generation.\n *\n * You can create a reference to a function like:\n * ```js\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * This supports accessing any path regardless of what directories and modules\n * are in your project. All function references are typed as\n * {@link AnyFunctionReference}.\n *\n *\n * If you're using code generation, use `api` from `convex/_generated/api`\n * instead. It will be more type-safe and produce better auto-complete\n * in your editor.\n *\n * @public\n */\nexport const anyApi: AnyApi = createApi() as any;\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * This is represented as an object mapping argument names to values.\n * @public\n */\nexport type FunctionArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`.\n *\n * This type is used to make methods involving arguments type safe while allowing\n * skipping the arguments for functions that don't require arguments.\n *\n * @public\n */\nexport type OptionalRestArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject]\n : [args: FuncRef[\"_args\"]];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`, followed by an options\n * object of type `Options`.\n *\n * This type is used to make methods like `useQuery` type-safe while allowing\n * 1. Skipping arguments for functions that don't require arguments.\n * 2. Skipping the options object.\n * @public\n */\nexport type ArgsAndOptions<\n FuncRef extends AnyFunctionReference,\n Options,\n> = FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject, options?: Options]\n : [args: FuncRef[\"_args\"], options?: Options];\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * @public\n */\nexport type FunctionReturnType<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_returnType\"];\n\ntype UndefinedToNull<T> = T extends void ? null : T;\n\ntype NullToUndefinedOrNull<T> = T extends null ? T | undefined | void : T;\n\n/**\n * Convert the return type of a function to it's client-facing format.\n *\n * This means:\n * - Converting `undefined` and `void` to `null`\n * - Removing all `Promise` wrappers\n */\nexport type ConvertReturnType<T> = UndefinedToNull<Awaited<T>>;\n\nexport type ValidatorTypeToReturnType<T> =\n | Promise<NullToUndefinedOrNull<T>>\n | NullToUndefinedOrNull<T>;\n"],
|
|
5
|
-
"mappings": ";AAUA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;
|
|
4
|
+
"sourcesContent": ["import {\n EmptyObject,\n DefaultFunctionArgs,\n FunctionVisibility,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"./registration.js\";\nimport { Expand, UnionToIntersection } from \"../type_utils.js\";\nimport { PaginationOptions, PaginationResult } from \"./pagination.js\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\n\n/**\n * The type of a Convex function.\n *\n * @public\n */\nexport type FunctionType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * A reference to a registered Convex function.\n *\n * You can create a {@link FunctionReference} using the generated `api` utility:\n * ```js\n * import { api } from \"../convex/_generated/api\";\n *\n * const reference = api.myModule.myFunction;\n * ```\n *\n * If you aren't using code generation, you can create references using\n * {@link anyApi}:\n * ```js\n * import { anyApi } from \"convex/server\";\n *\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * Function references can be used to invoke functions from the client. For\n * example, in React you can pass references to the {@link react.useQuery} hook:\n * ```js\n * const result = useQuery(api.myModule.myFunction);\n * ```\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments to this function. This is an object mapping\n * argument names to their types.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n _args: Args;\n _returnType: ReturnType;\n _componentPath: ComponentPath;\n};\n\n/**\n * Get the name of a function from a {@link FunctionReference}.\n *\n * The name is a string like \"myDir/myModule:myFunction\". If the exported name\n * of the function is `\"default\"`, the function name is omitted\n * (e.g. \"myDir/myModule\").\n *\n * @param functionReference - A {@link FunctionReference} to get the name of.\n * @returns A string of the function's name.\n *\n * @public\n */\nexport function getFunctionName(\n functionReference: AnyFunctionReference,\n): string {\n const address = getFunctionAddress(functionReference);\n\n if (address.name === undefined) {\n if (address.functionHandle !== undefined) {\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`,\n );\n } else if (address.reference !== undefined) {\n throw new Error(\n `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`,\n );\n }\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`,\n );\n }\n // Both a legacy thing and also a convenience for interactive use:\n // the types won't check but a string is always allowed at runtime.\n if (typeof functionReference === \"string\") return functionReference;\n\n // Two different runtime values for FunctionReference implement this\n // interface: api objects returned from `createApi()` and standalone\n // function reference objects returned from makeFunctionReference.\n const name = (functionReference as any)[functionName];\n if (!name) {\n throw new Error(`${functionReference as any} is not a functionReference`);\n }\n return name;\n}\n\n/**\n * FunctionReferences generally come from generated code, but in custom clients\n * it may be useful to be able to build one manually.\n *\n * Real function references are empty objects at runtime, but the same interface\n * can be implemented with an object for tests and clients which don't use\n * code generation.\n *\n * @param name - The identifier of the function. E.g. `path/to/file:functionName`\n * @public\n */\nexport function makeFunctionReference<\n type extends FunctionType,\n args extends DefaultFunctionArgs = any,\n ret = any,\n>(name: string): FunctionReference<type, \"public\", args, ret> {\n return { [functionName]: name } as unknown as FunctionReference<\n type,\n \"public\",\n args,\n ret\n >;\n}\n\n/**\n * Create a runtime API object that implements {@link AnyApi}.\n *\n * This allows accessing any path regardless of what directories, modules,\n * or functions are defined.\n *\n * @param pathParts - The path to the current node in the API.\n * @returns An {@link AnyApi}\n * @public\n */\nfunction createApi(pathParts: string[] = []): AnyApi {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createApi(newParts);\n } else if (prop === functionName) {\n if (pathParts.length < 2) {\n const found = [\"api\", ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``,\n );\n }\n const path = pathParts.slice(0, -1).join(\"/\");\n const exportName = pathParts[pathParts.length - 1];\n if (exportName === \"default\") {\n return path;\n } else {\n return path + \":\" + exportName;\n }\n } else if (prop === Symbol.toStringTag) {\n return \"FunctionReference\";\n } else {\n return undefined;\n }\n },\n };\n\n return new Proxy({}, handler);\n}\n\n/**\n * Given an export from a module, convert it to a {@link FunctionReference}\n * if it is a Convex function.\n */\nexport type FunctionReferenceFromExport<Export> =\n Export extends RegisteredQuery<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"query\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredMutation<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"mutation\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredAction<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"action\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : never;\n\n/**\n * Given a module, convert all the Convex functions into\n * {@link FunctionReference}s and remove the other exports.\n *\n * BE CAREFUL WHEN EDITING THIS!\n *\n * This is written carefully to preserve jumping to function definitions using\n * cmd+click. If you edit it, please test that cmd+click still works.\n */\ntype FunctionReferencesInModule<Module extends Record<string, any>> = {\n -readonly [ExportName in keyof Module as Module[ExportName][\"isConvexFunction\"] extends true\n ? ExportName\n : never]: FunctionReferenceFromExport<Module[ExportName]>;\n};\n\n/**\n * Given a path to a module and it's type, generate an API type for this module.\n *\n * This is a nested object according to the module's path.\n */\ntype ApiForModule<\n ModulePath extends string,\n Module extends object,\n> = ModulePath extends `${infer First}/${infer Second}`\n ? {\n [_ in First]: ApiForModule<Second, Module>;\n }\n : { [_ in ModulePath]: FunctionReferencesInModule<Module> };\n\n/**\n * Given the types of all modules in the `convex/` directory, construct the type\n * of `api`.\n *\n * `api` is a utility for constructing {@link FunctionReference}s.\n *\n * @typeParam AllModules - A type mapping module paths (like `\"dir/myModule\"`) to\n * the types of the modules.\n * @public\n */\nexport type ApiFromModules<AllModules extends Record<string, object>> =\n FilterApi<\n ApiFromModulesAllowEmptyNodes<AllModules>,\n FunctionReference<any, any, any, any>\n >;\n\ntype ApiFromModulesAllowEmptyNodes<AllModules extends Record<string, object>> =\n ExpandModulesAndDirs<\n UnionToIntersection<\n {\n [ModulePath in keyof AllModules]: ApiForModule<\n ModulePath & string,\n AllModules[ModulePath]\n >;\n }[keyof AllModules]\n >\n >;\n\ntype FilterKeysInApi<key, API, Predicate> = API extends Predicate\n ? key\n : API extends FunctionReference<any, any, any, any>\n ? never\n : FilterApi<API, Predicate> extends Record<string, never>\n ? never\n : key;\n\n/**\n * @public\n *\n * Filter a Convex deployment api object for functions which meet criteria,\n * for example all public queries.\n */\nexport type FilterApi<API, Predicate> = Expand<{\n [mod in keyof API as FilterKeysInApi<\n mod,\n API[mod],\n Predicate\n >]: API[mod] extends Predicate ? API[mod] : FilterApi<API[mod], Predicate>;\n}>;\n\n/**\n * Given an api of type API and a FunctionReference subtype, return an api object\n * containing only the function references that match.\n *\n * ```ts\n * const q = filterApi<typeof api, FunctionReference<\"query\">>(api)\n * ```\n *\n * @public\n */\nexport function filterApi<API, Predicate>(api: API): FilterApi<API, Predicate> {\n return api as any;\n}\n\n// These just* API filter helpers require no type parameters so are useable from JavaScript.\n/** @public */\nexport function justInternal<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"internal\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPublic<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"public\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justQueries<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"query\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justMutations<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justActions<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"action\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPaginatedQueries<API>(\n api: API,\n): FilterApi<\n API,\n FunctionReference<\n \"query\",\n any,\n { paginationOpts: PaginationOptions },\n PaginationResult<any>\n >\n> {\n return api as any;\n}\n\n/** @public */\nexport function justSchedulable<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\" | \"action\", any, any, any>> {\n return api as any;\n}\n\n/**\n * Like {@link Expand}, this simplifies how TypeScript displays object types.\n * The differences are:\n * 1. This version is recursive.\n * 2. This stops recursing when it hits a {@link FunctionReference}.\n */\ntype ExpandModulesAndDirs<ObjectType> = ObjectType extends AnyFunctionReference\n ? ObjectType\n : {\n [Key in keyof ObjectType]: ExpandModulesAndDirs<ObjectType[Key]>;\n };\n\n/**\n * A {@link FunctionReference} of any type and any visibility with any\n * arguments and any return type.\n *\n * @public\n */\nexport type AnyFunctionReference = FunctionReference<any, any>;\n\ntype AnyModuleDirOrFunc = {\n [key: string]: AnyModuleDirOrFunc;\n} & AnyFunctionReference;\n\n/**\n * The type that Convex api objects extend. If you were writing an api from\n * scratch it should extend this type.\n *\n * @public\n */\nexport type AnyApi = Record<string, Record<string, AnyModuleDirOrFunc>>;\n\n/**\n * Recursive partial API, useful for defining a subset of an API when mocking\n * or building custom api objects.\n *\n * @public\n */\nexport type PartialApi<API> = {\n [mod in keyof API]?: API[mod] extends FunctionReference<any, any, any, any>\n ? API[mod]\n : PartialApi<API[mod]>;\n};\n\n/**\n * A utility for constructing {@link FunctionReference}s in projects that\n * are not using code generation.\n *\n * You can create a reference to a function like:\n * ```js\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * This supports accessing any path regardless of what directories and modules\n * are in your project. All function references are typed as\n * {@link AnyFunctionReference}.\n *\n *\n * If you're using code generation, use `api` from `convex/_generated/api`\n * instead. It will be more type-safe and produce better auto-complete\n * in your editor.\n *\n * @public\n */\nexport const anyApi: AnyApi = createApi() as any;\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * This is represented as an object mapping argument names to values.\n * @public\n */\nexport type FunctionArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`.\n *\n * This type is used to make methods involving arguments type safe while allowing\n * skipping the arguments for functions that don't require arguments.\n *\n * @public\n */\nexport type OptionalRestArgs<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject]\n : [args: FuncRef[\"_args\"]];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`, followed by an options\n * object of type `Options`.\n *\n * This type is used to make methods like `useQuery` type-safe while allowing\n * 1. Skipping arguments for functions that don't require arguments.\n * 2. Skipping the options object.\n * @public\n */\nexport type ArgsAndOptions<\n FuncRef extends AnyFunctionReference,\n Options,\n> = FuncRef[\"_args\"] extends EmptyObject\n ? [args?: EmptyObject, options?: Options]\n : [args: FuncRef[\"_args\"], options?: Options];\n\n/**\n * Given a {@link FunctionReference}, get the return type of the function.\n *\n * @public\n */\nexport type FunctionReturnType<FuncRef extends AnyFunctionReference> =\n FuncRef[\"_returnType\"];\n\ntype UndefinedToNull<T> = T extends void ? null : T;\n\ntype NullToUndefinedOrNull<T> = T extends null ? T | undefined | void : T;\n\n/**\n * Convert the return type of a function to it's client-facing format.\n *\n * This means:\n * - Converting `undefined` and `void` to `null`\n * - Removing all `Promise` wrappers\n */\nexport type ConvertReturnType<T> = UndefinedToNull<Awaited<T>>;\n\nexport type ValidatorTypeToReturnType<T> =\n | Promise<NullToUndefinedOrNull<T>>\n | NullToUndefinedOrNull<T>;\n"],
|
|
5
|
+
"mappings": ";AAUA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AAkE5B,gBAAS,gBACd,mBACQ;AACR,QAAM,UAAU,mBAAmB,iBAAiB;AAEpD,MAAI,QAAQ,SAAS,QAAW;AAC9B,QAAI,QAAQ,mBAAmB,QAAW;AACxC,YAAM,IAAI;AAAA,QACR,0GAA0G,QAAQ,cAAc;AAAA,MAClI;AAAA,IACF,WAAW,QAAQ,cAAc,QAAW;AAC1C,YAAM,IAAI;AAAA,QACR,6HAA6H,QAAQ,SAAS;AAAA,MAChJ;AAAA,IACF;AACA,UAAM,IAAI;AAAA,MACR,0FAA0F,KAAK,UAAU,OAAO,CAAC;AAAA,IACnH;AAAA,EACF;AAGA,MAAI,OAAO,sBAAsB,SAAU,QAAO;AAKlD,QAAM,OAAQ,kBAA0B,YAAY;AACpD,MAAI,CAAC,MAAM;AACT,UAAM,IAAI,MAAM,GAAG,iBAAwB,6BAA6B;AAAA,EAC1E;AACA,SAAO;AACT;AAaO,gBAAS,sBAId,MAA4D;AAC5D,SAAO,EAAE,CAAC,YAAY,GAAG,KAAK;AAMhC;AAYA,SAAS,UAAU,YAAsB,CAAC,GAAW;AACnD,QAAM,UAAgC;AAAA,IACpC,IAAI,GAAG,MAAuB;AAC5B,UAAI,OAAO,SAAS,UAAU;AAC5B,cAAM,WAAW,CAAC,GAAG,WAAW,IAAI;AACpC,eAAO,UAAU,QAAQ;AAAA,MAC3B,WAAW,SAAS,cAAc;AAChC,YAAI,UAAU,SAAS,GAAG;AACxB,gBAAM,QAAQ,CAAC,OAAO,GAAG,SAAS,EAAE,KAAK,GAAG;AAC5C,gBAAM,IAAI;AAAA,YACR,oFAAoF,KAAK;AAAA,UAC3F;AAAA,QACF;AACA,cAAM,OAAO,UAAU,MAAM,GAAG,EAAE,EAAE,KAAK,GAAG;AAC5C,cAAM,aAAa,UAAU,UAAU,SAAS,CAAC;AACjD,YAAI,eAAe,WAAW;AAC5B,iBAAO;AAAA,QACT,OAAO;AACL,iBAAO,OAAO,MAAM;AAAA,QACtB;AAAA,MACF,WAAW,SAAS,OAAO,aAAa;AACtC,eAAO;AAAA,MACT,OAAO;AACL,eAAO;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,SAAO,IAAI,MAAM,CAAC,GAAG,OAAO;AAC9B;AAmIO,gBAAS,UAA0B,KAAqC;AAC7E,SAAO;AACT;AAIO,gBAAS,aACd,KAC8D;AAC9D,SAAO;AACT;AAGO,gBAAS,WACd,KAC4D;AAC5D,SAAO;AACT;AAGO,gBAAS,YACd,KAC2D;AAC3D,SAAO;AACT;AAGO,gBAAS,cACd,KAC8D;AAC9D,SAAO;AACT;AAGO,gBAAS,YACd,KAC4D;AAC5D,SAAO;AACT;AAGO,gBAAS,qBACd,KASA;AACA,SAAO;AACT;AAGO,gBAAS,gBACd,KACyE;AACzE,SAAO;AACT;AAkEO,aAAM,SAAiB,UAAU;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -27,5 +27,4 @@ export { ConvexHttpClient } from "./http_client.js";
|
|
|
27
27
|
export type { HttpMutationOptions } from "./http_client.js";
|
|
28
28
|
export type { QueryJournal } from "./sync/protocol.js";
|
|
29
29
|
export type { FunctionResult } from "./sync/function_result.js";
|
|
30
|
-
export type { QueryOptions } from "./query_options.js";
|
|
31
30
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,YAAY,EACV,uBAAuB,EACvB,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,YAAY,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,YAAY,EACV,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,8BAA8B,CAAC;AACtC,YAAY,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAG3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,YAAY,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGvD,YAAY,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,YAAY,EACV,uBAAuB,EACvB,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,gBAAgB,GACjB,MAAM,kBAAkB,CAAC;AAC1B,YAAY,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC7D,YAAY,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,YAAY,EACV,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,8BAA8B,CAAC;AACtC,YAAY,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAG3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,YAAY,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGvD,YAAY,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC"}
|
|
@@ -1,19 +1,16 @@
|
|
|
1
|
-
import type { FunctionArgs, FunctionReference } from "../server/api.js";
|
|
2
1
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* Used with the object-form overload of {@link useQuery}.
|
|
2
|
+
* Query options are a potential new API for a variety of functions, but in particular a new overload of the React hook for queries.
|
|
6
3
|
*
|
|
7
|
-
*
|
|
4
|
+
* Inspired by https://tanstack.com/query/v5/docs/framework/react/guides/query-options
|
|
5
|
+
*/
|
|
6
|
+
import type { FunctionArgs, FunctionReference } from "../server/api.js";
|
|
7
|
+
/**
|
|
8
|
+
* Query options.
|
|
8
9
|
*/
|
|
9
|
-
export type
|
|
10
|
-
/**
|
|
11
|
-
* The query function to run.
|
|
12
|
-
*/
|
|
10
|
+
export type ConvexQueryOptions<Query extends FunctionReference<"query">> = {
|
|
13
11
|
query: Query;
|
|
14
|
-
/**
|
|
15
|
-
* The arguments to the query function.
|
|
16
|
-
*/
|
|
17
12
|
args: FunctionArgs<Query>;
|
|
13
|
+
extendSubscriptionFor?: number;
|
|
18
14
|
};
|
|
15
|
+
export declare function convexQueryOptions<Query extends FunctionReference<"query">>(options: ConvexQueryOptions<Query>): ConvexQueryOptions<Query>;
|
|
19
16
|
//# sourceMappingURL=query_options.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"query_options.d.ts","sourceRoot":"","sources":["../../../src/browser/query_options.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"query_options.d.ts","sourceRoot":"","sources":["../../../src/browser/query_options.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAMxE;;GAEG;AACH,MAAM,MAAM,kBAAkB,CAAC,KAAK,SAAS,iBAAiB,CAAC,OAAO,CAAC,IAAI;IACzE,KAAK,EAAE,KAAK,CAAC;IACb,IAAI,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC;IAC1B,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAGF,wBAAgB,kBAAkB,CAAC,KAAK,SAAS,iBAAiB,CAAC,OAAO,CAAC,EACzE,OAAO,EAAE,kBAAkB,CAAC,KAAK,CAAC,GACjC,kBAAkB,CAAC,KAAK,CAAC,CAE3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readme.d.ts","sourceRoot":"","sources":["../../../../src/cli/codegen_templates/readme.ts"],"names":[],"mappings":"AAAA,wBAAgB,aAAa,
|
|
1
|
+
{"version":3,"file":"readme.d.ts","sourceRoot":"","sources":["../../../../src/cli/codegen_templates/readme.ts"],"names":[],"mappings":"AAAA,wBAAgB,aAAa,WAwF5B"}
|
|
@@ -7,13 +7,13 @@ export declare const appDefinitionConfig: z.ZodObject<{
|
|
|
7
7
|
environment: z.ZodUnion<[z.ZodLiteral<"isolate">, z.ZodLiteral<"node">]>;
|
|
8
8
|
}, "passthrough", z.ZodTypeAny, {
|
|
9
9
|
path: string;
|
|
10
|
-
environment: "node" | "isolate";
|
|
11
10
|
source: string;
|
|
11
|
+
environment: "node" | "isolate";
|
|
12
12
|
sourceMap?: string | undefined;
|
|
13
13
|
}, {
|
|
14
14
|
path: string;
|
|
15
|
-
environment: "node" | "isolate";
|
|
16
15
|
source: string;
|
|
16
|
+
environment: "node" | "isolate";
|
|
17
17
|
sourceMap?: string | undefined;
|
|
18
18
|
}>>;
|
|
19
19
|
dependencies: z.ZodArray<z.ZodString, "many">;
|
|
@@ -24,13 +24,13 @@ export declare const appDefinitionConfig: z.ZodObject<{
|
|
|
24
24
|
environment: z.ZodUnion<[z.ZodLiteral<"isolate">, z.ZodLiteral<"node">]>;
|
|
25
25
|
}, "passthrough", z.ZodTypeAny, {
|
|
26
26
|
path: string;
|
|
27
|
-
environment: "node" | "isolate";
|
|
28
27
|
source: string;
|
|
28
|
+
environment: "node" | "isolate";
|
|
29
29
|
sourceMap?: string | undefined;
|
|
30
30
|
}, {
|
|
31
31
|
path: string;
|
|
32
|
-
environment: "node" | "isolate";
|
|
33
32
|
source: string;
|
|
33
|
+
environment: "node" | "isolate";
|
|
34
34
|
sourceMap?: string | undefined;
|
|
35
35
|
}>>;
|
|
36
36
|
changedModules: z.ZodArray<z.ZodObject<{
|
|
@@ -40,13 +40,13 @@ export declare const appDefinitionConfig: z.ZodObject<{
|
|
|
40
40
|
environment: z.ZodUnion<[z.ZodLiteral<"isolate">, z.ZodLiteral<"node">]>;
|
|
41
41
|
}, "passthrough", z.ZodTypeAny, {
|
|
42
42
|
path: string;
|
|
43
|
-
environment: "node" | "isolate";
|
|
44
43
|
source: string;
|
|
44
|
+
environment: "node" | "isolate";
|
|
45
45
|
sourceMap?: string | undefined;
|
|
46
46
|
}, {
|
|
47
47
|
path: string;
|
|
48
|
-
environment: "node" | "isolate";
|
|
49
48
|
source: string;
|
|
49
|
+
environment: "node" | "isolate";
|
|
50
50
|
sourceMap?: string | undefined;
|
|
51
51
|
}>, "many">;
|
|
52
52
|
unchangedModuleHashes: z.ZodArray<z.ZodObject<{
|
|
@@ -66,21 +66,21 @@ export declare const appDefinitionConfig: z.ZodObject<{
|
|
|
66
66
|
}, "passthrough", z.ZodTypeAny, {
|
|
67
67
|
definition: {
|
|
68
68
|
path: string;
|
|
69
|
-
environment: "node" | "isolate";
|
|
70
69
|
source: string;
|
|
70
|
+
environment: "node" | "isolate";
|
|
71
71
|
sourceMap?: string | undefined;
|
|
72
72
|
} | null;
|
|
73
73
|
dependencies: string[];
|
|
74
74
|
schema: {
|
|
75
75
|
path: string;
|
|
76
|
-
environment: "node" | "isolate";
|
|
77
76
|
source: string;
|
|
77
|
+
environment: "node" | "isolate";
|
|
78
78
|
sourceMap?: string | undefined;
|
|
79
79
|
} | null;
|
|
80
80
|
changedModules: {
|
|
81
81
|
path: string;
|
|
82
|
-
environment: "node" | "isolate";
|
|
83
82
|
source: string;
|
|
83
|
+
environment: "node" | "isolate";
|
|
84
84
|
sourceMap?: string | undefined;
|
|
85
85
|
}[];
|
|
86
86
|
unchangedModuleHashes: {
|
|
@@ -92,21 +92,21 @@ export declare const appDefinitionConfig: z.ZodObject<{
|
|
|
92
92
|
}, {
|
|
93
93
|
definition: {
|
|
94
94
|
path: string;
|
|
95
|
-
environment: "node" | "isolate";
|
|
96
95
|
source: string;
|
|
96
|
+
environment: "node" | "isolate";
|
|
97
97
|
sourceMap?: string | undefined;
|
|
98
98
|
} | null;
|
|
99
99
|
dependencies: string[];
|
|
100
100
|
schema: {
|
|
101
101
|
path: string;
|
|
102
|
-
environment: "node" | "isolate";
|
|
103
102
|
source: string;
|
|
103
|
+
environment: "node" | "isolate";
|
|
104
104
|
sourceMap?: string | undefined;
|
|
105
105
|
} | null;
|
|
106
106
|
changedModules: {
|
|
107
107
|
path: string;
|
|
108
|
-
environment: "node" | "isolate";
|
|
109
108
|
source: string;
|
|
109
|
+
environment: "node" | "isolate";
|
|
110
110
|
sourceMap?: string | undefined;
|
|
111
111
|
}[];
|
|
112
112
|
unchangedModuleHashes: {
|
|
@@ -126,13 +126,13 @@ export declare const componentDefinitionConfig: z.ZodObject<{
|
|
|
126
126
|
environment: z.ZodUnion<[z.ZodLiteral<"isolate">, z.ZodLiteral<"node">]>;
|
|
127
127
|
}, "passthrough", z.ZodTypeAny, {
|
|
128
128
|
path: string;
|
|
129
|
-
environment: "node" | "isolate";
|
|
130
129
|
source: string;
|
|
130
|
+
environment: "node" | "isolate";
|
|
131
131
|
sourceMap?: string | undefined;
|
|
132
132
|
}, {
|
|
133
133
|
path: string;
|
|
134
|
-
environment: "node" | "isolate";
|
|
135
134
|
source: string;
|
|
135
|
+
environment: "node" | "isolate";
|
|
136
136
|
sourceMap?: string | undefined;
|
|
137
137
|
}>;
|
|
138
138
|
dependencies: z.ZodArray<z.ZodString, "many">;
|
|
@@ -143,13 +143,13 @@ export declare const componentDefinitionConfig: z.ZodObject<{
|
|
|
143
143
|
environment: z.ZodUnion<[z.ZodLiteral<"isolate">, z.ZodLiteral<"node">]>;
|
|
144
144
|
}, "passthrough", z.ZodTypeAny, {
|
|
145
145
|
path: string;
|
|
146
|
-
environment: "node" | "isolate";
|
|
147
146
|
source: string;
|
|
147
|
+
environment: "node" | "isolate";
|
|
148
148
|
sourceMap?: string | undefined;
|
|
149
149
|
}, {
|
|
150
150
|
path: string;
|
|
151
|
-
environment: "node" | "isolate";
|
|
152
151
|
source: string;
|
|
152
|
+
environment: "node" | "isolate";
|
|
153
153
|
sourceMap?: string | undefined;
|
|
154
154
|
}>>;
|
|
155
155
|
functions: z.ZodArray<z.ZodObject<{
|
|
@@ -159,34 +159,34 @@ export declare const componentDefinitionConfig: z.ZodObject<{
|
|
|
159
159
|
environment: z.ZodUnion<[z.ZodLiteral<"isolate">, z.ZodLiteral<"node">]>;
|
|
160
160
|
}, "passthrough", z.ZodTypeAny, {
|
|
161
161
|
path: string;
|
|
162
|
-
environment: "node" | "isolate";
|
|
163
162
|
source: string;
|
|
163
|
+
environment: "node" | "isolate";
|
|
164
164
|
sourceMap?: string | undefined;
|
|
165
165
|
}, {
|
|
166
166
|
path: string;
|
|
167
|
-
environment: "node" | "isolate";
|
|
168
167
|
source: string;
|
|
168
|
+
environment: "node" | "isolate";
|
|
169
169
|
sourceMap?: string | undefined;
|
|
170
170
|
}>, "many">;
|
|
171
171
|
udfServerVersion: z.ZodString;
|
|
172
172
|
}, "passthrough", z.ZodTypeAny, {
|
|
173
173
|
definition: {
|
|
174
174
|
path: string;
|
|
175
|
-
environment: "node" | "isolate";
|
|
176
175
|
source: string;
|
|
176
|
+
environment: "node" | "isolate";
|
|
177
177
|
sourceMap?: string | undefined;
|
|
178
178
|
};
|
|
179
179
|
dependencies: string[];
|
|
180
180
|
schema: {
|
|
181
181
|
path: string;
|
|
182
|
-
environment: "node" | "isolate";
|
|
183
182
|
source: string;
|
|
183
|
+
environment: "node" | "isolate";
|
|
184
184
|
sourceMap?: string | undefined;
|
|
185
185
|
} | null;
|
|
186
186
|
functions: {
|
|
187
187
|
path: string;
|
|
188
|
-
environment: "node" | "isolate";
|
|
189
188
|
source: string;
|
|
189
|
+
environment: "node" | "isolate";
|
|
190
190
|
sourceMap?: string | undefined;
|
|
191
191
|
}[];
|
|
192
192
|
definitionPath: string;
|
|
@@ -194,21 +194,21 @@ export declare const componentDefinitionConfig: z.ZodObject<{
|
|
|
194
194
|
}, {
|
|
195
195
|
definition: {
|
|
196
196
|
path: string;
|
|
197
|
-
environment: "node" | "isolate";
|
|
198
197
|
source: string;
|
|
198
|
+
environment: "node" | "isolate";
|
|
199
199
|
sourceMap?: string | undefined;
|
|
200
200
|
};
|
|
201
201
|
dependencies: string[];
|
|
202
202
|
schema: {
|
|
203
203
|
path: string;
|
|
204
|
-
environment: "node" | "isolate";
|
|
205
204
|
source: string;
|
|
205
|
+
environment: "node" | "isolate";
|
|
206
206
|
sourceMap?: string | undefined;
|
|
207
207
|
} | null;
|
|
208
208
|
functions: {
|
|
209
209
|
path: string;
|
|
210
|
-
environment: "node" | "isolate";
|
|
211
210
|
source: string;
|
|
211
|
+
environment: "node" | "isolate";
|
|
212
212
|
sourceMap?: string | undefined;
|
|
213
213
|
}[];
|
|
214
214
|
definitionPath: string;
|
|
@@ -8,13 +8,13 @@ export declare const moduleConfig: z.ZodObject<{
|
|
|
8
8
|
environment: z.ZodUnion<[z.ZodLiteral<"isolate">, z.ZodLiteral<"node">]>;
|
|
9
9
|
}, "passthrough", z.ZodTypeAny, {
|
|
10
10
|
path: string;
|
|
11
|
-
environment: "node" | "isolate";
|
|
12
11
|
source: string;
|
|
12
|
+
environment: "node" | "isolate";
|
|
13
13
|
sourceMap?: string | undefined;
|
|
14
14
|
}, {
|
|
15
15
|
path: string;
|
|
16
|
-
environment: "node" | "isolate";
|
|
17
16
|
source: string;
|
|
17
|
+
environment: "node" | "isolate";
|
|
18
18
|
sourceMap?: string | undefined;
|
|
19
19
|
}>;
|
|
20
20
|
export type ModuleConfig = z.infer<typeof moduleConfig>;
|