convex 1.42.0 → 1.42.2-alpha.0
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/CHANGELOG.md +7 -0
- package/dist/browser.bundle.js +24 -6
- package/dist/browser.bundle.js.map +2 -2
- package/dist/cjs/browser/simple_client.js +2 -2
- package/dist/cjs/browser/simple_client.js.map +2 -2
- package/dist/cjs/browser/sync/authentication_manager.js +21 -4
- package/dist/cjs/browser/sync/authentication_manager.js.map +2 -2
- package/dist/cjs/browser/sync/client.js +2 -1
- package/dist/cjs/browser/sync/client.js.map +2 -2
- package/dist/cjs/cli/dev.js +1 -0
- package/dist/cjs/cli/dev.js.map +2 -2
- package/dist/cjs/cli/generatedApi.js.map +1 -1
- package/dist/cjs/cli/lib/api.js.map +2 -2
- package/dist/cjs/cli/lib/typecheck.js +28 -10
- package/dist/cjs/cli/lib/typecheck.js.map +2 -2
- package/dist/cjs/cli/lib/utils/utils.js +4 -12
- package/dist/cjs/cli/lib/utils/utils.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 +1 -1
- package/dist/cjs/react/client.js.map +2 -2
- package/dist/cjs/react-clerk/ConvexProviderWithClerk.js +2 -1
- package/dist/cjs/react-clerk/ConvexProviderWithClerk.js.map +2 -2
- package/dist/cjs/server/database.js.map +1 -1
- package/dist/cjs/server/impl/meta_impl.js +2 -2
- package/dist/cjs/server/impl/meta_impl.js.map +2 -2
- package/dist/cjs/server/impl/query_impl.js.map +2 -2
- package/dist/cjs/server/impl/registration_impl.js +0 -2
- package/dist/cjs/server/impl/registration_impl.js.map +2 -2
- package/dist/cjs/server/meta.js.map +1 -1
- package/dist/cjs/server/query.js.map +1 -1
- package/dist/cjs/server/registration.js.map +1 -1
- package/dist/cjs/server/schema.js.map +1 -1
- package/dist/cjs-types/browser/simple_client.d.ts +1 -2
- package/dist/cjs-types/browser/simple_client.d.ts.map +1 -1
- package/dist/cjs-types/browser/sync/authentication_manager.d.ts +2 -0
- package/dist/cjs-types/browser/sync/authentication_manager.d.ts.map +1 -1
- package/dist/cjs-types/browser/sync/client.d.ts +16 -0
- package/dist/cjs-types/browser/sync/client.d.ts.map +1 -1
- package/dist/cjs-types/cli/dev.d.ts.map +1 -1
- package/dist/cjs-types/cli/dev.test.d.ts +2 -0
- package/dist/cjs-types/cli/dev.test.d.ts.map +1 -0
- package/dist/cjs-types/cli/generatedApi.d.ts +0 -1
- package/dist/cjs-types/cli/generatedApi.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/api.d.ts +0 -1
- package/dist/cjs-types/cli/lib/api.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/utils/utils.d.ts.map +1 -1
- package/dist/cjs-types/index.d.ts +1 -1
- package/dist/cjs-types/index.d.ts.map +1 -1
- package/dist/cjs-types/react/client.d.ts.map +1 -1
- package/dist/cjs-types/react/client_provided_base_client.test.d.ts +2 -0
- package/dist/cjs-types/react/client_provided_base_client.test.d.ts.map +1 -0
- package/dist/cjs-types/react-clerk/ConvexProviderWithClerk.d.ts +1 -0
- package/dist/cjs-types/react-clerk/ConvexProviderWithClerk.d.ts.map +1 -1
- package/dist/cjs-types/server/database.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/query_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/registration_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/meta.d.ts.map +1 -1
- package/dist/cjs-types/server/query.d.ts.map +1 -1
- package/dist/cjs-types/server/registration.d.ts.map +1 -1
- package/dist/cjs-types/server/schema.d.ts.map +1 -1
- package/dist/cli.bundle.cjs +58 -28
- package/dist/cli.bundle.cjs.map +3 -3
- package/dist/esm/browser/simple_client.js +5 -3
- package/dist/esm/browser/simple_client.js.map +2 -2
- package/dist/esm/browser/sync/authentication_manager.js +21 -4
- package/dist/esm/browser/sync/authentication_manager.js.map +2 -2
- package/dist/esm/browser/sync/client.js +2 -1
- package/dist/esm/browser/sync/client.js.map +2 -2
- package/dist/esm/cli/dev.js +3 -1
- package/dist/esm/cli/dev.js.map +2 -2
- package/dist/esm/cli/lib/api.js.map +2 -2
- package/dist/esm/cli/lib/typecheck.js +28 -10
- package/dist/esm/cli/lib/typecheck.js.map +3 -3
- package/dist/esm/cli/lib/utils/utils.js +4 -12
- package/dist/esm/cli/lib/utils/utils.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 +1 -1
- package/dist/esm/react/client.js.map +2 -2
- package/dist/esm/react-clerk/ConvexProviderWithClerk.js +2 -1
- package/dist/esm/react-clerk/ConvexProviderWithClerk.js.map +2 -2
- package/dist/esm/server/impl/meta_impl.js +2 -2
- package/dist/esm/server/impl/meta_impl.js.map +2 -2
- package/dist/esm/server/impl/query_impl.js.map +2 -2
- package/dist/esm/server/impl/registration_impl.js +0 -2
- package/dist/esm/server/impl/registration_impl.js.map +2 -2
- package/dist/esm/server/schema.js.map +1 -1
- package/dist/esm-types/browser/simple_client.d.ts +1 -2
- package/dist/esm-types/browser/simple_client.d.ts.map +1 -1
- package/dist/esm-types/browser/sync/authentication_manager.d.ts +2 -0
- package/dist/esm-types/browser/sync/authentication_manager.d.ts.map +1 -1
- package/dist/esm-types/browser/sync/client.d.ts +16 -0
- package/dist/esm-types/browser/sync/client.d.ts.map +1 -1
- package/dist/esm-types/cli/dev.d.ts.map +1 -1
- package/dist/esm-types/cli/dev.test.d.ts +2 -0
- package/dist/esm-types/cli/dev.test.d.ts.map +1 -0
- package/dist/esm-types/cli/generatedApi.d.ts +0 -1
- package/dist/esm-types/cli/generatedApi.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/api.d.ts +0 -1
- package/dist/esm-types/cli/lib/api.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/utils/utils.d.ts.map +1 -1
- package/dist/esm-types/index.d.ts +1 -1
- package/dist/esm-types/index.d.ts.map +1 -1
- package/dist/esm-types/react/client.d.ts.map +1 -1
- package/dist/esm-types/react/client_provided_base_client.test.d.ts +2 -0
- package/dist/esm-types/react/client_provided_base_client.test.d.ts.map +1 -0
- package/dist/esm-types/react-clerk/ConvexProviderWithClerk.d.ts +1 -0
- package/dist/esm-types/react-clerk/ConvexProviderWithClerk.d.ts.map +1 -1
- package/dist/esm-types/server/database.d.ts.map +1 -1
- package/dist/esm-types/server/impl/query_impl.d.ts.map +1 -1
- package/dist/esm-types/server/impl/registration_impl.d.ts.map +1 -1
- package/dist/esm-types/server/meta.d.ts.map +1 -1
- package/dist/esm-types/server/query.d.ts.map +1 -1
- package/dist/esm-types/server/registration.d.ts.map +1 -1
- package/dist/esm-types/server/schema.d.ts.map +1 -1
- package/dist/react.bundle.js +25 -7
- package/dist/react.bundle.js.map +2 -2
- package/package.json +2 -2
- package/src/browser/simple_client.ts +12 -10
- package/src/browser/sync/authentication_manager.ts +42 -14
- package/src/browser/sync/client.ts +17 -0
- package/src/cli/dev.test.ts +157 -0
- package/src/cli/dev.ts +7 -0
- package/src/cli/generatedApi.ts +0 -1
- package/src/cli/lib/api.ts +0 -1
- package/src/cli/lib/config.test.ts +1 -4
- package/src/cli/lib/typecheck.ts +26 -10
- package/src/cli/lib/utils/utils.ts +4 -12
- package/src/index.ts +1 -1
- package/src/react/ConvexAuthState.test.tsx +145 -0
- package/src/react/client.ts +23 -6
- package/src/react/client_provided_base_client.test.tsx +56 -0
- package/src/react-clerk/ConvexProviderWithClerk.tsx +3 -1
- package/src/server/database.ts +6 -4
- package/src/server/impl/meta_impl.ts +2 -2
- package/src/server/impl/query_impl.ts +1 -3
- package/src/server/impl/registration_impl.ts +0 -2
- package/src/server/meta.ts +10 -0
- package/src/server/query.ts +9 -6
- package/src/server/registration.ts +10 -10
- package/src/server/schema.ts +3 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/server/impl/registration_impl.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n ConvexError,\n convexToJson,\n GenericValidator,\n jsonToConvex,\n v,\n Validator,\n Value,\n} from \"../../values/index.js\";\nimport { GenericDataModel } from \"../data_model.js\";\nimport {\n ActionBuilder,\n DefaultFunctionArgs,\n FunctionVisibility,\n GenericActionCtx,\n GenericMutationCtx,\n GenericQueryCtx,\n MutationBuilder,\n PublicHttpAction,\n QueryBuilder,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"../registration.js\";\nimport { setupActionCalls } from \"./actions_impl.js\";\nimport { setupActionVectorSearch } from \"./vector_search_impl.js\";\nimport { setupAuth } from \"./authentication_impl.js\";\nimport { setupReader, setupWriter } from \"./database_impl.js\";\nimport { QueryImpl, QueryInitializerImpl } from \"./query_impl.js\";\nimport {\n setupActionScheduler,\n setupMutationScheduler,\n} from \"./scheduler_impl.js\";\nimport {\n setupStorageActionWriter,\n setupStorageReader,\n setupStorageWriter,\n} from \"./storage_impl.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { asObjectValidator } from \"../../values/validator.js\";\nimport { getFunctionAddress } from \"../components/paths.js\";\nimport {\n setupQueryMeta,\n setupMutationMeta,\n setupActionMeta,\n} from \"./meta_impl.js\";\n\nasync function invokeMutation<\n F extends (ctx: GenericMutationCtx<GenericDataModel>, ...args: any) => any,\n>(func: F, argsStr: string, visibility: FunctionVisibility) {\n // TODO(presley): Change the function signature and propagate the requestId from Rust.\n // Ok, to mock it out for now, since queries are only running in V8.\n const requestId = \"\";\n const args = jsonToConvex(JSON.parse(argsStr));\n const mutationCtx = {\n db: setupWriter(),\n auth: setupAuth(requestId),\n storage: setupStorageWriter(requestId),\n scheduler: setupMutationScheduler(),\n meta: setupMutationMeta(visibility),\n\n runQuery: (reference: any, args?: any, options?: any) =>\n options?.useStaleSnapshot\n ? runUdf(\"snapshotQuery\", reference, args, options?.transactionLimits)\n : runUdf(\"query\", reference, args, options?.transactionLimits),\n runMutation: (reference: any, args?: any, options?: any) =>\n runUdf(\"mutation\", reference, args, options?.transactionLimits),\n };\n const result = await invokeFunction(func, mutationCtx, args as any);\n validateReturnValue(result);\n return JSON.stringify(convexToJson(result === undefined ? null : result));\n}\n\nexport function validateReturnValue(v: any) {\n if (v instanceof QueryInitializerImpl || v instanceof QueryImpl) {\n throw new Error(\n \"Return value is a Query. Results must be retrieved with `.collect()`, `.take(n), `.unique()`, or `.first()`.\",\n );\n }\n}\n\nexport async function invokeFunction<\n Ctx,\n Args extends any[],\n F extends (ctx: Ctx, ...args: Args) => any,\n>(func: F, ctx: Ctx, args: Args) {\n let result;\n try {\n result = await Promise.resolve(func(ctx, ...args));\n } catch (thrown: unknown) {\n throw serializeConvexErrorData(thrown);\n }\n return result;\n}\n\nfunction dontCallDirectly(\n funcType: string,\n handler: (ctx: any, args: any) => any,\n): unknown {\n return (ctx: any, args: any) => {\n globalThis.console.warn(\n \"Convex functions should not directly call other Convex functions. Consider calling a helper function instead. \" +\n `e.g. \\`export const foo = ${funcType}(...); await foo(ctx);\\` is not supported. ` +\n \"See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code\",\n );\n return handler(ctx, args);\n };\n}\n\n// Keep in sync with node executor\nfunction serializeConvexErrorData(thrown: unknown) {\n if (\n typeof thrown === \"object\" &&\n thrown !== null &&\n Symbol.for(\"ConvexError\") in thrown\n ) {\n const error = thrown as ConvexError<any>;\n error.data = JSON.stringify(\n convexToJson(error.data === undefined ? null : error.data),\n );\n (error as any).ConvexErrorSymbol = Symbol.for(\"ConvexError\");\n return error;\n } else {\n return thrown;\n }\n}\n\n/**\n * Guard against Convex functions accidentally getting included in a browser bundle.\n * Convex functions may include secret logic or credentials that should not be\n * send to untrusted clients (browsers).\n */\nfunction assertNotBrowser() {\n if (\n typeof window === \"undefined\" ||\n (window as any).__convexAllowFunctionsInBrowser\n ) {\n return;\n }\n // JSDom doesn't count, developers are allowed to use JSDom in Convex functions.\n const isRealBrowser =\n Object.getOwnPropertyDescriptor(globalThis, \"window\")\n ?.get?.toString()\n .includes(\"[native code]\") ?? false;\n if (isRealBrowser) {\n // eslint-disable-next-line no-console\n console.error(\n \"Convex functions should not be imported in the browser. This will throw an error in future versions of `convex`. If this is a false negative, please report it to Convex support.\",\n );\n }\n}\n\ntype FunctionDefinition =\n | ((ctx: any, args: DefaultFunctionArgs) => any)\n | {\n args?: GenericValidator | Record<string, GenericValidator>;\n returns?: GenericValidator | Record<string, GenericValidator>;\n handler: (ctx: any, args: DefaultFunctionArgs) => any;\n };\n\nfunction strictReplacer(key: string, value: any) {\n if (value === undefined) {\n throw new Error(\n `A validator is undefined for field \"${key}\". ` +\n `This is often caused by circular imports. ` +\n `See https://docs.convex.dev/error#undefined-validator for details.`,\n );\n }\n return value;\n}\nfunction exportArgs(functionDefinition: FunctionDefinition) {\n return () => {\n let args: GenericValidator = v.any();\n if (\n typeof functionDefinition === \"object\" &&\n functionDefinition.args !== undefined\n ) {\n args = asObjectValidator(functionDefinition.args);\n }\n return JSON.stringify(args.json, strictReplacer);\n };\n}\n\nfunction exportReturns(functionDefinition: FunctionDefinition) {\n return () => {\n let returns: Validator<any, any, any> | undefined;\n if (\n typeof functionDefinition === \"object\" &&\n functionDefinition.returns !== undefined\n ) {\n returns = asObjectValidator(functionDefinition.returns);\n }\n return JSON.stringify(returns ? returns.json : null, strictReplacer);\n };\n}\n\n/**\n * Define a mutation in this Convex app's public API.\n *\n * You should generally use the `mutation` function from\n * `\"./_generated/server\"`.\n *\n * Mutations can read from and write to the database, and are accessible from\n * the client. They run **transactionally**, all database reads and writes\n * within a single mutation are atomic and isolated from other mutations.\n *\n * @example\n * ```typescript\n * import { mutation } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const createTask = mutation({\n * args: { text: v.string() },\n * returns: v.id(\"tasks\"),\n * handler: async (ctx, args) => {\n * const taskId = await ctx.db.insert(\"tasks\", {\n * text: args.text,\n * completed: false,\n * });\n * return taskId;\n * },\n * });\n * ```\n *\n * **Best practice:** Always include `args` and `returns` validators on all\n * mutations. If the function doesn't return a value, use `returns: v.null()`.\n * Argument validation is critical for security since public mutations are\n * exposed to the internet.\n *\n * **Common mistake:** Mutations cannot call third-party APIs or use `fetch`.\n * They must be deterministic. Use actions for external API calls.\n *\n * **Common mistake:** Do not use `mutation` for sensitive internal functions\n * that should not be called by clients. Use `internalMutation` instead.\n *\n * @param func - The mutation function. It receives a {@link GenericMutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/mutation-functions\n * @public\n */\nexport const mutationGeneric: MutationBuilder<any, \"public\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericMutationCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"mutation\", handler) as RegisteredMutation<\n \"public\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isMutation = true;\n func.isPublic = true;\n func.invokeMutation = (argsStr) => invokeMutation(handler, argsStr, \"public\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as MutationBuilder<any, \"public\">;\n\n/**\n * Define a mutation that is only accessible from other Convex functions (but not from the client).\n *\n * You should generally use the `internalMutation` function from\n * `\"./_generated/server\"`.\n *\n * Internal mutations can read from and write to the database but are **not**\n * exposed as part of your app's public API. They can only be called by other\n * Convex functions using `ctx.runMutation` or by the scheduler. Like public\n * mutations, they run transactionally.\n *\n * @example\n * ```typescript\n * import { internalMutation } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * // This mutation can only be called from other Convex functions:\n * export const markTaskCompleted = internalMutation({\n * args: { taskId: v.id(\"tasks\") },\n * returns: v.null(),\n * handler: async (ctx, args) => {\n * await ctx.db.patch(\"tasks\", args.taskId, { completed: true });\n * return null;\n * },\n * });\n * ```\n *\n * **Best practice:** Use `internalMutation` for any mutation that should not\n * be directly callable by clients, such as write-back functions from actions\n * or scheduled background work. Reference it via the `internal` object:\n * `await ctx.runMutation(internal.myModule.markTaskCompleted, { taskId })`.\n *\n * @param func - The mutation function. It receives a {@link GenericMutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/internal-functions\n * @public\n */\nexport const internalMutationGeneric: MutationBuilder<any, \"internal\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericMutationCtx<any>, args: any) => any;\n const func = dontCallDirectly(\n \"internalMutation\",\n handler,\n ) as RegisteredMutation<\"internal\", any, any>;\n\n assertNotBrowser();\n func.isMutation = true;\n func.isInternal = true;\n func.invokeMutation = (argsStr) =>\n invokeMutation(handler, argsStr, \"internal\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as MutationBuilder<any, \"internal\">;\n\nasync function invokeQuery<\n F extends (ctx: GenericQueryCtx<GenericDataModel>, ...args: any) => any,\n>(func: F, argsStr: string, visibility: FunctionVisibility) {\n // TODO(presley): Change the function signature and propagate the requestId from Rust.\n // Ok, to mock it out for now, since queries are only running in V8.\n const requestId = \"\";\n const args = jsonToConvex(JSON.parse(argsStr));\n const queryCtx = {\n db: setupReader(),\n auth: setupAuth(requestId),\n storage: setupStorageReader(requestId),\n meta: setupQueryMeta(visibility),\n runQuery: (reference: any, args?: any, options?: any) => {\n if (options?.useStaleSnapshot) {\n throw new Error(\n \"`useStaleSnapshot` is only supported in mutations, not queries.\",\n );\n }\n return runUdf(\"query\", reference, args, options?.transactionLimits);\n },\n };\n const result = await invokeFunction(func, queryCtx, args as any);\n validateReturnValue(result);\n return JSON.stringify(convexToJson(result === undefined ? null : result));\n}\n\n/**\n * Define a query in this Convex app's public API.\n *\n * You should generally use the `query` function from\n * `\"./_generated/server\"`.\n *\n * Queries can read from the database and are accessible from the client. They\n * are **reactive**, when used with `useQuery` in React, the component\n * automatically re-renders whenever the underlying data changes. Queries\n * cannot modify the database.\n * Query results are automatically cached by the Convex client and kept\n * consistent via WebSocket subscriptions.\n *\n *\n * @example\n * ```typescript\n * import { query } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const listTasks = query({\n * args: { completed: v.optional(v.boolean()) },\n * returns: v.array(v.object({\n * _id: v.id(\"tasks\"),\n * _creationTime: v.number(),\n * text: v.string(),\n * completed: v.boolean(),\n * })),\n * handler: async (ctx, args) => {\n * if (args.completed !== undefined) {\n * return await ctx.db\n * .query(\"tasks\")\n * .withIndex(\"by_completed\", (q) => q.eq(\"completed\", args.completed))\n * .collect();\n * }\n * return await ctx.db.query(\"tasks\").collect();\n * },\n * });\n * ```\n *\n * **Best practice:** Always include `args` and `returns` validators. Use\n * `.withIndex()` instead of `.filter()` for efficient database queries.\n * Queries should be fast since they run on every relevant data change.\n *\n * **Common mistake:** Queries are pure reads, they cannot write to the\n * database, call external APIs, or schedule functions. Use actions for HTTP\n * calls and mutations for database writes and scheduling.\n *\n * @param func - The query function. It receives a {@link GenericQueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/query-functions\n * @public\n */\nexport const queryGeneric: QueryBuilder<any, \"public\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericQueryCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"query\", handler) as RegisteredQuery<\n \"public\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isQuery = true;\n func.isPublic = true;\n func.invokeQuery = (argsStr) => invokeQuery(handler, argsStr, \"public\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as QueryBuilder<any, \"public\">;\n\n/**\n * Define a query that is only accessible from other Convex functions (but not from the client).\n *\n * You should generally use the `internalQuery` function from\n * `\"./_generated/server\"`.\n *\n * Internal queries can read from the database but are **not** exposed as part\n * of your app's public API. They can only be called by other Convex functions\n * using `ctx.runQuery`. This is useful for loading data in actions or for\n * helper queries that shouldn't be client-facing.\n *\n * @example\n * ```typescript\n * import { internalQuery } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * // Only callable from other Convex functions:\n * export const getUser = internalQuery({\n * args: { userId: v.id(\"users\") },\n * returns: v.union(\n * v.object({\n * _id: v.id(\"users\"),\n * _creationTime: v.number(),\n * name: v.string(),\n * email: v.string(),\n * }),\n * v.null(),\n * ),\n * handler: async (ctx, args) => {\n * return await ctx.db.get(\"users\", args.userId);\n * },\n * });\n * ```\n *\n * **Best practice:** Use `internalQuery` for data-loading in actions via\n * `ctx.runQuery(internal.myModule.getUser, { userId })`.\n *\n * @param func - The query function. It receives a {@link GenericQueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/internal-functions\n * @public\n */\nexport const internalQueryGeneric: QueryBuilder<any, \"internal\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericQueryCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"internalQuery\", handler) as RegisteredQuery<\n \"internal\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isQuery = true;\n func.isInternal = true;\n func.invokeQuery = (argsStr) =>\n invokeQuery(handler as any, argsStr, \"internal\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as QueryBuilder<any, \"internal\">;\n\nasync function invokeAction<\n F extends (ctx: GenericActionCtx<GenericDataModel>, ...args: any) => any,\n>(func: F, requestId: string, argsStr: string, visibility: FunctionVisibility) {\n (globalThis as any).Convex?.setupPerformance?.();\n const args = jsonToConvex(JSON.parse(argsStr));\n const calls = setupActionCalls(requestId);\n const ctx = {\n ...calls,\n auth: setupAuth(requestId),\n scheduler: setupActionScheduler(requestId),\n storage: setupStorageActionWriter(requestId),\n vectorSearch: setupActionVectorSearch(requestId) as any,\n meta: setupActionMeta(visibility),\n };\n const result = await invokeFunction(func, ctx, args as any);\n return JSON.stringify(convexToJson(result === undefined ? null : result));\n}\n\n/**\n * Define an action in this Convex app's public API.\n *\n * Actions can call third-party APIs, use Node.js libraries, and perform other\n * side effects. Unlike queries and mutations, actions do **not** have direct\n * database access (`ctx.db` is not available). Instead, use `ctx.runQuery`\n * and `ctx.runMutation` to read and write data.\n *\n * You should generally use the `action` function from\n * `\"./_generated/server\"`.\n *\n * Actions are accessible from the client and run outside of the database\n * transaction, so they are not atomic. They are best for integrating with\n * external services.\n *\n * @example\n * ```typescript\n * // Add \"use node\"; at the top of the file if using Node.js built-in modules.\n * import { action } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n * import { internal } from \"./_generated/api\";\n *\n * export const generateSummary = action({\n * args: { text: v.string() },\n * returns: v.string(),\n * handler: async (ctx, args) => {\n * // Call an external API:\n * const response = await fetch(\"https://api.example.com/summarize\", {\n * method: \"POST\",\n * body: JSON.stringify({ text: args.text }),\n * });\n * const { summary } = await response.json();\n *\n * // Write results back via a mutation:\n * await ctx.runMutation(internal.myModule.saveSummary, {\n * text: args.text,\n * summary,\n * });\n *\n * return summary;\n * },\n * });\n * ```\n *\n * **Best practice:** Minimize the number of `ctx.runQuery` and\n * `ctx.runMutation` calls from actions. Each call is a separate transaction,\n * so splitting logic across multiple calls introduces the risk of race\n * conditions. Try to batch reads/writes into single query/mutation calls.\n *\n * **`\"use node\"` runtime:** Actions run in Convex's default JavaScript\n * runtime, which supports `fetch` and most NPM packages. Only add\n * `\"use node\";` at the top of the file if a third-party library specifically\n * requires Node.js built-in APIs, it is a last resort, not the default.\n * Node.js actions have slower cold starts, and **only actions can be defined\n * in `\"use node\"` files** (no queries or mutations), so prefer the default\n * runtime whenever possible.\n *\n * **Common mistake:** Do not try to access `ctx.db` in an action, it is\n * not available. Use `ctx.runQuery` and `ctx.runMutation` instead.\n *\n * @param func - The function. It receives a {@link GenericActionCtx} as its first argument.\n * @returns The wrapped function. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/actions\n * @public\n */\nexport const actionGeneric: ActionBuilder<any, \"public\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericActionCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"action\", handler) as RegisteredAction<\n \"public\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isAction = true;\n func.isPublic = true;\n func.invokeAction = (requestId, argsStr) =>\n invokeAction(handler, requestId, argsStr, \"public\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as ActionBuilder<any, \"public\">;\n\n/**\n * Define an action that is only accessible from other Convex functions (but not from the client).\n *\n * You should generally use the `internalAction` function from\n * `\"./_generated/server\"`.\n *\n * Internal actions behave like public actions (they can call external APIs and\n * use Node.js libraries) but are **not** exposed in your app's public API. They\n * can only be called by other Convex functions using `ctx.runAction` or via the\n * scheduler.\n *\n * @example\n * ```typescript\n * import { internalAction } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const sendEmail = internalAction({\n * args: { to: v.string(), subject: v.string(), body: v.string() },\n * returns: v.null(),\n * handler: async (ctx, args) => {\n * // Call an external email service (fetch works in the default runtime):\n * await fetch(\"https://api.email-service.com/send\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(args),\n * });\n * return null;\n * },\n * });\n * ```\n *\n * **Best practice:** Use `internalAction` for background work scheduled from\n * mutations: `await ctx.scheduler.runAfter(0, internal.myModule.sendEmail, { ... })`.\n * Only use `ctx.runAction` from another action if you need to cross runtimes\n * (e.g., default Convex runtime to Node.js). Otherwise, extract shared code\n * into a helper function.\n *\n * **`\"use node\"` runtime:** Only add `\"use node\";` at the top of the file\n * as a last resort when a third-party library requires Node.js APIs. Node.js\n * actions have slower cold starts, and **only actions can be defined in\n * `\"use node\"` files** (no queries or mutations).\n *\n * @param func - The function. It receives a {@link GenericActionCtx} as its first argument.\n * @returns The wrapped function. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/internal-functions\n * @public\n */\nexport const internalActionGeneric: ActionBuilder<any, \"internal\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericActionCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"internalAction\", handler) as RegisteredAction<\n \"internal\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isAction = true;\n func.isInternal = true;\n func.invokeAction = (requestId, argsStr) =>\n invokeAction(handler, requestId, argsStr, \"internal\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as ActionBuilder<any, \"internal\">;\n\nasync function invokeHttpAction<\n F extends (ctx: GenericActionCtx<GenericDataModel>, request: Request) => any,\n>(func: F, request: Request) {\n (globalThis as any).Convex?.setupPerformance?.();\n // TODO(presley): Change the function signature and propagate the requestId from Rust.\n // Ok, to mock it out for now, since http endpoints are only running in V8.\n const requestId = \"\";\n const calls = setupActionCalls(requestId);\n const ctx = {\n ...calls,\n auth: setupAuth(requestId),\n storage: setupStorageActionWriter(requestId),\n scheduler: setupActionScheduler(requestId),\n vectorSearch: setupActionVectorSearch(requestId) as any,\n meta: setupActionMeta(\"public\"),\n };\n return await invokeFunction(func, ctx, [request]);\n}\n\n/**\n * Define a Convex HTTP action.\n *\n * HTTP actions handle raw HTTP requests and return HTTP responses. They are\n * registered by routing URL paths to them in `convex/http.ts` using\n * {@link HttpRouter}. Like regular actions, they can call external APIs and\n * use `ctx.runQuery` / `ctx.runMutation` but do not have direct `ctx.db` access.\n *\n * @example\n * ```typescript\n * // convex/http.ts\n * import { httpRouter } from \"convex/server\";\n * import { httpAction } from \"./_generated/server\";\n *\n * const http = httpRouter();\n *\n * http.route({\n * path: \"/api/webhook\",\n * method: \"POST\",\n * handler: httpAction(async (ctx, request) => {\n * const body = await request.json();\n * // Process the webhook payload...\n * return new Response(JSON.stringify({ ok: true }), {\n * status: 200,\n * headers: { \"Content-Type\": \"application/json\" },\n * });\n * }),\n * });\n *\n * export default http;\n * ```\n *\n * **Best practice:** HTTP actions are registered at the exact path specified.\n * For example, `path: \"/api/webhook\"` registers at `/api/webhook`.\n *\n * @param func - The function. It receives a {@link GenericActionCtx} as its first argument, and a `Request` object\n * as its second.\n * @returns The wrapped function. Route a URL path to this function in `convex/http.ts`.\n *\n * @see https://docs.convex.dev/functions/http-actions\n * @public\n */\nexport const httpActionGeneric = (\n func: (\n ctx: GenericActionCtx<GenericDataModel>,\n request: Request,\n ) => Promise<Response>,\n): PublicHttpAction => {\n const q = dontCallDirectly(\"httpAction\", func) as PublicHttpAction;\n assertNotBrowser();\n q.isHttp = true;\n q.invokeHttpAction = (request) => invokeHttpAction(func as any, request);\n q._handler = func;\n return q;\n};\n\nasync function runUdf(\n udfType: \"query\" | \"mutation\" | \"snapshotQuery\",\n f: any,\n args?: Record<string, Value>,\n transactionLimits?: Record<string, number>,\n): Promise<any> {\n const queryArgs = parseArgs(args);\n const syscallArgs: Record<string, any> = {\n udfType,\n args: convexToJson(queryArgs),\n ...getFunctionAddress(f),\n };\n if (transactionLimits) {\n syscallArgs.transactionLimits = transactionLimits;\n }\n const result = await performAsyncSyscall(\"1.0/runUdf\", syscallArgs);\n return jsonToConvex(result);\n}\n"],
|
|
5
|
-
"mappings": "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
|
|
4
|
+
"sourcesContent": ["import {\n ConvexError,\n convexToJson,\n GenericValidator,\n jsonToConvex,\n v,\n Validator,\n Value,\n} from \"../../values/index.js\";\nimport { GenericDataModel } from \"../data_model.js\";\nimport {\n ActionBuilder,\n DefaultFunctionArgs,\n FunctionVisibility,\n GenericActionCtx,\n GenericMutationCtx,\n GenericQueryCtx,\n MutationBuilder,\n PublicHttpAction,\n QueryBuilder,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"../registration.js\";\nimport { setupActionCalls } from \"./actions_impl.js\";\nimport { setupActionVectorSearch } from \"./vector_search_impl.js\";\nimport { setupAuth } from \"./authentication_impl.js\";\nimport { setupReader, setupWriter } from \"./database_impl.js\";\nimport { QueryImpl, QueryInitializerImpl } from \"./query_impl.js\";\nimport {\n setupActionScheduler,\n setupMutationScheduler,\n} from \"./scheduler_impl.js\";\nimport {\n setupStorageActionWriter,\n setupStorageReader,\n setupStorageWriter,\n} from \"./storage_impl.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\nimport { asObjectValidator } from \"../../values/validator.js\";\nimport { getFunctionAddress } from \"../components/paths.js\";\nimport {\n setupQueryMeta,\n setupMutationMeta,\n setupActionMeta,\n} from \"./meta_impl.js\";\n\nasync function invokeMutation<\n F extends (ctx: GenericMutationCtx<GenericDataModel>, ...args: any) => any,\n>(func: F, argsStr: string, visibility: FunctionVisibility) {\n // TODO(presley): Change the function signature and propagate the requestId from Rust.\n // Ok, to mock it out for now, since queries are only running in V8.\n const requestId = \"\";\n const args = jsonToConvex(JSON.parse(argsStr));\n const mutationCtx = {\n db: setupWriter(),\n auth: setupAuth(requestId),\n storage: setupStorageWriter(requestId),\n scheduler: setupMutationScheduler(),\n meta: setupMutationMeta(visibility),\n\n runQuery: (reference: any, args?: any, options?: any) =>\n options?.useStaleSnapshot\n ? runUdf(\"snapshotQuery\", reference, args, options?.transactionLimits)\n : runUdf(\"query\", reference, args, options?.transactionLimits),\n runMutation: (reference: any, args?: any, options?: any) =>\n runUdf(\"mutation\", reference, args, options?.transactionLimits),\n };\n const result = await invokeFunction(func, mutationCtx, args as any);\n validateReturnValue(result);\n return JSON.stringify(convexToJson(result === undefined ? null : result));\n}\n\nexport function validateReturnValue(v: any) {\n if (v instanceof QueryInitializerImpl || v instanceof QueryImpl) {\n throw new Error(\n \"Return value is a Query. Results must be retrieved with `.collect()`, `.take(n), `.unique()`, or `.first()`.\",\n );\n }\n}\n\nexport async function invokeFunction<\n Ctx,\n Args extends any[],\n F extends (ctx: Ctx, ...args: Args) => any,\n>(func: F, ctx: Ctx, args: Args) {\n let result;\n try {\n result = await Promise.resolve(func(ctx, ...args));\n } catch (thrown: unknown) {\n throw serializeConvexErrorData(thrown);\n }\n return result;\n}\n\nfunction dontCallDirectly(\n funcType: string,\n handler: (ctx: any, args: any) => any,\n): unknown {\n return (ctx: any, args: any) => {\n globalThis.console.warn(\n \"Convex functions should not directly call other Convex functions. Consider calling a helper function instead. \" +\n `e.g. \\`export const foo = ${funcType}(...); await foo(ctx);\\` is not supported. ` +\n \"See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code\",\n );\n return handler(ctx, args);\n };\n}\n\n// Keep in sync with node executor\nfunction serializeConvexErrorData(thrown: unknown) {\n if (\n typeof thrown === \"object\" &&\n thrown !== null &&\n Symbol.for(\"ConvexError\") in thrown\n ) {\n const error = thrown as ConvexError<any>;\n error.data = JSON.stringify(\n convexToJson(error.data === undefined ? null : error.data),\n );\n (error as any).ConvexErrorSymbol = Symbol.for(\"ConvexError\");\n return error;\n } else {\n return thrown;\n }\n}\n\n/**\n * Guard against Convex functions accidentally getting included in a browser bundle.\n * Convex functions may include secret logic or credentials that should not be\n * send to untrusted clients (browsers).\n */\nfunction assertNotBrowser() {\n if (\n typeof window === \"undefined\" ||\n (window as any).__convexAllowFunctionsInBrowser\n ) {\n return;\n }\n // JSDom doesn't count, developers are allowed to use JSDom in Convex functions.\n const isRealBrowser =\n Object.getOwnPropertyDescriptor(globalThis, \"window\")\n ?.get?.toString()\n .includes(\"[native code]\") ?? false;\n if (isRealBrowser) {\n // eslint-disable-next-line no-console\n console.error(\n \"Convex functions should not be imported in the browser. This will throw an error in future versions of `convex`. If this is a false negative, please report it to Convex support.\",\n );\n }\n}\n\ntype FunctionDefinition =\n | ((ctx: any, args: DefaultFunctionArgs) => any)\n | {\n args?: GenericValidator | Record<string, GenericValidator>;\n returns?: GenericValidator | Record<string, GenericValidator>;\n handler: (ctx: any, args: DefaultFunctionArgs) => any;\n };\n\nfunction strictReplacer(key: string, value: any) {\n if (value === undefined) {\n throw new Error(\n `A validator is undefined for field \"${key}\". ` +\n `This is often caused by circular imports. ` +\n `See https://docs.convex.dev/error#undefined-validator for details.`,\n );\n }\n return value;\n}\nfunction exportArgs(functionDefinition: FunctionDefinition) {\n return () => {\n let args: GenericValidator = v.any();\n if (\n typeof functionDefinition === \"object\" &&\n functionDefinition.args !== undefined\n ) {\n args = asObjectValidator(functionDefinition.args);\n }\n return JSON.stringify(args.json, strictReplacer);\n };\n}\n\nfunction exportReturns(functionDefinition: FunctionDefinition) {\n return () => {\n let returns: Validator<any, any, any> | undefined;\n if (\n typeof functionDefinition === \"object\" &&\n functionDefinition.returns !== undefined\n ) {\n returns = asObjectValidator(functionDefinition.returns);\n }\n return JSON.stringify(returns ? returns.json : null, strictReplacer);\n };\n}\n\n/**\n * Define a mutation in this Convex app's public API.\n *\n * You should generally use the `mutation` function from\n * `\"./_generated/server\"`.\n *\n * Mutations can read from and write to the database, and are accessible from\n * the client. They run **transactionally**, all database reads and writes\n * within a single mutation are atomic and isolated from other mutations.\n *\n * @example\n * ```typescript\n * import { mutation } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const createTask = mutation({\n * args: { text: v.string() },\n * returns: v.id(\"tasks\"),\n * handler: async (ctx, args) => {\n * const taskId = await ctx.db.insert(\"tasks\", {\n * text: args.text,\n * completed: false,\n * });\n * return taskId;\n * },\n * });\n * ```\n *\n * **Best practice:** Always include `args` and `returns` validators on all\n * mutations. If the function doesn't return a value, use `returns: v.null()`.\n * Argument validation is critical for security since public mutations are\n * exposed to the internet.\n *\n * **Common mistake:** Mutations cannot call third-party APIs or use `fetch`.\n * They must be deterministic. Use actions for external API calls.\n *\n * **Common mistake:** Do not use `mutation` for sensitive internal functions\n * that should not be called by clients. Use `internalMutation` instead.\n *\n * @param func - The mutation function. It receives a {@link GenericMutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/mutation-functions\n * @public\n */\nexport const mutationGeneric: MutationBuilder<any, \"public\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericMutationCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"mutation\", handler) as RegisteredMutation<\n \"public\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isMutation = true;\n func.isPublic = true;\n func.invokeMutation = (argsStr) => invokeMutation(handler, argsStr, \"public\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as MutationBuilder<any, \"public\">;\n\n/**\n * Define a mutation that is only accessible from other Convex functions (but not from the client).\n *\n * You should generally use the `internalMutation` function from\n * `\"./_generated/server\"`.\n *\n * Internal mutations can read from and write to the database but are **not**\n * exposed as part of your app's public API. They can only be called by other\n * Convex functions using `ctx.runMutation` or by the scheduler. Like public\n * mutations, they run transactionally.\n *\n * @example\n * ```typescript\n * import { internalMutation } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * // This mutation can only be called from other Convex functions:\n * export const markTaskCompleted = internalMutation({\n * args: { taskId: v.id(\"tasks\") },\n * returns: v.null(),\n * handler: async (ctx, args) => {\n * await ctx.db.patch(\"tasks\", args.taskId, { completed: true });\n * return null;\n * },\n * });\n * ```\n *\n * **Best practice:** Use `internalMutation` for any mutation that should not\n * be directly callable by clients, such as write-back functions from actions\n * or scheduled background work. Reference it via the `internal` object:\n * `await ctx.runMutation(internal.myModule.markTaskCompleted, { taskId })`.\n *\n * @param func - The mutation function. It receives a {@link GenericMutationCtx} as its first argument.\n * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/internal-functions\n * @public\n */\nexport const internalMutationGeneric: MutationBuilder<any, \"internal\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericMutationCtx<any>, args: any) => any;\n const func = dontCallDirectly(\n \"internalMutation\",\n handler,\n ) as RegisteredMutation<\"internal\", any, any>;\n\n assertNotBrowser();\n func.isMutation = true;\n func.isInternal = true;\n func.invokeMutation = (argsStr) =>\n invokeMutation(handler, argsStr, \"internal\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as MutationBuilder<any, \"internal\">;\n\nasync function invokeQuery<\n F extends (ctx: GenericQueryCtx<GenericDataModel>, ...args: any) => any,\n>(func: F, argsStr: string, visibility: FunctionVisibility) {\n // TODO(presley): Change the function signature and propagate the requestId from Rust.\n // Ok, to mock it out for now, since queries are only running in V8.\n const requestId = \"\";\n const args = jsonToConvex(JSON.parse(argsStr));\n const queryCtx = {\n db: setupReader(),\n auth: setupAuth(requestId),\n storage: setupStorageReader(requestId),\n meta: setupQueryMeta(visibility),\n runQuery: (reference: any, args?: any, options?: any) => {\n if (options?.useStaleSnapshot) {\n throw new Error(\n \"`useStaleSnapshot` is only supported in mutations, not queries.\",\n );\n }\n return runUdf(\"query\", reference, args, options?.transactionLimits);\n },\n };\n const result = await invokeFunction(func, queryCtx, args as any);\n validateReturnValue(result);\n return JSON.stringify(convexToJson(result === undefined ? null : result));\n}\n\n/**\n * Define a query in this Convex app's public API.\n *\n * You should generally use the `query` function from\n * `\"./_generated/server\"`.\n *\n * Queries can read from the database and are accessible from the client. They\n * are **reactive**, when used with `useQuery` in React, the component\n * automatically re-renders whenever the underlying data changes. Queries\n * cannot modify the database.\n * Query results are automatically cached by the Convex client and kept\n * consistent via WebSocket subscriptions.\n *\n *\n * @example\n * ```typescript\n * import { query } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const listTasks = query({\n * args: { completed: v.optional(v.boolean()) },\n * returns: v.array(v.object({\n * _id: v.id(\"tasks\"),\n * _creationTime: v.number(),\n * text: v.string(),\n * completed: v.boolean(),\n * })),\n * handler: async (ctx, args) => {\n * if (args.completed !== undefined) {\n * return await ctx.db\n * .query(\"tasks\")\n * .withIndex(\"by_completed\", (q) => q.eq(\"completed\", args.completed))\n * .collect();\n * }\n * return await ctx.db.query(\"tasks\").collect();\n * },\n * });\n * ```\n *\n * **Best practice:** Always include `args` and `returns` validators. Use\n * `.withIndex()` instead of `.filter()` for efficient database queries.\n * Queries should be fast since they run on every relevant data change.\n *\n * **Common mistake:** Queries are pure reads, they cannot write to the\n * database, call external APIs, or schedule functions. Use actions for HTTP\n * calls and mutations for database writes and scheduling.\n *\n * @param func - The query function. It receives a {@link GenericQueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/query-functions\n * @public\n */\nexport const queryGeneric: QueryBuilder<any, \"public\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericQueryCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"query\", handler) as RegisteredQuery<\n \"public\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isQuery = true;\n func.isPublic = true;\n func.invokeQuery = (argsStr) => invokeQuery(handler, argsStr, \"public\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as QueryBuilder<any, \"public\">;\n\n/**\n * Define a query that is only accessible from other Convex functions (but not from the client).\n *\n * You should generally use the `internalQuery` function from\n * `\"./_generated/server\"`.\n *\n * Internal queries can read from the database but are **not** exposed as part\n * of your app's public API. They can only be called by other Convex functions\n * using `ctx.runQuery`. This is useful for loading data in actions or for\n * helper queries that shouldn't be client-facing.\n *\n * @example\n * ```typescript\n * import { internalQuery } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * // Only callable from other Convex functions:\n * export const getUser = internalQuery({\n * args: { userId: v.id(\"users\") },\n * returns: v.union(\n * v.object({\n * _id: v.id(\"users\"),\n * _creationTime: v.number(),\n * name: v.string(),\n * email: v.string(),\n * }),\n * v.null(),\n * ),\n * handler: async (ctx, args) => {\n * return await ctx.db.get(\"users\", args.userId);\n * },\n * });\n * ```\n *\n * **Best practice:** Use `internalQuery` for data-loading in actions via\n * `ctx.runQuery(internal.myModule.getUser, { userId })`.\n *\n * @param func - The query function. It receives a {@link GenericQueryCtx} as its first argument.\n * @returns The wrapped query. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/internal-functions\n * @public\n */\nexport const internalQueryGeneric: QueryBuilder<any, \"internal\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericQueryCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"internalQuery\", handler) as RegisteredQuery<\n \"internal\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isQuery = true;\n func.isInternal = true;\n func.invokeQuery = (argsStr) =>\n invokeQuery(handler as any, argsStr, \"internal\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as QueryBuilder<any, \"internal\">;\n\nasync function invokeAction<\n F extends (ctx: GenericActionCtx<GenericDataModel>, ...args: any) => any,\n>(func: F, requestId: string, argsStr: string, visibility: FunctionVisibility) {\n const args = jsonToConvex(JSON.parse(argsStr));\n const calls = setupActionCalls(requestId);\n const ctx = {\n ...calls,\n auth: setupAuth(requestId),\n scheduler: setupActionScheduler(requestId),\n storage: setupStorageActionWriter(requestId),\n vectorSearch: setupActionVectorSearch(requestId) as any,\n meta: setupActionMeta(visibility),\n };\n const result = await invokeFunction(func, ctx, args as any);\n return JSON.stringify(convexToJson(result === undefined ? null : result));\n}\n\n/**\n * Define an action in this Convex app's public API.\n *\n * Actions can call third-party APIs, use Node.js libraries, and perform other\n * side effects. Unlike queries and mutations, actions do **not** have direct\n * database access (`ctx.db` is not available). Instead, use `ctx.runQuery`\n * and `ctx.runMutation` to read and write data.\n *\n * You should generally use the `action` function from\n * `\"./_generated/server\"`.\n *\n * Actions are accessible from the client and run outside of the database\n * transaction, so they are not atomic. They are best for integrating with\n * external services.\n *\n * @example\n * ```typescript\n * // Add \"use node\"; at the top of the file if using Node.js built-in modules.\n * import { action } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n * import { internal } from \"./_generated/api\";\n *\n * export const generateSummary = action({\n * args: { text: v.string() },\n * returns: v.string(),\n * handler: async (ctx, args) => {\n * // Call an external API:\n * const response = await fetch(\"https://api.example.com/summarize\", {\n * method: \"POST\",\n * body: JSON.stringify({ text: args.text }),\n * });\n * const { summary } = await response.json();\n *\n * // Write results back via a mutation:\n * await ctx.runMutation(internal.myModule.saveSummary, {\n * text: args.text,\n * summary,\n * });\n *\n * return summary;\n * },\n * });\n * ```\n *\n * **Best practice:** Minimize the number of `ctx.runQuery` and\n * `ctx.runMutation` calls from actions. Each call is a separate transaction,\n * so splitting logic across multiple calls introduces the risk of race\n * conditions. Try to batch reads/writes into single query/mutation calls.\n *\n * **`\"use node\"` runtime:** Actions run in Convex's default JavaScript\n * runtime, which supports `fetch` and most NPM packages. Only add\n * `\"use node\";` at the top of the file if a third-party library specifically\n * requires Node.js built-in APIs, it is a last resort, not the default.\n * Node.js actions have slower cold starts, and **only actions can be defined\n * in `\"use node\"` files** (no queries or mutations), so prefer the default\n * runtime whenever possible.\n *\n * **Common mistake:** Do not try to access `ctx.db` in an action, it is\n * not available. Use `ctx.runQuery` and `ctx.runMutation` instead.\n *\n * @param func - The function. It receives a {@link GenericActionCtx} as its first argument.\n * @returns The wrapped function. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/actions\n * @public\n */\nexport const actionGeneric: ActionBuilder<any, \"public\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericActionCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"action\", handler) as RegisteredAction<\n \"public\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isAction = true;\n func.isPublic = true;\n func.invokeAction = (requestId, argsStr) =>\n invokeAction(handler, requestId, argsStr, \"public\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as ActionBuilder<any, \"public\">;\n\n/**\n * Define an action that is only accessible from other Convex functions (but not from the client).\n *\n * You should generally use the `internalAction` function from\n * `\"./_generated/server\"`.\n *\n * Internal actions behave like public actions (they can call external APIs and\n * use Node.js libraries) but are **not** exposed in your app's public API. They\n * can only be called by other Convex functions using `ctx.runAction` or via the\n * scheduler.\n *\n * @example\n * ```typescript\n * import { internalAction } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const sendEmail = internalAction({\n * args: { to: v.string(), subject: v.string(), body: v.string() },\n * returns: v.null(),\n * handler: async (ctx, args) => {\n * // Call an external email service (fetch works in the default runtime):\n * await fetch(\"https://api.email-service.com/send\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(args),\n * });\n * return null;\n * },\n * });\n * ```\n *\n * **Best practice:** Use `internalAction` for background work scheduled from\n * mutations: `await ctx.scheduler.runAfter(0, internal.myModule.sendEmail, { ... })`.\n * Only use `ctx.runAction` from another action if you need to cross runtimes\n * (e.g., default Convex runtime to Node.js). Otherwise, extract shared code\n * into a helper function.\n *\n * **`\"use node\"` runtime:** Only add `\"use node\";` at the top of the file\n * as a last resort when a third-party library requires Node.js APIs. Node.js\n * actions have slower cold starts, and **only actions can be defined in\n * `\"use node\"` files** (no queries or mutations).\n *\n * @param func - The function. It receives a {@link GenericActionCtx} as its first argument.\n * @returns The wrapped function. Include this as an `export` to name it and make it accessible.\n *\n * @see https://docs.convex.dev/functions/internal-functions\n * @public\n */\nexport const internalActionGeneric: ActionBuilder<any, \"internal\"> = ((\n functionDefinition: FunctionDefinition,\n) => {\n const handler = (\n typeof functionDefinition === \"function\"\n ? functionDefinition\n : functionDefinition.handler\n ) as (ctx: GenericActionCtx<any>, args: any) => any;\n const func = dontCallDirectly(\"internalAction\", handler) as RegisteredAction<\n \"internal\",\n any,\n any\n >;\n\n assertNotBrowser();\n func.isAction = true;\n func.isInternal = true;\n func.invokeAction = (requestId, argsStr) =>\n invokeAction(handler, requestId, argsStr, \"internal\");\n func.exportArgs = exportArgs(functionDefinition);\n func.exportReturns = exportReturns(functionDefinition);\n func._handler = handler;\n return func;\n}) as ActionBuilder<any, \"internal\">;\n\nasync function invokeHttpAction<\n F extends (ctx: GenericActionCtx<GenericDataModel>, request: Request) => any,\n>(func: F, request: Request) {\n // TODO(presley): Change the function signature and propagate the requestId from Rust.\n // Ok, to mock it out for now, since http endpoints are only running in V8.\n const requestId = \"\";\n const calls = setupActionCalls(requestId);\n const ctx = {\n ...calls,\n auth: setupAuth(requestId),\n storage: setupStorageActionWriter(requestId),\n scheduler: setupActionScheduler(requestId),\n vectorSearch: setupActionVectorSearch(requestId) as any,\n meta: setupActionMeta(\"public\"),\n };\n return await invokeFunction(func, ctx, [request]);\n}\n\n/**\n * Define a Convex HTTP action.\n *\n * HTTP actions handle raw HTTP requests and return HTTP responses. They are\n * registered by routing URL paths to them in `convex/http.ts` using\n * {@link HttpRouter}. Like regular actions, they can call external APIs and\n * use `ctx.runQuery` / `ctx.runMutation` but do not have direct `ctx.db` access.\n *\n * @example\n * ```typescript\n * // convex/http.ts\n * import { httpRouter } from \"convex/server\";\n * import { httpAction } from \"./_generated/server\";\n *\n * const http = httpRouter();\n *\n * http.route({\n * path: \"/api/webhook\",\n * method: \"POST\",\n * handler: httpAction(async (ctx, request) => {\n * const body = await request.json();\n * // Process the webhook payload...\n * return new Response(JSON.stringify({ ok: true }), {\n * status: 200,\n * headers: { \"Content-Type\": \"application/json\" },\n * });\n * }),\n * });\n *\n * export default http;\n * ```\n *\n * **Best practice:** HTTP actions are registered at the exact path specified.\n * For example, `path: \"/api/webhook\"` registers at `/api/webhook`.\n *\n * @param func - The function. It receives a {@link GenericActionCtx} as its first argument, and a `Request` object\n * as its second.\n * @returns The wrapped function. Route a URL path to this function in `convex/http.ts`.\n *\n * @see https://docs.convex.dev/functions/http-actions\n * @public\n */\nexport const httpActionGeneric = (\n func: (\n ctx: GenericActionCtx<GenericDataModel>,\n request: Request,\n ) => Promise<Response>,\n): PublicHttpAction => {\n const q = dontCallDirectly(\"httpAction\", func) as PublicHttpAction;\n assertNotBrowser();\n q.isHttp = true;\n q.invokeHttpAction = (request) => invokeHttpAction(func as any, request);\n q._handler = func;\n return q;\n};\n\nasync function runUdf(\n udfType: \"query\" | \"mutation\" | \"snapshotQuery\",\n f: any,\n args?: Record<string, Value>,\n transactionLimits?: Record<string, number>,\n): Promise<any> {\n const queryArgs = parseArgs(args);\n const syscallArgs: Record<string, any> = {\n udfType,\n args: convexToJson(queryArgs),\n ...getFunctionAddress(f),\n };\n if (transactionLimits) {\n syscallArgs.transactionLimits = transactionLimits;\n }\n const result = await performAsyncSyscall(\"1.0/runUdf\", syscallArgs);\n return jsonToConvex(result);\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
6
|
"names": ["args", "v"]
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/server/meta.ts"],
|
|
4
|
-
"sourcesContent": ["import { FunctionType } from \"./api.js\";\nimport { FunctionVisibility } from \"./registration.js\";\n\n/**\n * Used and remaining amounts for a single transaction limit.\n *\n * @public\n */\nexport type TransactionMetric = {\n used: number;\n remaining: number;\n};\n\n/**\n * The remaining headroom for a transaction before hitting limits.\n *\n * See https://docs.convex.dev/production/state/limits\n *\n * @public\n */\nexport type TransactionMetrics = {\n bytesRead: TransactionMetric;\n bytesWritten: TransactionMetric;\n databaseQueries: TransactionMetric;\n documentsRead: TransactionMetric;\n documentsWritten: TransactionMetric;\n functionsScheduled: TransactionMetric;\n scheduledFunctionArgsBytes: TransactionMetric;\n};\n\n/**\n * Custom limits for a nested transaction. Each field specifies the absolute\n * maximum allowed for the nested function call. Values are capped at the\n * global transaction limits, so they can only lower limits, never raise them.\n *\n * @public\n */\nexport interface TransactionLimits {\n bytesRead?: number;\n bytesWritten?: number;\n databaseQueries?: number;\n documentsRead?: number;\n documentsWritten?: number;\n functionsScheduled?: number;\n scheduledFunctionArgsBytes?: number;\n}\n\n/**\n * Metadata about the currently executing Convex function.\n *\n * @public\n */\nexport type FunctionMetadata = {\n /**\n * The name of the function, in the format `\"path/to/module:functionName\"`\n */\n name: string;\n /**\n * The path of the component this function belongs to.\n * This is an empty string `\"\"` for the app.\n */\n componentPath: string;\n /** Whether it's a query, mutation, or action. */\n type: FunctionType;\n /** Whether the function is public or internal. */\n visibility: FunctionVisibility;\n};\n\n/**\n * Metadata about the deployment this function is running on.\n *\n * @public\n */\nexport type DeploymentMetadata = {\n /**\n * The deployment name, e.g. `\"tall-tiger-123\"` for cloud deployments,\n * `\"local-my_team-my_project\"` for local deployments, or\n * `\"anonymous-*\"` for anonymous deployments.\n */\n name: string;\n /**\n * The deployment region, e.g. `\"aws-us-east-1\"`.\n * `null` for local and self-hosted deployments.\n */\n region: string | null;\n /**\n * The deployment class, e.g. `\"s16\"`, `\"s256\"`, or `\"d1024\"`.\n */\n class: \"s16\" | \"s256\" | \"d1024\";\n};\n\n/**\n * Metadata about the HTTP request that triggered the current function execution.\n *\n * `ip` and `userAgent` are `null` when the function was not triggered by an\n * HTTP request (e.g. scheduled jobs or cron jobs).\n *\n * Functions called from within a function (i.e. using `runMutation` or\n * `runAction`) will have the same request metadata as the parent function.\n *\n * @public\n */\nexport type RequestMetadata = {\n ip: string | null;\n userAgent: string | null;\n requestId: string;\n /**\n * The ID of the scheduled function document (in `_scheduled_functions`) that\n * this execution belongs to, or `null` otherwise.\n *\n * This is set for the scheduled function itself and for any functions it\n * calls (e.g. a mutation invoked via `runMutation` by a scheduled action),\n * propagating the top-level scheduled function's ID down the call tree. It is\n * `null` when the function was not scheduled.\n */\n scheduledFunctionId: string | null;\n};\n\n/**\n * Extra context available in Convex query functions.\n *\n * @public\n */\nexport interface QueryMeta {\n getFunctionMetadata(): Promise<FunctionMetadata>;\n getTransactionMetrics(): Promise<TransactionMetrics>;\n getDeploymentMetadata(): Promise<DeploymentMetadata>;\n}\n\n/**\n * Extra context available in Convex mutation functions.\n *\n * @public\n */\nexport interface MutationMeta extends QueryMeta {\n getRequestMetadata(): Promise<RequestMetadata>;\n}\n\n/**\n * Extra context available in Convex action functions.\n *\n * @public\n */\nexport interface ActionMeta {\n getFunctionMetadata(): Promise<FunctionMetadata>;\n getDeploymentMetadata(): Promise<DeploymentMetadata>;\n getRequestMetadata(): Promise<RequestMetadata>;\n}\n"],
|
|
4
|
+
"sourcesContent": ["import { FunctionType } from \"./api.js\";\nimport { FunctionVisibility } from \"./registration.js\";\n\n/**\n * Used and remaining amounts for a single transaction limit.\n *\n * @public\n */\nexport type TransactionMetric = {\n used: number;\n remaining: number;\n};\n\n/**\n * The remaining headroom for a transaction before hitting limits.\n *\n * See https://docs.convex.dev/production/state/limits\n *\n * @public\n */\nexport type TransactionMetrics = {\n bytesRead: TransactionMetric;\n bytesWritten: TransactionMetric;\n databaseQueries: TransactionMetric;\n documentsRead: TransactionMetric;\n documentsWritten: TransactionMetric;\n functionsScheduled: TransactionMetric;\n scheduledFunctionArgsBytes: TransactionMetric;\n};\n\n/**\n * Custom limits for a nested transaction. Each field specifies the absolute\n * maximum allowed for the nested function call. Values are capped at the\n * global transaction limits, so they can only lower limits, never raise them.\n *\n * @public\n */\nexport interface TransactionLimits {\n bytesRead?: number;\n bytesWritten?: number;\n databaseQueries?: number;\n documentsRead?: number;\n documentsWritten?: number;\n functionsScheduled?: number;\n scheduledFunctionArgsBytes?: number;\n}\n\n/**\n * Metadata about the currently executing Convex function.\n *\n * @public\n */\nexport type FunctionMetadata = {\n /**\n * The name of the function, in the format `\"path/to/module:functionName\"`\n */\n name: string;\n /**\n * The path of the component this function belongs to.\n * This is an empty string `\"\"` for the app.\n */\n componentPath: string;\n /** Whether it's a query, mutation, or action. */\n type: FunctionType;\n /** Whether the function is public or internal. */\n visibility: FunctionVisibility;\n};\n\n/**\n * Metadata about the deployment this function is running on.\n *\n * @public\n */\nexport type DeploymentMetadata = {\n /**\n * The deployment name, e.g. `\"tall-tiger-123\"` for cloud deployments,\n * `\"local-my_team-my_project\"` for local deployments, or\n * `\"anonymous-*\"` for anonymous deployments.\n */\n name: string;\n /**\n * The deployment region, e.g. `\"aws-us-east-1\"`.\n * `null` for local and self-hosted deployments.\n */\n region: string | null;\n /**\n * The deployment class, e.g. `\"s16\"`, `\"s256\"`, or `\"d1024\"`.\n */\n class: \"s16\" | \"s256\" | \"d1024\";\n};\n\n/**\n * Metadata about the HTTP request that triggered the current function execution.\n *\n * `ip` and `userAgent` are `null` when the function was not triggered by an\n * HTTP request (e.g. scheduled jobs or cron jobs).\n *\n * Functions called from within a function (i.e. using `runMutation` or\n * `runAction`) will have the same request metadata as the parent function.\n *\n * @public\n */\nexport type RequestMetadata = {\n ip: string | null;\n userAgent: string | null;\n requestId: string;\n /**\n * The ID of the scheduled function document (in `_scheduled_functions`) that\n * this execution belongs to, or `null` otherwise.\n *\n * This is set for the scheduled function itself and for any functions it\n * calls (e.g. a mutation invoked via `runMutation` by a scheduled action),\n * propagating the top-level scheduled function's ID down the call tree. It is\n * `null` when the function was not scheduled.\n */\n scheduledFunctionId: string | null;\n /**\n * The raw auth token (a JWT) the request was authenticated with, or `null`\n * when the request was unauthenticated or authenticated with an admin key.\n *\n * This is the same token that `ctx.auth.getUserIdentity()` derives its\n * attributes from.\n *\n * @internal\n */\n authToken: string | null;\n};\n\n/**\n * Extra context available in Convex query functions.\n *\n * @public\n */\nexport interface QueryMeta {\n getFunctionMetadata(): Promise<FunctionMetadata>;\n getTransactionMetrics(): Promise<TransactionMetrics>;\n getDeploymentMetadata(): Promise<DeploymentMetadata>;\n}\n\n/**\n * Extra context available in Convex mutation functions.\n *\n * @public\n */\nexport interface MutationMeta extends QueryMeta {\n getRequestMetadata(): Promise<RequestMetadata>;\n}\n\n/**\n * Extra context available in Convex action functions.\n *\n * @public\n */\nexport interface ActionMeta {\n getFunctionMetadata(): Promise<FunctionMetadata>;\n getDeploymentMetadata(): Promise<DeploymentMetadata>;\n getRequestMetadata(): Promise<RequestMetadata>;\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/server/query.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n DocumentByInfo,\n GenericTableInfo,\n IndexNames,\n NamedIndex,\n NamedSearchIndex,\n SearchIndexNames,\n} from \"./data_model.js\";\nimport { ExpressionOrValue, FilterBuilder } from \"./filter_builder.js\";\nimport { IndexRange, IndexRangeBuilder } from \"./index_range_builder.js\";\nimport { PaginationResult, PaginationOptions } from \"./pagination.js\";\nimport { SearchFilter, SearchFilterBuilder } from \"./search_filter_builder.js\";\n\n/**\n * The {@link QueryInitializer} interface is the entry point for building a {@link Query}\n * over a Convex database table.\n *\n * There are two types of queries:\n * 1. Full table scans: Queries created with {@link QueryInitializer.fullTableScan} which\n * iterate over all of the documents in the table in insertion order.\n * 2. Indexed Queries: Queries created with {@link QueryInitializer.withIndex} which iterate\n * over an index range in index order.\n *\n * For convenience, {@link QueryInitializer} extends the {@link Query} interface, implicitly\n * starting a full table scan.\n *\n * @public\n */\nexport interface QueryInitializer<TableInfo extends GenericTableInfo>\n extends Query<TableInfo> {\n /**\n * Query by reading all of the values out of this table.\n *\n * This query's cost is relative to the size of the entire table, so this\n * should only be used on tables that will stay very small (say between a few\n * hundred and a few thousand documents) and are updated infrequently.\n *\n * @returns - The {@link Query} that iterates over every document of the table.\n */\n fullTableScan(): Query<TableInfo>;\n\n /**\n * Query by reading documents from an index on this table.\n *\n * This query's cost is relative to the number of documents that match the\n * index range expression.\n *\n * Results will be returned in index order.\n *\n * To learn about indexes, see [Indexes](https://docs.convex.dev/using/indexes).\n *\n * @param indexName - The name of the index to query.\n * @param indexRange - An optional index range constructed with the supplied\n * {@link IndexRangeBuilder}. An index range is a description of which\n * documents Convex should consider when running the query. If no index\n * range is present, the query will consider all documents in the index.\n * @returns - The query that yields documents in the index.\n */\n withIndex<IndexName extends IndexNames<TableInfo>>(\n indexName: IndexName,\n indexRange?: (\n q: IndexRangeBuilder<\n DocumentByInfo<TableInfo>,\n NamedIndex<TableInfo, IndexName>\n >,\n ) => IndexRange,\n ): Query<TableInfo>;\n\n /**\n * Query by running a full text search against a search index.\n *\n * Search queries must always search for some text within the index's\n * `searchField`. This query can optionally add equality filters for any\n * `filterFields` specified in the index.\n *\n * Documents will be returned in relevance order based on how well they\n * match the search text.\n *\n * To learn about full text search, see [Indexes](https://docs.convex.dev/text-search).\n *\n * @param indexName - The name of the search index to query.\n * @param searchFilter - A search filter expression constructed with the\n * supplied {@link SearchFilterBuilder}. This defines the full text search to run\n * along with equality filtering to run within the search index.\n * @returns - A query that searches for matching documents, returning them\n * in relevancy order.\n */\n withSearchIndex<IndexName extends SearchIndexNames<TableInfo>>(\n indexName: IndexName,\n searchFilter: (\n q: SearchFilterBuilder<\n DocumentByInfo<TableInfo>,\n NamedSearchIndex<TableInfo, IndexName>\n >,\n ) => SearchFilter,\n ): OrderedQuery<TableInfo>;\n\n /**\n * The number of documents in the table.\n *\n * @internal\n */\n count(): Promise<number>;\n}\n\n/**\n * The {@link Query} interface allows functions to read values out of the database.\n *\n * **If you only need to load an object by ID, use `db.get(tableName, id)` instead.**\n *\n * Executing a query consists of calling\n * 1. (Optional) {@link Query.order} to define the order\n * 2. (Optional) {@link Query.filter} to refine the results\n * 3. A *consumer* method to obtain the results\n *\n * Queries are lazily evaluated. No work is done until iteration begins, so constructing and\n * extending a query is free. The query is executed incrementally as the results are iterated over,\n * so early terminating also reduces the cost of the query.\n *\n * @example\n * ```typescript\n * // Use .withIndex() for efficient queries (preferred over .filter()):\n * const messages = await ctx.db\n * .query(\"messages\")\n * .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", channelId))\n * .order(\"desc\")\n * .take(10);\n *\n * // Async iteration for processing large result sets:\n * for await (const task of ctx.db.query(\"tasks\")) {\n * // Process each task without loading all into memory\n * }\n *\n * // Get a single unique result (throws if multiple match):\n * const user = await ctx.db\n * .query(\"users\")\n * .withIndex(\"by_email\", (q) => q.eq(\"email\", email))\n * .unique();\n * ```\n *\n * **Common mistake:** `.collect()` loads **all** matching documents into memory.\n * If the result set can grow unbounded as your database grows, this will\n * eventually cause problems. Prefer `.first()`, `.unique()`, `.take(n)`, or\n * pagination instead. Only use `.collect()` on queries with a tightly bounded\n * result set (e.g., items belonging to a single user with a known small limit).\n *\n * | | |\n * |----------------------------------------------|-|\n * | **Ordering** | |\n * | [`order(\"asc\")`](#order) | Define the order of query results. |\n * | | |\n * | **Filtering** | |\n * | [`filter(...)`](#filter) | Filter the query results to only the values that match some condition. |\n * | | |\n * | **Consuming** | Execute a query and return results in different ways. |\n * | [`[Symbol.asyncIterator]()`](#asynciterator) | The query's results can be iterated over using a `for await..of` loop. |\n * | [`collect()`](#collect) | Return all of the results as an array. |\n * | [`take(n: number)`](#take) | Return the first `n` results as an array. |\n * | [`first()`](#first) | Return the first result. |\n * | [`unique()`](#unique) | Return the only result, and throw if there is more than one result. |\n *\n * To learn more about how to write queries, see [Querying the Database](https://docs.convex.dev/database/reading-data).\n *\n * @public\n */\nexport interface Query<TableInfo extends GenericTableInfo>\n extends OrderedQuery<TableInfo> {\n /**\n * Define the order of the query output.\n *\n * Use `\"asc\"` for an ascending order and `\"desc\"` for a descending order. If not specified, the order defaults to ascending.\n * @param order - The order to return results in.\n */\n order(order: \"asc\" | \"desc\"): OrderedQuery<TableInfo>;\n}\n\n/**\n * A {@link Query} with an order that has already been defined.\n *\n * @public\n */\nexport interface OrderedQuery<TableInfo extends GenericTableInfo>\n extends AsyncIterable<DocumentByInfo<TableInfo>> {\n /**\n * Filter the query output, returning only the values for which `predicate` evaluates to true.\n *\n * **Important:** Prefer using `.withIndex()` over `.filter()` whenever\n * possible. Filters scan all documents matched so far and discard non-matches,\n * while indexes efficiently skip non-matching documents. Define an index in\n * your schema for fields you filter on frequently.\n *\n * @param predicate - An {@link Expression} constructed with the supplied {@link FilterBuilder} that specifies which documents to keep.\n * @returns - A new {@link OrderedQuery} with the given filter predicate applied.\n */\n filter(\n predicate: (q: FilterBuilder<TableInfo>) => ExpressionOrValue<boolean>,\n ): this;\n\n /**\n * Take only the first `n` results from the pipeline so far.\n *\n * @param n - Limit for the number of results at this stage of the query pipeline.\n * @returns - A new {@link OrderedQuery} with the specified limit applied.\n *\n * @internal\n */\n limit(n: number): this;\n\n /**\n * Load a page of `n` results and obtain a {@link Cursor} for loading more.\n *\n * Note: If this is called from a reactive query function the number of\n * results may not match `paginationOpts.numItems`!\n *\n * `paginationOpts.numItems` is only an initial value. After the first invocation,\n * `paginate` will return all items in the original query range. This ensures\n * that all pages will remain adjacent and non-overlapping.\n *\n * @param paginationOpts - A {@link PaginationOptions} object containing the number\n * of items to load and the cursor to start at.\n * @returns A {@link PaginationResult} containing the page of results and a\n * cursor to continue paginating.\n */\n paginate(\n paginationOpts: PaginationOptions,\n ): Promise<PaginationResult<DocumentByInfo<TableInfo>>>;\n\n /**\n * Execute the query and return all of the results as an array.\n *\n * **Warning:** This loads every matching document into memory. If the result\n * set can grow unbounded as your database grows, `.collect()` will eventually\n * cause performance problems or hit limits. Only use `.collect()` when the\n * result set is tightly bounded (e.g., a known small number of items).\n *\n * Prefer `.first()`, `.unique()`, `.take(n)`, or `.paginate()` when the\n * result set may be large or unbounded. For processing many results without\n * loading all into memory, use the `Query` as an `AsyncIterable` with\n * `for await...of`.\n *\n * @returns - An array of all of the query's results.\n */\n collect(): Promise<Array<DocumentByInfo<TableInfo>>>;\n\n /**\n * Execute the query and return the first `n` results.\n *\n * @param n - The number of items to take.\n * @returns - An array of the first `n` results of the query (or less if the\n * query doesn't have `n` results).\n */\n take(n: number): Promise<Array<DocumentByInfo<TableInfo>>>;\n\n /**\n * Execute the query and return the first result if there is one.\n *\n * @returns - The first value of the query or `null` if the query returned no results.\n * */\n first(): Promise<DocumentByInfo<TableInfo> | null>;\n\n /**\n * Execute the query and return the singular result if there is one.\n *\n * Use this when you expect exactly zero or one result, for example when\n * querying by a unique field. If the query matches more than one document,\n * this will throw an error.\n *\n * @example\n * ```typescript\n * const user = await ctx.db\n * .query(\"users\")\n * .withIndex(\"by_email\", (q) => q.eq(\"email\", \"alice@example.com\"))\n * .unique();\n * ```\n *\n * @returns - The single result returned from the query or null if none exists.\n * @throws Will throw an error if the query returns more than one result.\n */\n unique(): Promise<DocumentByInfo<TableInfo> | null>;\n}\n"],
|
|
4
|
+
"sourcesContent": ["import {\n DocumentByInfo,\n GenericTableInfo,\n IndexNames,\n NamedIndex,\n NamedSearchIndex,\n SearchIndexNames,\n} from \"./data_model.js\";\nimport { ExpressionOrValue, FilterBuilder } from \"./filter_builder.js\";\nimport { IndexRange, IndexRangeBuilder } from \"./index_range_builder.js\";\nimport { PaginationResult, PaginationOptions } from \"./pagination.js\";\nimport { SearchFilter, SearchFilterBuilder } from \"./search_filter_builder.js\";\n\n/**\n * The {@link QueryInitializer} interface is the entry point for building a {@link Query}\n * over a Convex database table.\n *\n * There are two types of queries:\n * 1. Full table scans: Queries created with {@link QueryInitializer.fullTableScan} which\n * iterate over all of the documents in the table in insertion order.\n * 2. Indexed Queries: Queries created with {@link QueryInitializer.withIndex} which iterate\n * over an index range in index order.\n *\n * For convenience, {@link QueryInitializer} extends the {@link Query} interface, implicitly\n * starting a full table scan.\n *\n * @public\n */\nexport interface QueryInitializer<\n TableInfo extends GenericTableInfo,\n> extends Query<TableInfo> {\n /**\n * Query by reading all of the values out of this table.\n *\n * This query's cost is relative to the size of the entire table, so this\n * should only be used on tables that will stay very small (say between a few\n * hundred and a few thousand documents) and are updated infrequently.\n *\n * @returns - The {@link Query} that iterates over every document of the table.\n */\n fullTableScan(): Query<TableInfo>;\n\n /**\n * Query by reading documents from an index on this table.\n *\n * This query's cost is relative to the number of documents that match the\n * index range expression.\n *\n * Results will be returned in index order.\n *\n * To learn about indexes, see [Indexes](https://docs.convex.dev/using/indexes).\n *\n * @param indexName - The name of the index to query.\n * @param indexRange - An optional index range constructed with the supplied\n * {@link IndexRangeBuilder}. An index range is a description of which\n * documents Convex should consider when running the query. If no index\n * range is present, the query will consider all documents in the index.\n * @returns - The query that yields documents in the index.\n */\n withIndex<IndexName extends IndexNames<TableInfo>>(\n indexName: IndexName,\n indexRange?: (\n q: IndexRangeBuilder<\n DocumentByInfo<TableInfo>,\n NamedIndex<TableInfo, IndexName>\n >,\n ) => IndexRange,\n ): Query<TableInfo>;\n\n /**\n * Query by running a full text search against a search index.\n *\n * Search queries must always search for some text within the index's\n * `searchField`. This query can optionally add equality filters for any\n * `filterFields` specified in the index.\n *\n * Documents will be returned in relevance order based on how well they\n * match the search text.\n *\n * To learn about full text search, see [Indexes](https://docs.convex.dev/text-search).\n *\n * @param indexName - The name of the search index to query.\n * @param searchFilter - A search filter expression constructed with the\n * supplied {@link SearchFilterBuilder}. This defines the full text search to run\n * along with equality filtering to run within the search index.\n * @returns - A query that searches for matching documents, returning them\n * in relevancy order.\n */\n withSearchIndex<IndexName extends SearchIndexNames<TableInfo>>(\n indexName: IndexName,\n searchFilter: (\n q: SearchFilterBuilder<\n DocumentByInfo<TableInfo>,\n NamedSearchIndex<TableInfo, IndexName>\n >,\n ) => SearchFilter,\n ): OrderedQuery<TableInfo>;\n\n /**\n * The number of documents in the table.\n *\n * @internal\n */\n count(): Promise<number>;\n}\n\n/**\n * The {@link Query} interface allows functions to read values out of the database.\n *\n * **If you only need to load an object by ID, use `db.get(tableName, id)` instead.**\n *\n * Executing a query consists of calling\n * 1. (Optional) {@link Query.order} to define the order\n * 2. (Optional) {@link Query.filter} to refine the results\n * 3. A *consumer* method to obtain the results\n *\n * Queries are lazily evaluated. No work is done until iteration begins, so constructing and\n * extending a query is free. The query is executed incrementally as the results are iterated over,\n * so early terminating also reduces the cost of the query.\n *\n * @example\n * ```typescript\n * // Use .withIndex() for efficient queries (preferred over .filter()):\n * const messages = await ctx.db\n * .query(\"messages\")\n * .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", channelId))\n * .order(\"desc\")\n * .take(10);\n *\n * // Async iteration for processing large result sets:\n * for await (const task of ctx.db.query(\"tasks\")) {\n * // Process each task without loading all into memory\n * }\n *\n * // Get a single unique result (throws if multiple match):\n * const user = await ctx.db\n * .query(\"users\")\n * .withIndex(\"by_email\", (q) => q.eq(\"email\", email))\n * .unique();\n * ```\n *\n * **Common mistake:** `.collect()` loads **all** matching documents into memory.\n * If the result set can grow unbounded as your database grows, this will\n * eventually cause problems. Prefer `.first()`, `.unique()`, `.take(n)`, or\n * pagination instead. Only use `.collect()` on queries with a tightly bounded\n * result set (e.g., items belonging to a single user with a known small limit).\n *\n * | | |\n * |----------------------------------------------|-|\n * | **Ordering** | |\n * | [`order(\"asc\")`](#order) | Define the order of query results. |\n * | | |\n * | **Filtering** | |\n * | [`filter(...)`](#filter) | Filter the query results to only the values that match some condition. |\n * | | |\n * | **Consuming** | Execute a query and return results in different ways. |\n * | [`[Symbol.asyncIterator]()`](#asynciterator) | The query's results can be iterated over using a `for await..of` loop. |\n * | [`collect()`](#collect) | Return all of the results as an array. |\n * | [`take(n: number)`](#take) | Return the first `n` results as an array. |\n * | [`first()`](#first) | Return the first result. |\n * | [`unique()`](#unique) | Return the only result, and throw if there is more than one result. |\n *\n * To learn more about how to write queries, see [Querying the Database](https://docs.convex.dev/database/reading-data).\n *\n * @public\n */\nexport interface Query<\n TableInfo extends GenericTableInfo,\n> extends OrderedQuery<TableInfo> {\n /**\n * Define the order of the query output.\n *\n * Use `\"asc\"` for an ascending order and `\"desc\"` for a descending order. If not specified, the order defaults to ascending.\n * @param order - The order to return results in.\n */\n order(order: \"asc\" | \"desc\"): OrderedQuery<TableInfo>;\n}\n\n/**\n * A {@link Query} with an order that has already been defined.\n *\n * @public\n */\nexport interface OrderedQuery<\n TableInfo extends GenericTableInfo,\n> extends AsyncIterable<DocumentByInfo<TableInfo>> {\n /**\n * Filter the query output, returning only the values for which `predicate` evaluates to true.\n *\n * **Important:** Prefer using `.withIndex()` over `.filter()` whenever\n * possible. Filters scan all documents matched so far and discard non-matches,\n * while indexes efficiently skip non-matching documents. Define an index in\n * your schema for fields you filter on frequently.\n *\n * @param predicate - An {@link Expression} constructed with the supplied {@link FilterBuilder} that specifies which documents to keep.\n * @returns - A new {@link OrderedQuery} with the given filter predicate applied.\n */\n filter(\n predicate: (q: FilterBuilder<TableInfo>) => ExpressionOrValue<boolean>,\n ): this;\n\n /**\n * Take only the first `n` results from the pipeline so far.\n *\n * @param n - Limit for the number of results at this stage of the query pipeline.\n * @returns - A new {@link OrderedQuery} with the specified limit applied.\n *\n * @internal\n */\n limit(n: number): this;\n\n /**\n * Load a page of `n` results and obtain a {@link Cursor} for loading more.\n *\n * Note: If this is called from a reactive query function the number of\n * results may not match `paginationOpts.numItems`!\n *\n * `paginationOpts.numItems` is only an initial value. After the first invocation,\n * `paginate` will return all items in the original query range. This ensures\n * that all pages will remain adjacent and non-overlapping.\n *\n * @param paginationOpts - A {@link PaginationOptions} object containing the number\n * of items to load and the cursor to start at.\n * @returns A {@link PaginationResult} containing the page of results and a\n * cursor to continue paginating.\n */\n paginate(\n paginationOpts: PaginationOptions,\n ): Promise<PaginationResult<DocumentByInfo<TableInfo>>>;\n\n /**\n * Execute the query and return all of the results as an array.\n *\n * **Warning:** This loads every matching document into memory. If the result\n * set can grow unbounded as your database grows, `.collect()` will eventually\n * cause performance problems or hit limits. Only use `.collect()` when the\n * result set is tightly bounded (e.g., a known small number of items).\n *\n * Prefer `.first()`, `.unique()`, `.take(n)`, or `.paginate()` when the\n * result set may be large or unbounded. For processing many results without\n * loading all into memory, use the `Query` as an `AsyncIterable` with\n * `for await...of`.\n *\n * @returns - An array of all of the query's results.\n */\n collect(): Promise<Array<DocumentByInfo<TableInfo>>>;\n\n /**\n * Execute the query and return the first `n` results.\n *\n * @param n - The number of items to take.\n * @returns - An array of the first `n` results of the query (or less if the\n * query doesn't have `n` results).\n */\n take(n: number): Promise<Array<DocumentByInfo<TableInfo>>>;\n\n /**\n * Execute the query and return the first result if there is one.\n *\n * @returns - The first value of the query or `null` if the query returned no results.\n * */\n first(): Promise<DocumentByInfo<TableInfo> | null>;\n\n /**\n * Execute the query and return the singular result if there is one.\n *\n * Use this when you expect exactly zero or one result, for example when\n * querying by a unique field. If the query matches more than one document,\n * this will throw an error.\n *\n * @example\n * ```typescript\n * const user = await ctx.db\n * .query(\"users\")\n * .withIndex(\"by_email\", (q) => q.eq(\"email\", \"alice@example.com\"))\n * .unique();\n * ```\n *\n * @returns - The single result returned from the query or null if none exists.\n * @throws Will throw an error if the query returns more than one result.\n */\n unique(): Promise<DocumentByInfo<TableInfo> | null>;\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/server/registration.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n Auth,\n GenericDatabaseReader,\n GenericDatabaseReaderWithTable,\n GenericDatabaseWriter,\n GenericDatabaseWriterWithTable,\n StorageActionWriter,\n StorageReader,\n StorageWriter,\n} from \"./index.js\";\nimport {\n ActionMeta,\n MutationMeta,\n QueryMeta,\n TransactionLimits,\n} from \"./meta.js\";\nimport {\n ArgsAndOptions,\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n ValidatorTypeToReturnType,\n} from \"../server/api.js\";\nimport {\n GenericValidator,\n Infer,\n ObjectType,\n PropertyValidators,\n} from \"../values/validator.js\";\nimport { Id } from \"../values/value.js\";\nimport {\n GenericDataModel,\n NamedTableInfo,\n TableNamesInDataModel,\n VectorIndexNames,\n} from \"./data_model.js\";\nimport { Scheduler } from \"./scheduler.js\";\nimport { VectorSearchQuery } from \"./vector_search.js\";\nimport { Expand } from \"../type_utils.js\";\nimport { Validator } from \"../values/validators.js\";\n\n/**\n * A set of services for use within Convex mutation functions.\n *\n * The mutation context is passed as the first argument to any Convex mutation\n * function run on the server. Mutations run **transactionally**, all reads\n * and writes within a single mutation are atomic and isolated.\n *\n * You should generally use the `MutationCtx` type from\n * `\"./_generated/server\"`.\n *\n * @example\n * ```typescript\n * import { mutation } from \"./_generated/server\";\n * import { internal } from \"./_generated/api\";\n * import { v } from \"convex/values\";\n *\n * export const createTask = mutation({\n * args: { text: v.string() },\n * returns: v.id(\"tasks\"),\n * handler: async (ctx, args) => {\n * // ctx.db: read and write documents\n * const taskId = await ctx.db.insert(\"tasks\", { text: args.text, completed: false });\n *\n * // ctx.auth: check the authenticated user\n * const identity = await ctx.auth.getUserIdentity();\n *\n * // ctx.scheduler: schedule functions for later\n * await ctx.scheduler.runAfter(0, internal.notifications.send, { taskId });\n *\n * return taskId;\n * },\n * });\n * ```\n *\n * @public\n */\nexport interface GenericMutationCtx<DataModel extends GenericDataModel> {\n /**\n * A utility for reading and writing data in the database.\n *\n * Use `ctx.db.insert()`, `ctx.db.patch()`, `ctx.db.replace()`, and\n * `ctx.db.delete()` to write data. Use `ctx.db.get()` and `ctx.db.query()`\n * to read data. All operations within a mutation are atomic.\n */\n db: GenericDatabaseWriter<DataModel>;\n\n /**\n * Information about the currently authenticated user.\n *\n * Call `await ctx.auth.getUserIdentity()` to get the current user's identity,\n * or `null` if the user is not authenticated.\n */\n auth: Auth;\n\n /**\n * A utility for reading and writing files in storage.\n *\n * Use `ctx.storage.generateUploadUrl()` to create an upload URL for clients,\n * `ctx.storage.getUrl(storageId)` to get a URL for a stored file,\n * or `ctx.storage.delete(storageId)` to remove one.\n */\n storage: StorageWriter;\n\n /**\n * A utility for scheduling Convex functions to run in the future.\n *\n * @example\n * ```typescript\n * // Schedule an action to run immediately after this mutation commits:\n * await ctx.scheduler.runAfter(0, internal.emails.sendWelcome, { userId });\n *\n * // Schedule a cleanup to run in 24 hours:\n * await ctx.scheduler.runAfter(24 * 60 * 60 * 1000, internal.tasks.cleanup, {});\n * ```\n */\n scheduler: Scheduler;\n\n /**\n * Call a query function within the same transaction.\n *\n * The query runs within the same transaction as the calling mutation,\n * seeing a consistent snapshot of the database. Requires a\n * {@link FunctionReference} (e.g., `api.myModule.myQuery` or\n * `internal.myModule.myQuery`).\n *\n * NOTE: Often you can extract shared logic into a helper function instead.\n * `runQuery` incurs overhead of running argument and return value validation,\n * and creating a new isolated JS context.\n *\n * @example\n * ```typescript\n * const user = await ctx.runQuery(internal.users.getUser, { userId });\n * ```\n */\n runQuery: <Query extends FunctionReference<\"query\", \"public\" | \"internal\">>(\n query: Query,\n ...args: ArgsAndOptions<Query, AdvancedRunQueryOptions>\n ) => Promise<FunctionReturnType<Query>>;\n\n /**\n * Call a mutation function within the same transaction.\n *\n * The mutation runs in a sub-transaction, so if it throws an error, all of\n * its writes will be rolled back. Requires a {@link FunctionReference}.\n *\n * NOTE: Often you can extract shared logic into a helper function instead.\n * `runMutation` incurs overhead of running argument and return value\n * validation, and creating a new isolated JS context.\n */\n runMutation: <\n Mutation extends FunctionReference<\"mutation\", \"public\" | \"internal\">,\n >(\n mutation: Mutation,\n ...args: ArgsAndOptions<Mutation, { transactionLimits?: TransactionLimits }>\n ) => Promise<FunctionReturnType<Mutation>>;\n\n meta: MutationMeta;\n}\n\n/**\n * A set of services for use within Convex mutation functions.\n *\n * The mutation context is passed as the first argument to any Convex mutation\n * function run on the server.\n *\n * You should generally use the `MutationCtx` type from\n * `\"./_generated/server\"`.\n *\n * @public\n */\nexport type GenericMutationCtxWithTable<DataModel extends GenericDataModel> =\n Omit<GenericMutationCtx<DataModel>, \"db\"> & {\n db: GenericDatabaseWriterWithTable<DataModel>;\n };\n\n/**\n * A set of services for use within Convex query functions.\n *\n * The query context is passed as the first argument to any Convex query\n * function run on the server. Queries are **read-only**, they can read from\n * the database but cannot write. They are also **reactive**, when used with\n * `useQuery` on the client, the result automatically updates when data changes.\n *\n * You should generally use the `QueryCtx` type from\n * `\"./_generated/server\"`.\n *\n * @example\n * ```typescript\n * import { query } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const listTasks = query({\n * args: {},\n * returns: v.array(v.object({\n * _id: v.id(\"tasks\"),\n * _creationTime: v.number(),\n * text: v.string(),\n * completed: v.boolean(),\n * })),\n * handler: async (ctx, args) => {\n * // ctx.db: read-only database access\n * return await ctx.db.query(\"tasks\").order(\"desc\").take(100);\n * },\n * });\n * ```\n *\n * @public\n */\nexport interface GenericQueryCtx<DataModel extends GenericDataModel> {\n /**\n * A utility for reading data in the database.\n *\n * Use `ctx.db.get(table, id)` to fetch a single document by ID, or\n * `ctx.db.query(\"tableName\")` to query multiple documents with filtering\n * and ordering. Queries are read-only, no write methods are available.\n */\n db: GenericDatabaseReader<DataModel>;\n\n /**\n * Information about the currently authenticated user.\n *\n * Call `await ctx.auth.getUserIdentity()` to get the current user's identity,\n * or `null` if the user is not authenticated.\n */\n auth: Auth;\n\n /**\n * A utility for reading files in storage.\n *\n * Use `ctx.storage.getUrl(storageId)` to get a URL for a stored file.\n */\n storage: StorageReader;\n\n /**\n * Call a query function within the same transaction.\n *\n * The query runs within the same read snapshot. Requires a\n * {@link FunctionReference} (e.g., `api.myModule.myQuery` or\n * `internal.myModule.myQuery`).\n *\n * NOTE: Often you can extract shared logic into a helper function instead.\n * `runQuery` incurs overhead of running argument and return value validation,\n * and creating a new isolated JS context.\n */\n runQuery: <Query extends FunctionReference<\"query\", \"public\" | \"internal\">>(\n query: Query,\n ...args: ArgsAndOptions<Query, { transactionLimits?: TransactionLimits }>\n ) => Promise<FunctionReturnType<Query>>;\n\n meta: QueryMeta;\n}\n\n/**\n * A set of services for use within Convex query functions.\n *\n * The query context is passed as the first argument to any Convex query\n * function run on the server.\n *\n * This differs from the {@link MutationCtx} because all of the services are\n * read-only.\n *\n *\n * @public\n */\nexport type GenericQueryCtxWithTable<DataModel extends GenericDataModel> = Omit<\n GenericQueryCtx<DataModel>,\n \"db\"\n> & {\n db: GenericDatabaseReaderWithTable<DataModel>;\n};\n\n/**\n * A set of services for use within Convex action functions.\n *\n * The action context is passed as the first argument to any Convex action\n * run on the server. Actions can call external APIs and use Node.js libraries,\n * but do **not** have direct database access (`ctx.db` is not available).\n * Use `ctx.runQuery` and `ctx.runMutation` to interact with the database.\n *\n * You should generally use the `ActionCtx` type from\n * `\"./_generated/server\"`.\n *\n * @example\n * ```typescript\n * import { action } from \"./_generated/server\";\n * import { internal } from \"./_generated/api\";\n * import { v } from \"convex/values\";\n *\n * export const processPayment = action({\n * args: { orderId: v.id(\"orders\"), amount: v.number() },\n * returns: v.null(),\n * handler: async (ctx, args) => {\n * // Read data via ctx.runQuery:\n * const order = await ctx.runQuery(internal.orders.get, { id: args.orderId });\n *\n * // Call external API:\n * const result = await fetch(\"https://api.stripe.com/v1/charges\", { ... });\n *\n * // Write results back via ctx.runMutation:\n * await ctx.runMutation(internal.orders.markPaid, { id: args.orderId });\n *\n * return null;\n * },\n * });\n * ```\n *\n * **Common mistake:** `ctx.db` is not available in actions. Do not try to\n * access it, use `ctx.runQuery` and `ctx.runMutation` instead.\n *\n * @public\n */\nexport interface GenericActionCtx<DataModel extends GenericDataModel> {\n /**\n * Run the Convex query with the given name and arguments.\n *\n * Each `runQuery` call is a separate read transaction. Consider using an\n * {@link internalQuery} to prevent users from calling the query directly.\n *\n * @example\n * ```typescript\n * const user = await ctx.runQuery(internal.users.get, { userId });\n * ```\n *\n * @param query - A {@link FunctionReference} for the query to run.\n * @param args - The arguments to the query function.\n * @returns A promise of the query's result.\n */\n runQuery<Query extends FunctionReference<\"query\", \"public\" | \"internal\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>>;\n\n /**\n * Run the Convex mutation with the given name and arguments.\n *\n * Each `runMutation` call is a separate write transaction. Consider using\n * an {@link internalMutation} to prevent users from calling it directly.\n *\n * @example\n * ```typescript\n * await ctx.runMutation(internal.orders.markPaid, { id: orderId });\n * ```\n *\n * @param mutation - A {@link FunctionReference} for the mutation to run.\n * @param args - The arguments to the mutation function.\n * @returns A promise of the mutation's result.\n */\n runMutation<\n Mutation extends FunctionReference<\"mutation\", \"public\" | \"internal\">,\n >(\n mutation: Mutation,\n ...args: OptionalRestArgs<Mutation>\n ): Promise<FunctionReturnType<Mutation>>;\n\n /**\n * Run the Convex action with the given name and arguments.\n *\n * **Important:** Only use `runAction` when you need to cross runtimes\n * (e.g., calling a `\"use node\"` action from the default Convex runtime).\n * For code in the same runtime, extract shared logic into a plain\n * TypeScript helper function instead, `runAction` has significant\n * overhead (separate function call, separate resource allocation).\n *\n * Consider using an {@link internalAction} to prevent users from calling the\n * action directly.\n *\n * @param action - A {@link FunctionReference} for the action to run.\n * @param args - The arguments to the action function.\n * @returns A promise of the action's result.\n */\n runAction<Action extends FunctionReference<\"action\", \"public\" | \"internal\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>>;\n\n /**\n * A utility for scheduling Convex functions to run in the future.\n */\n scheduler: Scheduler;\n\n /**\n * Information about the currently authenticated user.\n */\n auth: Auth;\n\n /**\n * A utility for reading and writing files in storage.\n */\n storage: StorageActionWriter;\n\n /**\n * Run a vector search on the given table and index.\n *\n * @param tableName - The name of the table to query.\n * @param indexName - The name of the vector index on the table to query.\n * @param query - A {@link VectorSearchQuery} containing the vector to query,\n * the number of results to return, and any filters.\n * @returns A promise of IDs and scores for the documents with the nearest\n * vectors\n */\n vectorSearch<\n TableName extends TableNamesInDataModel<DataModel>,\n IndexName extends VectorIndexNames<NamedTableInfo<DataModel, TableName>>,\n >(\n tableName: TableName,\n indexName: IndexName,\n query: Expand<\n VectorSearchQuery<NamedTableInfo<DataModel, TableName>, IndexName>\n >,\n ): Promise<Array<{ _id: Id<TableName>; _score: number }>>;\n\n meta: ActionMeta;\n}\n\n/**\n * The default arguments type for a Convex query, mutation, or action function.\n *\n * Convex functions always take an arguments object that maps the argument\n * names to their values.\n *\n * @public\n */\nexport type DefaultFunctionArgs = Record<string, unknown>;\n\n/**\n * The arguments array for a function that takes arguments.\n *\n * This is an array of a single {@link DefaultFunctionArgs} element.\n */\ntype OneArgArray<ArgsObject extends DefaultFunctionArgs = DefaultFunctionArgs> =\n [ArgsObject];\n\n/**\n * The arguments to a function that takes no arguments (just an empty array).\n */\ntype NoArgsArray = [];\n\n/**\n * An array of arguments to a Convex function.\n *\n * Convex functions can take either a single {@link DefaultFunctionArgs} object or no\n * args at all.\n *\n * @public\n */\nexport type ArgsArray = OneArgArray | NoArgsArray;\n\n/**\n * A type for the empty object `{}`.\n *\n * Note that we don't use `type EmptyObject = {}` because that matches every object.\n */\nexport type EmptyObject = Record<string, never>;\n\n/**\n * Convert an {@link ArgsArray} into a single object type.\n *\n * Empty arguments arrays are converted to {@link EmptyObject}.\n * @public\n */\nexport type ArgsArrayToObject<Args extends ArgsArray> =\n Args extends OneArgArray<infer ArgsObject> ? ArgsObject : EmptyObject;\n\n/**\n * A type representing the visibility of a Convex function.\n *\n * @public\n */\nexport type FunctionVisibility = \"public\" | \"internal\";\n\n/**\n * Given a {@link FunctionVisibility}, should this function have `isPublic: true`\n * or `isInternal: true`?\n */\ntype VisibilityProperties<Visiblity extends FunctionVisibility> = {\n /** Phantom type marker; not present at runtime. */\n _visibility: Visiblity;\n} & (Visiblity extends \"public\"\n ? {\n isPublic: true;\n }\n : {\n isInternal: true;\n });\n\n/**\n * A mutation function that is part of this app.\n *\n * You can create a mutation by wrapping your function in\n * {@link mutationGeneric} or {@link internalMutationGeneric} and exporting it.\n *\n * @public\n */\nexport type RegisteredMutation<\n Visibility extends FunctionVisibility,\n Args extends DefaultFunctionArgs,\n Returns,\n> = {\n isConvexFunction: true;\n isMutation: true;\n\n /** @internal */\n invokeMutation(argsStr: string): Promise<string>;\n\n /** @internal */\n exportArgs(): string;\n\n /** @internal */\n exportReturns(): string;\n\n /** @internal */\n _handler: (ctx: GenericMutationCtx<any>, args: Args) => Returns;\n} & VisibilityProperties<Visibility>;\n\n/**\n * A query function that is part of this app.\n *\n * You can create a query by wrapping your function in\n * {@link queryGeneric} or {@link internalQueryGeneric} and exporting it.\n *\n * @public\n */\nexport type RegisteredQuery<\n Visibility extends FunctionVisibility,\n Args extends DefaultFunctionArgs,\n Returns,\n> = {\n isConvexFunction: true;\n isQuery: true;\n\n /** @internal */\n invokeQuery(argsStr: string): Promise<string>;\n\n /** @internal */\n exportArgs(): string;\n\n /** @internal */\n exportReturns(): string;\n\n /** @internal */\n _handler: (ctx: GenericQueryCtx<any>, args: Args) => Returns;\n} & VisibilityProperties<Visibility>;\n\n/**\n * An action that is part of this app.\n *\n * You can create an action by wrapping your function in\n * {@link actionGeneric} or {@link internalActionGeneric} and exporting it.\n *\n * @public\n */\nexport type RegisteredAction<\n Visibility extends FunctionVisibility,\n Args extends DefaultFunctionArgs,\n Returns,\n> = {\n isConvexFunction: true;\n isAction: true;\n\n /** @internal */\n invokeAction(requestId: string, argsStr: string): Promise<string>;\n\n /** @internal */\n exportArgs(): string;\n\n /** @internal */\n exportReturns(): string;\n\n /** @internal */\n _handler: (ctx: GenericActionCtx<any>, args: Args) => Returns;\n} & VisibilityProperties<Visibility>;\n\n/**\n * An HTTP action that is part of this app's public API.\n *\n * You can create public HTTP actions by wrapping your function in\n * {@link httpActionGeneric} and exporting it.\n *\n * @public\n */\nexport type PublicHttpAction = {\n isHttp: true;\n\n /** @internal */\n invokeHttpAction(request: Request): Promise<Response>;\n /** @internal */\n _handler: (ctx: GenericActionCtx<any>, request: Request) => Promise<Response>;\n};\n\n/**\n * @deprecated -- See the type definition for `MutationBuilder` or similar for\n * the types used for defining Convex functions.\n *\n * The definition of a Convex query, mutation, or action function without\n * argument validation.\n *\n * Convex functions always take a context object as their first argument\n * and an (optional) args object as their second argument.\n *\n * This can be written as a function like:\n * ```js\n * import { query } from \"./_generated/server\";\n *\n * export const func = query(({ db }, { arg }) => {...});\n * ```\n * or as an object like:\n *\n * ```js\n * import { query } from \"./_generated/server\";\n *\n * export const func = query({\n * handler: ({ db }, { arg }) => {...},\n * });\n * ```\n * See {@link ValidatedFunction} to add argument validation.\n *\n * @public\n */\nexport type UnvalidatedFunction<Ctx, Args extends ArgsArray, Returns> =\n | ((ctx: Ctx, ...args: Args) => Returns)\n | {\n handler: (ctx: Ctx, ...args: Args) => Returns;\n };\n\n/**\n * @deprecated -- See the type definition for `MutationBuilder` or similar for\n * the types used for defining Convex functions.\n *\n * The definition of a Convex query, mutation, or action function with argument\n * validation.\n *\n * Argument validation allows you to assert that the arguments to this function\n * are the expected type.\n *\n * Example:\n *\n * ```js\n * import { query } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const func = query({\n * args: {\n * arg: v.string()\n * },\n * handler: ({ db }, { arg }) => {...},\n * });\n * ```\n *\n * **For security, argument validation should be added to all public functions in\n * production apps.**\n *\n * See {@link UnvalidatedFunction} for functions without argument validation.\n * @public\n */\nexport interface ValidatedFunction<\n Ctx,\n ArgsValidator extends PropertyValidators,\n Returns,\n> {\n /**\n * A validator for the arguments of this function.\n *\n * This is an object mapping argument names to validators constructed with\n * {@link values.v}.\n *\n * ```js\n * import { v } from \"convex/values\";\n *\n * const args = {\n * stringArg: v.string(),\n * optionalNumberArg: v.optional(v.number()),\n * }\n * ```\n */\n args: ArgsValidator;\n\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator.\n * @returns\n */\n handler: (ctx: Ctx, args: ObjectType<ArgsValidator>) => Returns;\n}\n\n/**\n * There are multiple syntaxes for defining a Convex function:\n * ```\n * - query(async (ctx, args) => {...})\n * - query({ handler: async (ctx, args) => {...} })\n * - query({ args: { a: v.string }, handler: async (ctx, args) => {...} } })\n * - query({ args: { a: v.string }, returns: v.string(), handler: async (ctx, args) => {...} } })\n *```\n *\n * In each of these, we want to correctly infer the type for the arguments and\n * return value, preferring the type derived from a validator if it's provided.\n *\n * To avoid having a separate overload for each, which would show up in error messages,\n * we use the type params -- ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs.\n *\n * The type for ReturnValue and OneOrZeroArgs are constrained by the type or ArgsValidator and\n * ReturnsValidator if they're present, and inferred from any explicit type annotations to the\n * arguments or return value of the function.\n *\n * Below are a few utility types to get the appropriate type constraints based on\n * an optional validator.\n *\n * Additional tricks:\n * - We use Validator | void instead of Validator | undefined because the latter does\n * not work with `strictNullChecks` since it's equivalent to just `Validator`.\n * - We use a tuple type of length 1 to avoid distribution over the union\n * https://github.com/microsoft/TypeScript/issues/29368#issuecomment-453529532\n */\n\nexport type ReturnValueForOptionalValidator<\n ReturnsValidator extends Validator<any, any, any> | PropertyValidators | void,\n> = [ReturnsValidator] extends [Validator<any, any, any>]\n ? ValidatorTypeToReturnType<Infer<ReturnsValidator>>\n : [ReturnsValidator] extends [PropertyValidators]\n ? ValidatorTypeToReturnType<ObjectType<ReturnsValidator>>\n : any;\n\nexport type ArgsArrayForOptionalValidator<\n ArgsValidator extends GenericValidator | PropertyValidators | void,\n> = [ArgsValidator] extends [Validator<any, any, any>]\n ? OneArgArray<Infer<ArgsValidator>>\n : [ArgsValidator] extends [PropertyValidators]\n ? OneArgArray<ObjectType<ArgsValidator>>\n : ArgsArray;\n\nexport type DefaultArgsForOptionalValidator<\n ArgsValidator extends GenericValidator | PropertyValidators | void,\n> = [ArgsValidator] extends [Validator<any, any, any>]\n ? [Infer<ArgsValidator>]\n : [ArgsValidator] extends [PropertyValidators]\n ? [ObjectType<ArgsValidator>]\n : OneArgArray;\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link mutationGeneric} a type specific to your data model.\n * @public\n */\nexport type MutationBuilder<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends\n ArgsArrayForOptionalValidator<ArgsValidator> = DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n mutation:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericMutationCtx<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericMutationCtx<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredMutation<\n Visibility,\n ArgsArrayToObject<OneOrZeroArgs>,\n ReturnValue\n >;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link mutationGeneric} a type specific to your data model.\n * @public\n */\nexport type MutationBuilderWithTable<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends\n ArgsArrayForOptionalValidator<ArgsValidator> = DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n mutation:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericMutationCtxWithTable<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericMutationCtxWithTable<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredMutation<\n Visibility,\n ArgsArrayToObject<OneOrZeroArgs>,\n ReturnValue\n >;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link queryGeneric} a type specific to your data model.\n * @public\n */\nexport type QueryBuilder<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends\n ArgsArrayForOptionalValidator<ArgsValidator> = DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n query:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericQueryCtx<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericQueryCtx<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link queryGeneric} a type specific to your data model.\n * @public\n */\nexport type QueryBuilderWithTable<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends\n ArgsArrayForOptionalValidator<ArgsValidator> = DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n query:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericQueryCtxWithTable<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericQueryCtxWithTable<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link actionGeneric} a type specific to your data model.\n * @public\n */\nexport type ActionBuilder<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends\n ArgsArrayForOptionalValidator<ArgsValidator> = DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n func:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n *\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericActionCtx<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericActionCtx<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredAction<\n Visibility,\n ArgsArrayToObject<OneOrZeroArgs>,\n ReturnValue\n >;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link httpActionGeneric} a type specific to your data model\n * and functions.\n * @public\n */\nexport type HttpActionBuilder = (\n func: (ctx: GenericActionCtx<any>, request: Request) => Promise<Response>,\n) => PublicHttpAction;\n\nexport interface AdvancedRunQueryOptions {\n transactionLimits?: TransactionLimits;\n /**\n * Run a query on a recent snapshot of the database that is not guaranteed\n * to be up-to-date when this transaction commits.\n *\n * This is an advanced feature which can introduce subtle race conditions,\n * so its use is generally discouraged except for specific use-cases where\n * database read conflicts are expected, e.g. reading from an append-only\n * table with immutable records where the only read conflicts are from\n * concurrent appends.\n */\n useStaleSnapshot?: boolean;\n}\n"],
|
|
4
|
+
"sourcesContent": ["import {\n Auth,\n GenericDatabaseReader,\n GenericDatabaseReaderWithTable,\n GenericDatabaseWriter,\n GenericDatabaseWriterWithTable,\n StorageActionWriter,\n StorageReader,\n StorageWriter,\n} from \"./index.js\";\nimport {\n ActionMeta,\n MutationMeta,\n QueryMeta,\n TransactionLimits,\n} from \"./meta.js\";\nimport {\n ArgsAndOptions,\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n ValidatorTypeToReturnType,\n} from \"../server/api.js\";\nimport {\n GenericValidator,\n Infer,\n ObjectType,\n PropertyValidators,\n} from \"../values/validator.js\";\nimport { Id } from \"../values/value.js\";\nimport {\n GenericDataModel,\n NamedTableInfo,\n TableNamesInDataModel,\n VectorIndexNames,\n} from \"./data_model.js\";\nimport { Scheduler } from \"./scheduler.js\";\nimport { VectorSearchQuery } from \"./vector_search.js\";\nimport { Expand } from \"../type_utils.js\";\nimport { Validator } from \"../values/validators.js\";\n\n/**\n * A set of services for use within Convex mutation functions.\n *\n * The mutation context is passed as the first argument to any Convex mutation\n * function run on the server. Mutations run **transactionally**, all reads\n * and writes within a single mutation are atomic and isolated.\n *\n * You should generally use the `MutationCtx` type from\n * `\"./_generated/server\"`.\n *\n * @example\n * ```typescript\n * import { mutation } from \"./_generated/server\";\n * import { internal } from \"./_generated/api\";\n * import { v } from \"convex/values\";\n *\n * export const createTask = mutation({\n * args: { text: v.string() },\n * returns: v.id(\"tasks\"),\n * handler: async (ctx, args) => {\n * // ctx.db: read and write documents\n * const taskId = await ctx.db.insert(\"tasks\", { text: args.text, completed: false });\n *\n * // ctx.auth: check the authenticated user\n * const identity = await ctx.auth.getUserIdentity();\n *\n * // ctx.scheduler: schedule functions for later\n * await ctx.scheduler.runAfter(0, internal.notifications.send, { taskId });\n *\n * return taskId;\n * },\n * });\n * ```\n *\n * @public\n */\nexport interface GenericMutationCtx<DataModel extends GenericDataModel> {\n /**\n * A utility for reading and writing data in the database.\n *\n * Use `ctx.db.insert()`, `ctx.db.patch()`, `ctx.db.replace()`, and\n * `ctx.db.delete()` to write data. Use `ctx.db.get()` and `ctx.db.query()`\n * to read data. All operations within a mutation are atomic.\n */\n db: GenericDatabaseWriter<DataModel>;\n\n /**\n * Information about the currently authenticated user.\n *\n * Call `await ctx.auth.getUserIdentity()` to get the current user's identity,\n * or `null` if the user is not authenticated.\n */\n auth: Auth;\n\n /**\n * A utility for reading and writing files in storage.\n *\n * Use `ctx.storage.generateUploadUrl()` to create an upload URL for clients,\n * `ctx.storage.getUrl(storageId)` to get a URL for a stored file,\n * or `ctx.storage.delete(storageId)` to remove one.\n */\n storage: StorageWriter;\n\n /**\n * A utility for scheduling Convex functions to run in the future.\n *\n * @example\n * ```typescript\n * // Schedule an action to run immediately after this mutation commits:\n * await ctx.scheduler.runAfter(0, internal.emails.sendWelcome, { userId });\n *\n * // Schedule a cleanup to run in 24 hours:\n * await ctx.scheduler.runAfter(24 * 60 * 60 * 1000, internal.tasks.cleanup, {});\n * ```\n */\n scheduler: Scheduler;\n\n /**\n * Call a query function within the same transaction.\n *\n * The query runs within the same transaction as the calling mutation,\n * seeing a consistent snapshot of the database. Requires a\n * {@link FunctionReference} (e.g., `api.myModule.myQuery` or\n * `internal.myModule.myQuery`).\n *\n * NOTE: Often you can extract shared logic into a helper function instead.\n * `runQuery` incurs overhead of running argument and return value validation,\n * and creating a new isolated JS context.\n *\n * @example\n * ```typescript\n * const user = await ctx.runQuery(internal.users.getUser, { userId });\n * ```\n */\n runQuery: <Query extends FunctionReference<\"query\", \"public\" | \"internal\">>(\n query: Query,\n ...args: ArgsAndOptions<Query, AdvancedRunQueryOptions>\n ) => Promise<FunctionReturnType<Query>>;\n\n /**\n * Call a mutation function within the same transaction.\n *\n * The mutation runs in a sub-transaction, so if it throws an error, all of\n * its writes will be rolled back. Requires a {@link FunctionReference}.\n *\n * NOTE: Often you can extract shared logic into a helper function instead.\n * `runMutation` incurs overhead of running argument and return value\n * validation, and creating a new isolated JS context.\n */\n runMutation: <\n Mutation extends FunctionReference<\"mutation\", \"public\" | \"internal\">,\n >(\n mutation: Mutation,\n ...args: ArgsAndOptions<Mutation, { transactionLimits?: TransactionLimits }>\n ) => Promise<FunctionReturnType<Mutation>>;\n\n meta: MutationMeta;\n}\n\n/**\n * A set of services for use within Convex mutation functions.\n *\n * The mutation context is passed as the first argument to any Convex mutation\n * function run on the server.\n *\n * You should generally use the `MutationCtx` type from\n * `\"./_generated/server\"`.\n *\n * @public\n */\nexport type GenericMutationCtxWithTable<DataModel extends GenericDataModel> =\n Omit<GenericMutationCtx<DataModel>, \"db\"> & {\n db: GenericDatabaseWriterWithTable<DataModel>;\n };\n\n/**\n * A set of services for use within Convex query functions.\n *\n * The query context is passed as the first argument to any Convex query\n * function run on the server. Queries are **read-only**, they can read from\n * the database but cannot write. They are also **reactive**, when used with\n * `useQuery` on the client, the result automatically updates when data changes.\n *\n * You should generally use the `QueryCtx` type from\n * `\"./_generated/server\"`.\n *\n * @example\n * ```typescript\n * import { query } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const listTasks = query({\n * args: {},\n * returns: v.array(v.object({\n * _id: v.id(\"tasks\"),\n * _creationTime: v.number(),\n * text: v.string(),\n * completed: v.boolean(),\n * })),\n * handler: async (ctx, args) => {\n * // ctx.db: read-only database access\n * return await ctx.db.query(\"tasks\").order(\"desc\").take(100);\n * },\n * });\n * ```\n *\n * @public\n */\nexport interface GenericQueryCtx<DataModel extends GenericDataModel> {\n /**\n * A utility for reading data in the database.\n *\n * Use `ctx.db.get(table, id)` to fetch a single document by ID, or\n * `ctx.db.query(\"tableName\")` to query multiple documents with filtering\n * and ordering. Queries are read-only, no write methods are available.\n */\n db: GenericDatabaseReader<DataModel>;\n\n /**\n * Information about the currently authenticated user.\n *\n * Call `await ctx.auth.getUserIdentity()` to get the current user's identity,\n * or `null` if the user is not authenticated.\n */\n auth: Auth;\n\n /**\n * A utility for reading files in storage.\n *\n * Use `ctx.storage.getUrl(storageId)` to get a URL for a stored file.\n */\n storage: StorageReader;\n\n /**\n * Call a query function within the same transaction.\n *\n * The query runs within the same read snapshot. Requires a\n * {@link FunctionReference} (e.g., `api.myModule.myQuery` or\n * `internal.myModule.myQuery`).\n *\n * NOTE: Often you can extract shared logic into a helper function instead.\n * `runQuery` incurs overhead of running argument and return value validation,\n * and creating a new isolated JS context.\n */\n runQuery: <Query extends FunctionReference<\"query\", \"public\" | \"internal\">>(\n query: Query,\n ...args: ArgsAndOptions<Query, { transactionLimits?: TransactionLimits }>\n ) => Promise<FunctionReturnType<Query>>;\n\n meta: QueryMeta;\n}\n\n/**\n * A set of services for use within Convex query functions.\n *\n * The query context is passed as the first argument to any Convex query\n * function run on the server.\n *\n * This differs from the {@link MutationCtx} because all of the services are\n * read-only.\n *\n *\n * @public\n */\nexport type GenericQueryCtxWithTable<DataModel extends GenericDataModel> = Omit<\n GenericQueryCtx<DataModel>,\n \"db\"\n> & {\n db: GenericDatabaseReaderWithTable<DataModel>;\n};\n\n/**\n * A set of services for use within Convex action functions.\n *\n * The action context is passed as the first argument to any Convex action\n * run on the server. Actions can call external APIs and use Node.js libraries,\n * but do **not** have direct database access (`ctx.db` is not available).\n * Use `ctx.runQuery` and `ctx.runMutation` to interact with the database.\n *\n * You should generally use the `ActionCtx` type from\n * `\"./_generated/server\"`.\n *\n * @example\n * ```typescript\n * import { action } from \"./_generated/server\";\n * import { internal } from \"./_generated/api\";\n * import { v } from \"convex/values\";\n *\n * export const processPayment = action({\n * args: { orderId: v.id(\"orders\"), amount: v.number() },\n * returns: v.null(),\n * handler: async (ctx, args) => {\n * // Read data via ctx.runQuery:\n * const order = await ctx.runQuery(internal.orders.get, { id: args.orderId });\n *\n * // Call external API:\n * const result = await fetch(\"https://api.stripe.com/v1/charges\", { ... });\n *\n * // Write results back via ctx.runMutation:\n * await ctx.runMutation(internal.orders.markPaid, { id: args.orderId });\n *\n * return null;\n * },\n * });\n * ```\n *\n * **Common mistake:** `ctx.db` is not available in actions. Do not try to\n * access it, use `ctx.runQuery` and `ctx.runMutation` instead.\n *\n * @public\n */\nexport interface GenericActionCtx<DataModel extends GenericDataModel> {\n /**\n * Run the Convex query with the given name and arguments.\n *\n * Each `runQuery` call is a separate read transaction. Consider using an\n * {@link internalQuery} to prevent users from calling the query directly.\n *\n * @example\n * ```typescript\n * const user = await ctx.runQuery(internal.users.get, { userId });\n * ```\n *\n * @param query - A {@link FunctionReference} for the query to run.\n * @param args - The arguments to the query function.\n * @returns A promise of the query's result.\n */\n runQuery<Query extends FunctionReference<\"query\", \"public\" | \"internal\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>>;\n\n /**\n * Run the Convex mutation with the given name and arguments.\n *\n * Each `runMutation` call is a separate write transaction. Consider using\n * an {@link internalMutation} to prevent users from calling it directly.\n *\n * @example\n * ```typescript\n * await ctx.runMutation(internal.orders.markPaid, { id: orderId });\n * ```\n *\n * @param mutation - A {@link FunctionReference} for the mutation to run.\n * @param args - The arguments to the mutation function.\n * @returns A promise of the mutation's result.\n */\n runMutation<\n Mutation extends FunctionReference<\"mutation\", \"public\" | \"internal\">,\n >(\n mutation: Mutation,\n ...args: OptionalRestArgs<Mutation>\n ): Promise<FunctionReturnType<Mutation>>;\n\n /**\n * Run the Convex action with the given name and arguments.\n *\n * **Important:** Only use `runAction` when you need to cross runtimes\n * (e.g., calling a `\"use node\"` action from the default Convex runtime).\n * For code in the same runtime, extract shared logic into a plain\n * TypeScript helper function instead, `runAction` has significant\n * overhead (separate function call, separate resource allocation).\n *\n * Consider using an {@link internalAction} to prevent users from calling the\n * action directly.\n *\n * @param action - A {@link FunctionReference} for the action to run.\n * @param args - The arguments to the action function.\n * @returns A promise of the action's result.\n */\n runAction<Action extends FunctionReference<\"action\", \"public\" | \"internal\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>>;\n\n /**\n * A utility for scheduling Convex functions to run in the future.\n */\n scheduler: Scheduler;\n\n /**\n * Information about the currently authenticated user.\n */\n auth: Auth;\n\n /**\n * A utility for reading and writing files in storage.\n */\n storage: StorageActionWriter;\n\n /**\n * Run a vector search on the given table and index.\n *\n * @param tableName - The name of the table to query.\n * @param indexName - The name of the vector index on the table to query.\n * @param query - A {@link VectorSearchQuery} containing the vector to query,\n * the number of results to return, and any filters.\n * @returns A promise of IDs and scores for the documents with the nearest\n * vectors\n */\n vectorSearch<\n TableName extends TableNamesInDataModel<DataModel>,\n IndexName extends VectorIndexNames<NamedTableInfo<DataModel, TableName>>,\n >(\n tableName: TableName,\n indexName: IndexName,\n query: Expand<\n VectorSearchQuery<NamedTableInfo<DataModel, TableName>, IndexName>\n >,\n ): Promise<Array<{ _id: Id<TableName>; _score: number }>>;\n\n meta: ActionMeta;\n}\n\n/**\n * The default arguments type for a Convex query, mutation, or action function.\n *\n * Convex functions always take an arguments object that maps the argument\n * names to their values.\n *\n * @public\n */\nexport type DefaultFunctionArgs = Record<string, unknown>;\n\n/**\n * The arguments array for a function that takes arguments.\n *\n * This is an array of a single {@link DefaultFunctionArgs} element.\n */\ntype OneArgArray<ArgsObject extends DefaultFunctionArgs = DefaultFunctionArgs> =\n [ArgsObject];\n\n/**\n * The arguments to a function that takes no arguments (just an empty array).\n */\ntype NoArgsArray = [];\n\n/**\n * An array of arguments to a Convex function.\n *\n * Convex functions can take either a single {@link DefaultFunctionArgs} object or no\n * args at all.\n *\n * @public\n */\nexport type ArgsArray = OneArgArray | NoArgsArray;\n\n/**\n * A type for the empty object `{}`.\n *\n * Note that we don't use `type EmptyObject = {}` because that matches every object.\n */\nexport type EmptyObject = Record<string, never>;\n\n/**\n * Convert an {@link ArgsArray} into a single object type.\n *\n * Empty arguments arrays are converted to {@link EmptyObject}.\n * @public\n */\nexport type ArgsArrayToObject<Args extends ArgsArray> =\n Args extends OneArgArray<infer ArgsObject> ? ArgsObject : EmptyObject;\n\n/**\n * A type representing the visibility of a Convex function.\n *\n * @public\n */\nexport type FunctionVisibility = \"public\" | \"internal\";\n\n/**\n * Given a {@link FunctionVisibility}, should this function have `isPublic: true`\n * or `isInternal: true`?\n */\ntype VisibilityProperties<Visiblity extends FunctionVisibility> = {\n /** Phantom type marker; not present at runtime. */\n _visibility: Visiblity;\n} & (Visiblity extends \"public\"\n ? {\n isPublic: true;\n }\n : {\n isInternal: true;\n });\n\n/**\n * A mutation function that is part of this app.\n *\n * You can create a mutation by wrapping your function in\n * {@link mutationGeneric} or {@link internalMutationGeneric} and exporting it.\n *\n * @public\n */\nexport type RegisteredMutation<\n Visibility extends FunctionVisibility,\n Args extends DefaultFunctionArgs,\n Returns,\n> = {\n isConvexFunction: true;\n isMutation: true;\n\n /** @internal */\n invokeMutation(argsStr: string): Promise<string>;\n\n /** @internal */\n exportArgs(): string;\n\n /** @internal */\n exportReturns(): string;\n\n /** @internal */\n _handler: (ctx: GenericMutationCtx<any>, args: Args) => Returns;\n} & VisibilityProperties<Visibility>;\n\n/**\n * A query function that is part of this app.\n *\n * You can create a query by wrapping your function in\n * {@link queryGeneric} or {@link internalQueryGeneric} and exporting it.\n *\n * @public\n */\nexport type RegisteredQuery<\n Visibility extends FunctionVisibility,\n Args extends DefaultFunctionArgs,\n Returns,\n> = {\n isConvexFunction: true;\n isQuery: true;\n\n /** @internal */\n invokeQuery(argsStr: string): Promise<string>;\n\n /** @internal */\n exportArgs(): string;\n\n /** @internal */\n exportReturns(): string;\n\n /** @internal */\n _handler: (ctx: GenericQueryCtx<any>, args: Args) => Returns;\n} & VisibilityProperties<Visibility>;\n\n/**\n * An action that is part of this app.\n *\n * You can create an action by wrapping your function in\n * {@link actionGeneric} or {@link internalActionGeneric} and exporting it.\n *\n * @public\n */\nexport type RegisteredAction<\n Visibility extends FunctionVisibility,\n Args extends DefaultFunctionArgs,\n Returns,\n> = {\n isConvexFunction: true;\n isAction: true;\n\n /** @internal */\n invokeAction(requestId: string, argsStr: string): Promise<string>;\n\n /** @internal */\n exportArgs(): string;\n\n /** @internal */\n exportReturns(): string;\n\n /** @internal */\n _handler: (ctx: GenericActionCtx<any>, args: Args) => Returns;\n} & VisibilityProperties<Visibility>;\n\n/**\n * An HTTP action that is part of this app's public API.\n *\n * You can create public HTTP actions by wrapping your function in\n * {@link httpActionGeneric} and exporting it.\n *\n * @public\n */\nexport type PublicHttpAction = {\n isHttp: true;\n\n /** @internal */\n invokeHttpAction(request: Request): Promise<Response>;\n /** @internal */\n _handler: (ctx: GenericActionCtx<any>, request: Request) => Promise<Response>;\n};\n\n/**\n * @deprecated -- See the type definition for `MutationBuilder` or similar for\n * the types used for defining Convex functions.\n *\n * The definition of a Convex query, mutation, or action function without\n * argument validation.\n *\n * Convex functions always take a context object as their first argument\n * and an (optional) args object as their second argument.\n *\n * This can be written as a function like:\n * ```js\n * import { query } from \"./_generated/server\";\n *\n * export const func = query(({ db }, { arg }) => {...});\n * ```\n * or as an object like:\n *\n * ```js\n * import { query } from \"./_generated/server\";\n *\n * export const func = query({\n * handler: ({ db }, { arg }) => {...},\n * });\n * ```\n * See {@link ValidatedFunction} to add argument validation.\n *\n * @public\n */\nexport type UnvalidatedFunction<Ctx, Args extends ArgsArray, Returns> =\n | ((ctx: Ctx, ...args: Args) => Returns)\n | {\n handler: (ctx: Ctx, ...args: Args) => Returns;\n };\n\n/**\n * @deprecated -- See the type definition for `MutationBuilder` or similar for\n * the types used for defining Convex functions.\n *\n * The definition of a Convex query, mutation, or action function with argument\n * validation.\n *\n * Argument validation allows you to assert that the arguments to this function\n * are the expected type.\n *\n * Example:\n *\n * ```js\n * import { query } from \"./_generated/server\";\n * import { v } from \"convex/values\";\n *\n * export const func = query({\n * args: {\n * arg: v.string()\n * },\n * handler: ({ db }, { arg }) => {...},\n * });\n * ```\n *\n * **For security, argument validation should be added to all public functions in\n * production apps.**\n *\n * See {@link UnvalidatedFunction} for functions without argument validation.\n * @public\n */\nexport interface ValidatedFunction<\n Ctx,\n ArgsValidator extends PropertyValidators,\n Returns,\n> {\n /**\n * A validator for the arguments of this function.\n *\n * This is an object mapping argument names to validators constructed with\n * {@link values.v}.\n *\n * ```js\n * import { v } from \"convex/values\";\n *\n * const args = {\n * stringArg: v.string(),\n * optionalNumberArg: v.optional(v.number()),\n * }\n * ```\n */\n args: ArgsValidator;\n\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator.\n * @returns\n */\n handler: (ctx: Ctx, args: ObjectType<ArgsValidator>) => Returns;\n}\n\n/**\n * There are multiple syntaxes for defining a Convex function:\n * ```\n * - query(async (ctx, args) => {...})\n * - query({ handler: async (ctx, args) => {...} })\n * - query({ args: { a: v.string }, handler: async (ctx, args) => {...} } })\n * - query({ args: { a: v.string }, returns: v.string(), handler: async (ctx, args) => {...} } })\n *```\n *\n * In each of these, we want to correctly infer the type for the arguments and\n * return value, preferring the type derived from a validator if it's provided.\n *\n * To avoid having a separate overload for each, which would show up in error messages,\n * we use the type params -- ArgsValidator, ReturnsValidator, ReturnValue, OneOrZeroArgs.\n *\n * The type for ReturnValue and OneOrZeroArgs are constrained by the type or ArgsValidator and\n * ReturnsValidator if they're present, and inferred from any explicit type annotations to the\n * arguments or return value of the function.\n *\n * Below are a few utility types to get the appropriate type constraints based on\n * an optional validator.\n *\n * Additional tricks:\n * - We use Validator | void instead of Validator | undefined because the latter does\n * not work with `strictNullChecks` since it's equivalent to just `Validator`.\n * - We use a tuple type of length 1 to avoid distribution over the union\n * https://github.com/microsoft/TypeScript/issues/29368#issuecomment-453529532\n */\n\nexport type ReturnValueForOptionalValidator<\n ReturnsValidator extends Validator<any, any, any> | PropertyValidators | void,\n> = [ReturnsValidator] extends [Validator<any, any, any>]\n ? ValidatorTypeToReturnType<Infer<ReturnsValidator>>\n : [ReturnsValidator] extends [PropertyValidators]\n ? ValidatorTypeToReturnType<ObjectType<ReturnsValidator>>\n : any;\n\nexport type ArgsArrayForOptionalValidator<\n ArgsValidator extends GenericValidator | PropertyValidators | void,\n> = [ArgsValidator] extends [Validator<any, any, any>]\n ? OneArgArray<Infer<ArgsValidator>>\n : [ArgsValidator] extends [PropertyValidators]\n ? OneArgArray<ObjectType<ArgsValidator>>\n : ArgsArray;\n\nexport type DefaultArgsForOptionalValidator<\n ArgsValidator extends GenericValidator | PropertyValidators | void,\n> = [ArgsValidator] extends [Validator<any, any, any>]\n ? [Infer<ArgsValidator>]\n : [ArgsValidator] extends [PropertyValidators]\n ? [ObjectType<ArgsValidator>]\n : OneArgArray;\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link mutationGeneric} a type specific to your data model.\n * @public\n */\nexport type MutationBuilder<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends ArgsArrayForOptionalValidator<ArgsValidator> =\n DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n mutation:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericMutationCtx<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericMutationCtx<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredMutation<\n Visibility,\n ArgsArrayToObject<OneOrZeroArgs>,\n ReturnValue\n >;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link mutationGeneric} a type specific to your data model.\n * @public\n */\nexport type MutationBuilderWithTable<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends ArgsArrayForOptionalValidator<ArgsValidator> =\n DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n mutation:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericMutationCtxWithTable<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericMutationCtxWithTable<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredMutation<\n Visibility,\n ArgsArrayToObject<OneOrZeroArgs>,\n ReturnValue\n >;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link queryGeneric} a type specific to your data model.\n * @public\n */\nexport type QueryBuilder<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends ArgsArrayForOptionalValidator<ArgsValidator> =\n DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n query:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericQueryCtx<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericQueryCtx<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link queryGeneric} a type specific to your data model.\n * @public\n */\nexport type QueryBuilderWithTable<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends ArgsArrayForOptionalValidator<ArgsValidator> =\n DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n query:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericQueryCtxWithTable<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericQueryCtxWithTable<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredQuery<Visibility, ArgsArrayToObject<OneOrZeroArgs>, ReturnValue>;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link actionGeneric} a type specific to your data model.\n * @public\n */\nexport type ActionBuilder<\n DataModel extends GenericDataModel,\n Visibility extends FunctionVisibility,\n> = {\n <\n ArgsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnsValidator extends\n | PropertyValidators\n | Validator<any, \"required\", any>\n | void,\n ReturnValue extends ReturnValueForOptionalValidator<ReturnsValidator> = any,\n OneOrZeroArgs extends ArgsArrayForOptionalValidator<ArgsValidator> =\n DefaultArgsForOptionalValidator<ArgsValidator>,\n >(\n func:\n | {\n /**\n * Argument validation.\n *\n * Examples:\n *\n * ```\n * args: {}\n * args: { input: v.optional(v.number()) }\n * args: { message: v.string(), author: v.id(\"authors\") }\n * args: { messages: v.array(v.string()) }\n * ```\n *\n */\n args?: ArgsValidator;\n /**\n * The return value validator.\n *\n * Examples:\n *\n * ```\n * returns: v.null()\n * returns: v.string()\n * returns: { message: v.string(), author: v.id(\"authors\") }\n * returns: v.array(v.string())\n * ```\n */\n returns?: ReturnsValidator;\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n handler: (\n ctx: GenericActionCtx<DataModel>,\n ...args: OneOrZeroArgs\n ) => ReturnValue;\n }\n | {\n /**\n * The implementation of this function.\n *\n * This is a function that takes in the appropriate context and arguments\n * and produces some result.\n *\n * @param ctx - The context object. This is one of {@link QueryCtx},\n * {@link MutationCtx}, or {@link ActionCtx} depending on the function type.\n * @param args - The arguments object for this function. This will match\n * the type defined by the argument validator if provided.\n * @returns\n */\n (\n ctx: GenericActionCtx<DataModel>,\n ...args: OneOrZeroArgs\n ): ReturnValue;\n },\n ): RegisteredAction<\n Visibility,\n ArgsArrayToObject<OneOrZeroArgs>,\n ReturnValue\n >;\n};\n\n/**\n * Internal type helper used by Convex code generation.\n *\n * Used to give {@link httpActionGeneric} a type specific to your data model\n * and functions.\n * @public\n */\nexport type HttpActionBuilder = (\n func: (ctx: GenericActionCtx<any>, request: Request) => Promise<Response>,\n) => PublicHttpAction;\n\nexport interface AdvancedRunQueryOptions {\n transactionLimits?: TransactionLimits;\n /**\n * Run a query on a recent snapshot of the database that is not guaranteed\n * to be up-to-date when this transaction commits.\n *\n * This is an advanced feature which can introduce subtle race conditions,\n * so its use is generally discouraged except for specific use-cases where\n * database read conflicts are expected, e.g. reading from an append-only\n * table with immutable records where the only read conflicts are from\n * concurrent appends.\n */\n useStaleSnapshot?: boolean;\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|