convex 1.41.0 → 1.42.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.
Files changed (167) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/browser.bundle.js +1 -1
  3. package/dist/browser.bundle.js.map +1 -1
  4. package/dist/cjs/browser/simple_client-node.js +85 -27
  5. package/dist/cjs/browser/simple_client-node.js.map +3 -3
  6. package/dist/cjs/cli/env.js +12 -5
  7. package/dist/cjs/cli/env.js.map +2 -2
  8. package/dist/cjs/cli/envDefault.js +12 -7
  9. package/dist/cjs/cli/envDefault.js.map +2 -2
  10. package/dist/cjs/cli/insights.js +11 -1
  11. package/dist/cjs/cli/insights.js.map +2 -2
  12. package/dist/cjs/cli/lib/env.js +5 -1
  13. package/dist/cjs/cli/lib/env.js.map +2 -2
  14. package/dist/cjs/cli/lib/login.js +16 -12
  15. package/dist/cjs/cli/lib/login.js.map +2 -2
  16. package/dist/cjs/cli/lib/logs.js +4 -1
  17. package/dist/cjs/cli/lib/logs.js.map +2 -2
  18. package/dist/cjs/cli/lib/run.js +27 -2
  19. package/dist/cjs/cli/lib/run.js.map +2 -2
  20. package/dist/cjs/cli/lib/utils/utils.js +30 -0
  21. package/dist/cjs/cli/lib/utils/utils.js.map +2 -2
  22. package/dist/cjs/cli/program.js +2 -1
  23. package/dist/cjs/cli/program.js.map +2 -2
  24. package/dist/cjs/cli/project.js +27 -0
  25. package/dist/cjs/cli/project.js.map +7 -0
  26. package/dist/cjs/cli/projectCreate.js +90 -0
  27. package/dist/cjs/cli/projectCreate.js.map +7 -0
  28. package/dist/cjs/index.js +1 -1
  29. package/dist/cjs/index.js.map +1 -1
  30. package/dist/cjs/server/database.js.map +1 -1
  31. package/dist/cjs/server/impl/meta_impl.js +6 -6
  32. package/dist/cjs/server/impl/meta_impl.js.map +2 -2
  33. package/dist/cjs/server/impl/registration_impl.js +9 -2
  34. package/dist/cjs/server/impl/registration_impl.js.map +2 -2
  35. package/dist/cjs/server/index.js.map +2 -2
  36. package/dist/cjs/server/meta.js.map +1 -1
  37. package/dist/cjs/server/query.js.map +1 -1
  38. package/dist/cjs/server/registration.js.map +1 -1
  39. package/dist/cjs/server/storage.js.map +1 -1
  40. package/dist/cjs/server/system_fields.js.map +1 -1
  41. package/dist/cjs-types/cli/env.d.ts.map +1 -1
  42. package/dist/cjs-types/cli/envDefault.d.ts.map +1 -1
  43. package/dist/cjs-types/cli/insights.d.ts +1 -0
  44. package/dist/cjs-types/cli/insights.d.ts.map +1 -1
  45. package/dist/cjs-types/cli/lib/env.d.ts +3 -1
  46. package/dist/cjs-types/cli/lib/env.d.ts.map +1 -1
  47. package/dist/cjs-types/cli/lib/env.test.d.ts +2 -0
  48. package/dist/cjs-types/cli/lib/env.test.d.ts.map +1 -0
  49. package/dist/cjs-types/cli/lib/login.d.ts.map +1 -1
  50. package/dist/cjs-types/cli/lib/logs.d.ts +1 -1
  51. package/dist/cjs-types/cli/lib/logs.d.ts.map +1 -1
  52. package/dist/cjs-types/cli/lib/run.d.ts +1 -1
  53. package/dist/cjs-types/cli/lib/run.d.ts.map +1 -1
  54. package/dist/cjs-types/cli/lib/utils/utils.d.ts +10 -0
  55. package/dist/cjs-types/cli/lib/utils/utils.d.ts.map +1 -1
  56. package/dist/cjs-types/cli/program.d.ts.map +1 -1
  57. package/dist/cjs-types/cli/project.d.ts +3 -0
  58. package/dist/cjs-types/cli/project.d.ts.map +1 -0
  59. package/dist/cjs-types/cli/projectCreate.d.ts +5 -0
  60. package/dist/cjs-types/cli/projectCreate.d.ts.map +1 -0
  61. package/dist/cjs-types/index.d.ts +1 -1
  62. package/dist/cjs-types/server/database.d.ts +21 -3
  63. package/dist/cjs-types/server/database.d.ts.map +1 -1
  64. package/dist/cjs-types/server/impl/meta_impl.d.ts.map +1 -1
  65. package/dist/cjs-types/server/impl/registration_impl.d.ts.map +1 -1
  66. package/dist/cjs-types/server/index.d.ts +1 -1
  67. package/dist/cjs-types/server/index.d.ts.map +1 -1
  68. package/dist/cjs-types/server/meta.d.ts +10 -0
  69. package/dist/cjs-types/server/meta.d.ts.map +1 -1
  70. package/dist/cjs-types/server/query.d.ts +1 -1
  71. package/dist/cjs-types/server/registration.d.ts +15 -3
  72. package/dist/cjs-types/server/registration.d.ts.map +1 -1
  73. package/dist/cjs-types/server/storage.d.ts +20 -3
  74. package/dist/cjs-types/server/storage.d.ts.map +1 -1
  75. package/dist/cli.bundle.cjs +1047 -619
  76. package/dist/cli.bundle.cjs.map +4 -4
  77. package/dist/esm/browser/simple_client-node.js +85 -27
  78. package/dist/esm/browser/simple_client-node.js.map +3 -3
  79. package/dist/esm/cli/env.js +12 -5
  80. package/dist/esm/cli/env.js.map +2 -2
  81. package/dist/esm/cli/envDefault.js +12 -7
  82. package/dist/esm/cli/envDefault.js.map +2 -2
  83. package/dist/esm/cli/insights.js +11 -1
  84. package/dist/esm/cli/insights.js.map +2 -2
  85. package/dist/esm/cli/lib/env.js +5 -1
  86. package/dist/esm/cli/lib/env.js.map +2 -2
  87. package/dist/esm/cli/lib/login.js +18 -13
  88. package/dist/esm/cli/lib/login.js.map +2 -2
  89. package/dist/esm/cli/lib/logs.js +5 -2
  90. package/dist/esm/cli/lib/logs.js.map +2 -2
  91. package/dist/esm/cli/lib/run.js +32 -3
  92. package/dist/esm/cli/lib/run.js.map +2 -2
  93. package/dist/esm/cli/lib/utils/utils.js +29 -0
  94. package/dist/esm/cli/lib/utils/utils.js.map +2 -2
  95. package/dist/esm/cli/program.js +2 -1
  96. package/dist/esm/cli/program.js.map +2 -2
  97. package/dist/esm/cli/project.js +5 -0
  98. package/dist/esm/cli/project.js.map +7 -0
  99. package/dist/esm/cli/projectCreate.js +68 -0
  100. package/dist/esm/cli/projectCreate.js.map +7 -0
  101. package/dist/esm/index.js +1 -1
  102. package/dist/esm/index.js.map +1 -1
  103. package/dist/esm/server/impl/meta_impl.js +6 -6
  104. package/dist/esm/server/impl/meta_impl.js.map +2 -2
  105. package/dist/esm/server/impl/registration_impl.js +9 -2
  106. package/dist/esm/server/impl/registration_impl.js.map +2 -2
  107. package/dist/esm/server/index.js.map +2 -2
  108. package/dist/esm-types/cli/env.d.ts.map +1 -1
  109. package/dist/esm-types/cli/envDefault.d.ts.map +1 -1
  110. package/dist/esm-types/cli/insights.d.ts +1 -0
  111. package/dist/esm-types/cli/insights.d.ts.map +1 -1
  112. package/dist/esm-types/cli/lib/env.d.ts +3 -1
  113. package/dist/esm-types/cli/lib/env.d.ts.map +1 -1
  114. package/dist/esm-types/cli/lib/env.test.d.ts +2 -0
  115. package/dist/esm-types/cli/lib/env.test.d.ts.map +1 -0
  116. package/dist/esm-types/cli/lib/login.d.ts.map +1 -1
  117. package/dist/esm-types/cli/lib/logs.d.ts +1 -1
  118. package/dist/esm-types/cli/lib/logs.d.ts.map +1 -1
  119. package/dist/esm-types/cli/lib/run.d.ts +1 -1
  120. package/dist/esm-types/cli/lib/run.d.ts.map +1 -1
  121. package/dist/esm-types/cli/lib/utils/utils.d.ts +10 -0
  122. package/dist/esm-types/cli/lib/utils/utils.d.ts.map +1 -1
  123. package/dist/esm-types/cli/program.d.ts.map +1 -1
  124. package/dist/esm-types/cli/project.d.ts +3 -0
  125. package/dist/esm-types/cli/project.d.ts.map +1 -0
  126. package/dist/esm-types/cli/projectCreate.d.ts +5 -0
  127. package/dist/esm-types/cli/projectCreate.d.ts.map +1 -0
  128. package/dist/esm-types/index.d.ts +1 -1
  129. package/dist/esm-types/server/database.d.ts +21 -3
  130. package/dist/esm-types/server/database.d.ts.map +1 -1
  131. package/dist/esm-types/server/impl/meta_impl.d.ts.map +1 -1
  132. package/dist/esm-types/server/impl/registration_impl.d.ts.map +1 -1
  133. package/dist/esm-types/server/index.d.ts +1 -1
  134. package/dist/esm-types/server/index.d.ts.map +1 -1
  135. package/dist/esm-types/server/meta.d.ts +10 -0
  136. package/dist/esm-types/server/meta.d.ts.map +1 -1
  137. package/dist/esm-types/server/query.d.ts +1 -1
  138. package/dist/esm-types/server/registration.d.ts +15 -3
  139. package/dist/esm-types/server/registration.d.ts.map +1 -1
  140. package/dist/esm-types/server/storage.d.ts +20 -3
  141. package/dist/esm-types/server/storage.d.ts.map +1 -1
  142. package/dist/react.bundle.js +1 -1
  143. package/dist/react.bundle.js.map +1 -1
  144. package/package.json +4 -4
  145. package/src/cli/env.ts +16 -6
  146. package/src/cli/envDefault.ts +13 -7
  147. package/src/cli/insights.ts +12 -0
  148. package/src/cli/lib/env.test.ts +60 -0
  149. package/src/cli/lib/env.ts +9 -1
  150. package/src/cli/lib/login.ts +18 -18
  151. package/src/cli/lib/logs.ts +7 -2
  152. package/src/cli/lib/run.ts +37 -3
  153. package/src/cli/lib/utils/utils.ts +56 -0
  154. package/src/cli/program.ts +2 -0
  155. package/src/cli/project.ts +7 -0
  156. package/src/cli/projectCreate.ts +99 -0
  157. package/src/index.ts +1 -1
  158. package/src/server/database.ts +21 -3
  159. package/src/server/impl/meta_impl.ts +7 -6
  160. package/src/server/impl/registration_impl.ts +11 -3
  161. package/src/server/index.ts +1 -0
  162. package/src/server/meta.ts +10 -0
  163. package/src/server/query.ts +1 -1
  164. package/src/server/registration.test.ts +25 -1
  165. package/src/server/registration.ts +16 -1
  166. package/src/server/storage.ts +22 -3
  167. package/src/server/system_fields.ts +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/server/database.ts"],
4
- "sourcesContent": ["import { GenericId } from \"../values/index.js\";\nimport {\n DocumentByName,\n GenericDataModel,\n NamedTableInfo,\n TableNamesInDataModel,\n} from \"./data_model.js\";\nimport { QueryInitializer } from \"./query.js\";\nimport { SystemDataModel } from \"./schema.js\";\nimport {\n WithOptionalSystemFields,\n WithoutSystemFields,\n} from \"./system_fields.js\";\n\ninterface BaseDatabaseReader<DataModel extends GenericDataModel> {\n /**\n * Fetch a single document from the database by its {@link values.GenericId}.\n *\n * @param table - The name of the table to fetch the document from.\n * @param id - The {@link values.GenericId} of the document to fetch from the database.\n * @returns - The {@link GenericDocument} of the document at the given {@link values.GenericId}, or `null` if it no longer exists.\n */\n get<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n id: GenericId<NonUnion<TableName>>,\n ): Promise<DocumentByName<DataModel, TableName> | null>;\n\n /**\n * Fetch a single document from the database by its {@link values.GenericId}.\n *\n * @param id - The {@link values.GenericId} of the document to fetch from the database.\n * @returns - The {@link GenericDocument} of the document at the given {@link values.GenericId}, or `null` if it no longer exists.\n */\n get<TableName extends TableNamesInDataModel<DataModel>>(\n id: GenericId<TableName>,\n ): Promise<DocumentByName<DataModel, TableName> | null>;\n\n /**\n * Begin a query for the given table name.\n *\n * Queries don't execute immediately, so calling this method and extending its\n * query are free until the results are actually used.\n *\n * @param tableName - The name of the table to query.\n * @returns - A {@link QueryInitializer} object to start building a query.\n */\n query<TableName extends TableNamesInDataModel<DataModel>>(\n tableName: TableName,\n ): QueryInitializer<NamedTableInfo<DataModel, TableName>>;\n\n /**\n * Returns the string ID format for the ID in a given table, or null if the ID\n * is from a different table or is not a valid ID.\n *\n * This accepts the string ID format as well as the `.toString()` representation\n * of the legacy class-based ID format.\n *\n * This does not guarantee that the ID exists (i.e. `db.get(id)` may return `null`).\n *\n * @param tableName - The name of the table.\n * @param id - The ID string.\n */\n normalizeId<TableName extends TableNamesInDataModel<DataModel>>(\n tableName: TableName,\n id: string,\n ): GenericId<TableName> | null;\n}\n\ninterface BaseDatabaseReaderWithTable<DataModel extends GenericDataModel> {\n /**\n * Scope the database to a specific table.\n */\n table<TableName extends TableNamesInDataModel<DataModel>>(\n tableName: TableName,\n ): BaseTableReader<DataModel, TableName>;\n}\n\nexport interface BaseTableReader<\n DataModel extends GenericDataModel,\n TableName extends TableNamesInDataModel<DataModel>,\n> {\n /**\n * Fetch a single document from the table by its {@link values.GenericId}.\n *\n * @param id - The {@link values.GenericId} of the document to fetch from the database.\n * @returns - The {@link GenericDocument} of the document at the given {@link values.GenericId}, or `null` if it no longer exists.\n */\n get(\n id: GenericId<TableName>,\n ): Promise<DocumentByName<DataModel, TableName> | null>;\n\n /**\n * Begin a query for the table.\n *\n * Queries don't execute immediately, so calling this method and extending its\n * query are free until the results are actually used.\n *\n * @returns - A {@link QueryInitializer} object to start building a query.\n */\n query(): QueryInitializer<NamedTableInfo<DataModel, TableName>>;\n}\n\n/**\n * An interface to read from the database within Convex query functions.\n *\n * Available as `ctx.db` in queries (read-only) and mutations (read-write).\n * You should generally use the `DatabaseReader` type from\n * `\"./_generated/server\"`.\n *\n * The two entry points are:\n * - {@link GenericDatabaseReader.get}, which fetches a single document\n * by its {@link values.GenericId}.\n * - {@link GenericDatabaseReader.query}, which starts building a query.\n *\n * @example\n * ```typescript\n * // Fetch a single document by ID:\n * const user = await ctx.db.get(\"users\", userId);\n *\n * // Query documents with an index:\n * const messages = await ctx.db\n * .query(\"messages\")\n * .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", channelId))\n * .order(\"desc\")\n * .take(50);\n * ```\n *\n * **Best practice:** Use `.withIndex()` instead of `.filter()` for efficient\n * queries. Define indexes in your schema for fields you query frequently.\n *\n * @see https://docs.convex.dev/database/reading-data\n * @public\n */\nexport interface GenericDatabaseReader<DataModel extends GenericDataModel>\n extends BaseDatabaseReader<DataModel> {\n /**\n * An interface to read from the system tables within Convex query functions.\n *\n * System tables include `_storage` (file metadata) and\n * `_scheduled_functions` (scheduled function state). Use `ctx.db.system.get()`\n * and `ctx.db.system.query()` just like regular tables.\n *\n * @example\n * ```typescript\n * // Get file metadata from the _storage system table:\n * const metadata = await ctx.db.system.get(\"_storage\", storageId);\n * // metadata has: _id, _creationTime, contentType, sha256, size\n * ```\n *\n * @public\n */\n system: BaseDatabaseReader<SystemDataModel>;\n}\n\nexport interface GenericDatabaseReaderWithTable<\n DataModel extends GenericDataModel,\n> extends BaseDatabaseReaderWithTable<DataModel> {\n /**\n * An interface to read from the system tables within Convex query functions\n *\n * The two entry points are:\n * - {@link GenericDatabaseReader.get}, which fetches a single document\n * by its {@link values.GenericId}.\n * - {@link GenericDatabaseReader.query}, which starts building a query.\n *\n * @public\n */\n system: BaseDatabaseReaderWithTable<SystemDataModel>;\n}\n\n/**\n * An interface to read from and write to the database within Convex mutation\n * functions.\n *\n * Available as `ctx.db` in mutations. You should generally use the\n * `DatabaseWriter` type from `\"./_generated/server\"`.\n *\n * Extends {@link GenericDatabaseReader}\n * with write operations. All reads and writes within a single mutation are\n * executed **atomically**, you never have to worry about partial writes\n * leaving your data in an inconsistent state.\n *\n * @example\n * ```typescript\n * // Insert a new document:\n * const userId = await ctx.db.insert(\"users\", { name: \"Alice\", email: \"alice@example.com\" });\n *\n * // Update specific fields (shallow merge):\n * await ctx.db.patch(\"users\", userId, { name: \"Alice Smith\" });\n *\n * // Replace entire document (all non-system fields):\n * await ctx.db.replace(\"users\", userId, { name: \"Bob\", email: \"bob@example.com\" });\n *\n * // Delete a document:\n * await ctx.db.delete(\"users\", userId);\n *\n * // Delete multiple documents (collect first, then delete each):\n * const oldTasks = await ctx.db\n * .query(\"tasks\")\n * .withIndex(\"by_completed\", (q) => q.eq(\"completed\", true))\n * .collect();\n * for (const task of oldTasks) {\n * await ctx.db.delete(\"tasks\", task._id);\n * }\n * ```\n *\n * @see https://docs.convex.dev/database/writing-data\n * @public\n */\nexport interface GenericDatabaseWriter<DataModel extends GenericDataModel>\n extends GenericDatabaseReader<DataModel> {\n /**\n * Insert a new document into a table.\n *\n * @example\n * ```typescript\n * const taskId = await ctx.db.insert(\"tasks\", {\n * text: \"Buy groceries\",\n * completed: false,\n * });\n * ```\n *\n * @param table - The name of the table to insert a new document into.\n * @param value - The document to insert. System fields (`_id`, `_creationTime`)\n * are added automatically and should not be included.\n * @returns The {@link values.GenericId} of the new document.\n */\n insert<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n value: WithoutSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<GenericId<TableName>>;\n\n /**\n * Patch an existing document, shallow merging it with the given partial\n * document.\n *\n * New fields are added. Existing fields are overwritten. Fields set to\n * `undefined` are removed. Fields not specified in the patch are left\n * unchanged.\n *\n * This method will throw if the document does not exist.\n *\n * @example\n * ```typescript\n * // Update only the \"completed\" field, leaving other fields unchanged:\n * await ctx.db.patch(\"tasks\", taskId, { completed: true });\n *\n * // Remove an optional field by setting it to undefined:\n * await ctx.db.patch(\"tasks\", taskId, { assignee: undefined });\n * ```\n *\n * **Tip:** Use `patch` for partial updates. Use `replace` when you want to\n * overwrite the entire document.\n *\n * @param table - The name of the table the document is in.\n * @param id - The {@link values.GenericId} of the document to patch.\n * @param value - The partial document to merge into the existing document.\n */\n patch<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n id: GenericId<NonUnion<TableName>>,\n value: PatchValue<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Patch an existing document, shallow merging it with the given partial\n * document.\n *\n * New fields are added. Existing fields are overwritten. Fields set to\n * `undefined` are removed. Fields not specified in the patch are left\n * unchanged.\n *\n * This method will throw if the document does not exist.\n *\n * @param id - The {@link values.GenericId} of the document to patch.\n * @param value - The partial document to merge into the existing document.\n */\n patch<TableName extends TableNamesInDataModel<DataModel>>(\n id: GenericId<TableName>,\n value: PatchValue<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Replace the value of an existing document, overwriting its old value\n * completely.\n *\n * Unlike `patch`, which does a shallow merge, `replace` overwrites the\n * entire document. Any fields not included in the new value will be removed\n * (except system fields `_id` and `_creationTime`).\n *\n * This method will throw if the document does not exist.\n *\n * @example\n * ```typescript\n * // Replace the entire document:\n * await ctx.db.replace(\"users\", userId, {\n * name: \"New Name\",\n * email: \"new@example.com\",\n * });\n * ```\n *\n * @param table - The name of the table the document is in.\n * @param id - The {@link values.GenericId} of the document to replace.\n * @param value - The new document. System fields can be omitted.\n */\n replace<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n id: GenericId<NonUnion<TableName>>,\n value: WithOptionalSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Replace the value of an existing document, overwriting its old value\n * completely.\n *\n * Unlike `patch`, which does a shallow merge, `replace` overwrites the\n * entire document.\n *\n * @param id - The {@link values.GenericId} of the document to replace.\n * @param value - The new document. System fields can be omitted.\n */\n replace<TableName extends TableNamesInDataModel<DataModel>>(\n id: GenericId<TableName>,\n value: WithOptionalSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Delete an existing document.\n *\n * @example\n * ```typescript\n * await ctx.db.delete(\"tasks\", taskId);\n * ```\n *\n * @param table - The name of the table the document is in.\n * @param id - The {@link values.GenericId} of the document to remove.\n */\n delete<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n id: GenericId<NonUnion<TableName>>,\n ): Promise<void>;\n\n /**\n * Delete an existing document.\n *\n * **Note:** Convex queries do not support `.delete()` directly on query\n * results. To delete multiple documents, `.collect()` them first, then\n * delete each one individually.\n *\n * @param id - The {@link values.GenericId} of the document to remove.\n */\n delete(id: GenericId<TableNamesInDataModel<DataModel>>): Promise<void>;\n}\n\n/**\n * An interface to read from and write to the database within Convex mutation\n * functions.\n *\n * You should generally use the `DatabaseWriter` type from\n * `\"./_generated/server\"`.\n *\n * Convex guarantees that all writes within a single mutation are\n * executed atomically, so you never have to worry about partial writes leaving\n * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)\n * for the guarantees Convex provides your functions.\n *\n * @public\n */\nexport interface GenericDatabaseWriterWithTable<\n DataModel extends GenericDataModel,\n> extends GenericDatabaseReaderWithTable<DataModel> {\n /**\n * Scope the database to a specific table.\n */\n table<TableName extends TableNamesInDataModel<DataModel>>(\n tableName: TableName,\n ): BaseTableWriter<DataModel, TableName>;\n}\n\nexport interface BaseTableWriter<\n DataModel extends GenericDataModel,\n TableName extends TableNamesInDataModel<DataModel>,\n> extends BaseTableReader<DataModel, TableName> {\n /**\n * Insert a new document into the table.\n *\n * @param value - The {@link values.Value} to insert into the given table.\n * @returns - {@link values.GenericId} of the new document.\n */\n insert(\n value: WithoutSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<GenericId<TableName>>;\n\n /**\n * Patch an existing document, shallow merging it with the given partial\n * document.\n *\n * New fields are added. Existing fields are overwritten. Fields set to\n * `undefined` are removed.\n *\n * @param id - The {@link values.GenericId} of the document to patch.\n * @param value - The partial {@link GenericDocument} to merge into the specified document. If this new value\n * specifies system fields like `_id`, they must match the document's existing field values.\n */\n patch(\n id: GenericId<TableName>,\n value: PatchValue<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Replace the value of an existing document, overwriting its old value.\n *\n * @param id - The {@link values.GenericId} of the document to replace.\n * @param value - The new {@link GenericDocument} for the document. This value can omit the system fields,\n * and the database will fill them in.\n */\n replace(\n id: GenericId<TableName>,\n value: WithOptionalSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Delete an existing document.\n *\n * @param id - The {@link values.GenericId} of the document to remove.\n */\n delete(id: GenericId<TableName>): Promise<void>;\n}\n\n/**\n * This prevents TypeScript from inferring that the generic `TableName` type is\n * a union type when `table` and `id` disagree.\n */\ntype NonUnion<T> = T extends never // `never` is the bottom type for TypeScript unions\n ? never\n : T;\n\n/**\n * This is like Partial, but it also allows undefined to be passed to optional\n * fields when `exactOptionalPropertyTypes` is enabled in the tsconfig.\n */\ntype PatchValue<T> = {\n [P in keyof T]?: undefined extends T[P] ? T[P] | undefined : T[P];\n};\n"],
4
+ "sourcesContent": ["import { GenericId } from \"../values/index.js\";\nimport {\n DocumentByName,\n GenericDataModel,\n NamedTableInfo,\n TableNamesInDataModel,\n} from \"./data_model.js\";\nimport { QueryInitializer } from \"./query.js\";\nimport { SystemDataModel } from \"./schema.js\";\nimport {\n WithOptionalSystemFields,\n WithoutSystemFields,\n} from \"./system_fields.js\";\n\ninterface BaseDatabaseReader<DataModel extends GenericDataModel> {\n /**\n * Fetch a single document from the database by table name and\n * {@link values.GenericId}.\n *\n * @example\n * ```typescript\n * const user = await ctx.db.get(\"users\", userId);\n * ```\n *\n * @param table - The name of the table to fetch the document from.\n * @param id - The {@link values.GenericId} of the document to fetch from the database.\n * @returns - The {@link GenericDocument} of the document at the given {@link values.GenericId}, or `null` if it no longer exists.\n */\n get<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n id: GenericId<NonUnion<TableName>>,\n ): Promise<DocumentByName<DataModel, TableName> | null>;\n\n /**\n * Fetch a single document from the database by its {@link values.GenericId}.\n *\n * Supported for backwards compatibility. Prefer `db.get(tableName, id)` in\n * new code, or `db.system.get(tableName, id)` for system tables.\n *\n * @param id - The {@link values.GenericId} of the document to fetch from the database.\n * @returns - The {@link GenericDocument} of the document at the given {@link values.GenericId}, or `null` if it no longer exists.\n */\n get<TableName extends TableNamesInDataModel<DataModel>>(\n id: GenericId<TableName>,\n ): Promise<DocumentByName<DataModel, TableName> | null>;\n\n /**\n * Begin a query for the given table name.\n *\n * Queries don't execute immediately, so calling this method and extending its\n * query are free until the results are actually used.\n *\n * @param tableName - The name of the table to query.\n * @returns - A {@link QueryInitializer} object to start building a query.\n */\n query<TableName extends TableNamesInDataModel<DataModel>>(\n tableName: TableName,\n ): QueryInitializer<NamedTableInfo<DataModel, TableName>>;\n\n /**\n * Returns the string ID format for the ID in a given table, or null if the ID\n * is from a different table or is not a valid ID.\n *\n * This accepts the string ID format as well as the `.toString()` representation\n * of the legacy class-based ID format.\n *\n * This does not guarantee that the ID exists (i.e. `db.get(tableName, id)` may return `null`).\n *\n * @param tableName - The name of the table.\n * @param id - The ID string.\n */\n normalizeId<TableName extends TableNamesInDataModel<DataModel>>(\n tableName: TableName,\n id: string,\n ): GenericId<TableName> | null;\n}\n\ninterface BaseDatabaseReaderWithTable<DataModel extends GenericDataModel> {\n /**\n * Scope the database to a specific table.\n */\n table<TableName extends TableNamesInDataModel<DataModel>>(\n tableName: TableName,\n ): BaseTableReader<DataModel, TableName>;\n}\n\nexport interface BaseTableReader<\n DataModel extends GenericDataModel,\n TableName extends TableNamesInDataModel<DataModel>,\n> {\n /**\n * Fetch a single document from the table by its {@link values.GenericId}.\n *\n * @param id - The {@link values.GenericId} of the document to fetch from the database.\n * @returns - The {@link GenericDocument} of the document at the given {@link values.GenericId}, or `null` if it no longer exists.\n */\n get(\n id: GenericId<TableName>,\n ): Promise<DocumentByName<DataModel, TableName> | null>;\n\n /**\n * Begin a query for the table.\n *\n * Queries don't execute immediately, so calling this method and extending its\n * query are free until the results are actually used.\n *\n * @returns - A {@link QueryInitializer} object to start building a query.\n */\n query(): QueryInitializer<NamedTableInfo<DataModel, TableName>>;\n}\n\n/**\n * An interface to read from the database within Convex query functions.\n *\n * Available as `ctx.db` in queries (read-only) and mutations (read-write).\n * You should generally use the `DatabaseReader` type from\n * `\"./_generated/server\"`.\n *\n * The two entry points are:\n * - {@link GenericDatabaseReader.get}, which fetches a single document\n * by table name and {@link values.GenericId}.\n * - {@link GenericDatabaseReader.query}, which starts building a query.\n *\n * @example\n * ```typescript\n * // Fetch a single document by ID:\n * const user = await ctx.db.get(\"users\", userId);\n *\n * // Query documents with an index:\n * const messages = await ctx.db\n * .query(\"messages\")\n * .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", channelId))\n * .order(\"desc\")\n * .take(50);\n * ```\n *\n * **Best practice:** Use `.withIndex()` instead of `.filter()` for efficient\n * queries. Define indexes in your schema for fields you query frequently.\n *\n * @see https://docs.convex.dev/database/reading-data\n * @public\n */\nexport interface GenericDatabaseReader<DataModel extends GenericDataModel>\n extends BaseDatabaseReader<DataModel> {\n /**\n * An interface to read from the system tables within Convex query functions.\n *\n * System tables include `_storage` (file metadata) and\n * `_scheduled_functions` (scheduled function state). Use `ctx.db.system.get()`\n * and `ctx.db.system.query()` just like regular tables.\n *\n * @example\n * ```typescript\n * // Get file metadata from the _storage system table:\n * const metadata = await ctx.db.system.get(\"_storage\", storageId);\n * // metadata has: _id, _creationTime, contentType, sha256, size\n * ```\n *\n * @public\n */\n system: BaseDatabaseReader<SystemDataModel>;\n}\n\nexport interface GenericDatabaseReaderWithTable<\n DataModel extends GenericDataModel,\n> extends BaseDatabaseReaderWithTable<DataModel> {\n /**\n * An interface to read from the system tables within Convex query functions\n *\n * The two entry points are:\n * - {@link GenericDatabaseReader.get}, which fetches a single document\n * by its {@link values.GenericId}.\n * - {@link GenericDatabaseReader.query}, which starts building a query.\n *\n * @public\n */\n system: BaseDatabaseReaderWithTable<SystemDataModel>;\n}\n\n/**\n * An interface to read from and write to the database within Convex mutation\n * functions.\n *\n * Available as `ctx.db` in mutations. You should generally use the\n * `DatabaseWriter` type from `\"./_generated/server\"`.\n *\n * Extends {@link GenericDatabaseReader}\n * with write operations. All reads and writes within a single mutation are\n * executed **atomically**, you never have to worry about partial writes\n * leaving your data in an inconsistent state.\n *\n * @example\n * ```typescript\n * // Insert a new document:\n * const userId = await ctx.db.insert(\"users\", { name: \"Alice\", email: \"alice@example.com\" });\n *\n * // Update specific fields (shallow merge):\n * await ctx.db.patch(\"users\", userId, { name: \"Alice Smith\" });\n *\n * // Replace entire document (all non-system fields):\n * await ctx.db.replace(\"users\", userId, { name: \"Bob\", email: \"bob@example.com\" });\n *\n * // Delete a document:\n * await ctx.db.delete(\"users\", userId);\n *\n * // Delete multiple documents (collect first, then delete each):\n * const oldTasks = await ctx.db\n * .query(\"tasks\")\n * .withIndex(\"by_completed\", (q) => q.eq(\"completed\", true))\n * .collect();\n * for (const task of oldTasks) {\n * await ctx.db.delete(\"tasks\", task._id);\n * }\n * ```\n *\n * @see https://docs.convex.dev/database/writing-data\n * @public\n */\nexport interface GenericDatabaseWriter<DataModel extends GenericDataModel>\n extends GenericDatabaseReader<DataModel> {\n /**\n * Insert a new document into a table.\n *\n * @example\n * ```typescript\n * const taskId = await ctx.db.insert(\"tasks\", {\n * text: \"Buy groceries\",\n * completed: false,\n * });\n * ```\n *\n * @param table - The name of the table to insert a new document into.\n * @param value - The document to insert. System fields (`_id`, `_creationTime`)\n * are added automatically and should not be included.\n * @returns The {@link values.GenericId} of the new document.\n */\n insert<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n value: WithoutSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<GenericId<TableName>>;\n\n /**\n * Patch an existing document, shallow merging it with the given partial\n * document.\n *\n * New fields are added. Existing fields are overwritten. Fields set to\n * `undefined` are removed. Fields not specified in the patch are left\n * unchanged.\n *\n * This method will throw if the document does not exist.\n *\n * @example\n * ```typescript\n * // Update only the \"completed\" field, leaving other fields unchanged:\n * await ctx.db.patch(\"tasks\", taskId, { completed: true });\n *\n * // Remove an optional field by setting it to undefined:\n * await ctx.db.patch(\"tasks\", taskId, { assignee: undefined });\n * ```\n *\n * **Tip:** Use `patch` for partial updates. Use `replace` when you want to\n * overwrite the entire document.\n *\n * @param table - The name of the table the document is in.\n * @param id - The {@link values.GenericId} of the document to patch.\n * @param value - The partial document to merge into the existing document.\n */\n patch<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n id: GenericId<NonUnion<TableName>>,\n value: PatchValue<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Patch an existing document, shallow merging it with the given partial\n * document.\n *\n * New fields are added. Existing fields are overwritten. Fields set to\n * `undefined` are removed. Fields not specified in the patch are left\n * unchanged.\n *\n * This method will throw if the document does not exist.\n *\n * Supported for backwards compatibility. Prefer `db.patch(tableName, id, value)`\n * in new code.\n *\n * @param id - The {@link values.GenericId} of the document to patch.\n * @param value - The partial document to merge into the existing document.\n */\n patch<TableName extends TableNamesInDataModel<DataModel>>(\n id: GenericId<TableName>,\n value: PatchValue<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Replace the value of an existing document, overwriting its old value\n * completely.\n *\n * Unlike `patch`, which does a shallow merge, `replace` overwrites the\n * entire document. Any fields not included in the new value will be removed\n * (except system fields `_id` and `_creationTime`).\n *\n * This method will throw if the document does not exist.\n *\n * @example\n * ```typescript\n * // Replace the entire document:\n * await ctx.db.replace(\"users\", userId, {\n * name: \"New Name\",\n * email: \"new@example.com\",\n * });\n * ```\n *\n * @param table - The name of the table the document is in.\n * @param id - The {@link values.GenericId} of the document to replace.\n * @param value - The new document. System fields can be omitted.\n */\n replace<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n id: GenericId<NonUnion<TableName>>,\n value: WithOptionalSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Replace the value of an existing document, overwriting its old value\n * completely.\n *\n * Unlike `patch`, which does a shallow merge, `replace` overwrites the\n * entire document.\n *\n * Supported for backwards compatibility. Prefer `db.replace(tableName, id, value)`\n * in new code.\n *\n * @param id - The {@link values.GenericId} of the document to replace.\n * @param value - The new document. System fields can be omitted.\n */\n replace<TableName extends TableNamesInDataModel<DataModel>>(\n id: GenericId<TableName>,\n value: WithOptionalSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Delete an existing document.\n *\n * @example\n * ```typescript\n * await ctx.db.delete(\"tasks\", taskId);\n * ```\n *\n * @param table - The name of the table the document is in.\n * @param id - The {@link values.GenericId} of the document to remove.\n */\n delete<TableName extends TableNamesInDataModel<DataModel>>(\n table: TableName,\n id: GenericId<NonUnion<TableName>>,\n ): Promise<void>;\n\n /**\n * Delete an existing document.\n *\n * Supported for backwards compatibility. Prefer `db.delete(tableName, id)` in\n * new code.\n *\n * **Note:** Convex queries do not support `.delete()` directly on query\n * results. To delete multiple documents, `.collect()` them first, then\n * delete each one individually.\n *\n * @param id - The {@link values.GenericId} of the document to remove.\n */\n delete(id: GenericId<TableNamesInDataModel<DataModel>>): Promise<void>;\n}\n\n/**\n * An interface to read from and write to the database within Convex mutation\n * functions.\n *\n * You should generally use the `DatabaseWriter` type from\n * `\"./_generated/server\"`.\n *\n * Convex guarantees that all writes within a single mutation are\n * executed atomically, so you never have to worry about partial writes leaving\n * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)\n * for the guarantees Convex provides your functions.\n *\n * @public\n */\nexport interface GenericDatabaseWriterWithTable<\n DataModel extends GenericDataModel,\n> extends GenericDatabaseReaderWithTable<DataModel> {\n /**\n * Scope the database to a specific table.\n */\n table<TableName extends TableNamesInDataModel<DataModel>>(\n tableName: TableName,\n ): BaseTableWriter<DataModel, TableName>;\n}\n\nexport interface BaseTableWriter<\n DataModel extends GenericDataModel,\n TableName extends TableNamesInDataModel<DataModel>,\n> extends BaseTableReader<DataModel, TableName> {\n /**\n * Insert a new document into the table.\n *\n * @param value - The {@link values.Value} to insert into the given table.\n * @returns - {@link values.GenericId} of the new document.\n */\n insert(\n value: WithoutSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<GenericId<TableName>>;\n\n /**\n * Patch an existing document, shallow merging it with the given partial\n * document.\n *\n * New fields are added. Existing fields are overwritten. Fields set to\n * `undefined` are removed.\n *\n * @param id - The {@link values.GenericId} of the document to patch.\n * @param value - The partial {@link GenericDocument} to merge into the specified document. If this new value\n * specifies system fields like `_id`, they must match the document's existing field values.\n */\n patch(\n id: GenericId<TableName>,\n value: PatchValue<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Replace the value of an existing document, overwriting its old value.\n *\n * @param id - The {@link values.GenericId} of the document to replace.\n * @param value - The new {@link GenericDocument} for the document. This value can omit the system fields,\n * and the database will fill them in.\n */\n replace(\n id: GenericId<TableName>,\n value: WithOptionalSystemFields<DocumentByName<DataModel, TableName>>,\n ): Promise<void>;\n\n /**\n * Delete an existing document.\n *\n * @param id - The {@link values.GenericId} of the document to remove.\n */\n delete(id: GenericId<TableName>): Promise<void>;\n}\n\n/**\n * This prevents TypeScript from inferring that the generic `TableName` type is\n * a union type when `table` and `id` disagree.\n */\ntype NonUnion<T> = T extends never // `never` is the bottom type for TypeScript unions\n ? never\n : T;\n\n/**\n * This is like Partial, but it also allows undefined to be passed to optional\n * fields when `exactOptionalPropertyTypes` is enabled in the tsconfig.\n */\ntype PatchValue<T> = {\n [P in keyof T]?: undefined extends T[P] ? T[P] | undefined : T[P];\n};\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
6
6
  "names": []
7
7
  }
@@ -44,7 +44,10 @@ async function getFunctionMetadata() {
44
44
  "1.0/getFunctionMetadata",
45
45
  {}
46
46
  );
47
- return { name, componentPath };
47
+ return {
48
+ name,
49
+ componentPath
50
+ };
48
51
  }
49
52
  async function getDeploymentMetadata() {
50
53
  const syscallJSON = await (0, import_syscall.performAsyncSyscall)(
@@ -59,11 +62,8 @@ async function getDeploymentMetadata() {
59
62
  };
60
63
  }
61
64
  async function getRequestMetadata() {
62
- const { ip, userAgent, requestId } = await (0, import_syscall.performAsyncSyscall)(
63
- "1.0/getRequestMetadata",
64
- {}
65
- );
66
- return { ip, userAgent, requestId };
65
+ const { ip, userAgent, requestId, scheduledFunctionId } = await (0, import_syscall.performAsyncSyscall)("1.0/getRequestMetadata", {});
66
+ return { ip, userAgent, requestId, scheduledFunctionId };
67
67
  }
68
68
  function setupQueryMeta(visibility) {
69
69
  return {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/server/impl/meta_impl.ts"],
4
- "sourcesContent": ["import { jsonToConvex } from \"../../values/index.js\";\nimport {\n ActionMeta,\n MutationMeta,\n QueryMeta,\n RequestMetadata,\n FunctionMetadata,\n TransactionMetrics,\n DeploymentMetadata,\n} from \"../meta.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\n\nasync function getTransactionMetrics(): Promise<TransactionMetrics> {\n let syscallJSON;\n try {\n syscallJSON = await performAsyncSyscall(\"1.0/getTransactionMetrics\", {});\n } catch (e: any) {\n if (e.message?.includes(\"Unknown async operation\")) {\n throw new Error(\n \"getTransactionMetrics() can only be called from a query or mutation. \" +\n \"It is not available in actions or outside of a Convex function.\",\n );\n }\n throw e;\n }\n return jsonToConvex(syscallJSON) as any;\n}\n\nasync function getFunctionMetadata(): Promise<{\n name: string;\n componentPath: string;\n}> {\n const { name, componentPath } = await performAsyncSyscall(\n \"1.0/getFunctionMetadata\",\n {},\n );\n return { name, componentPath };\n}\n\nasync function getDeploymentMetadata(): Promise<DeploymentMetadata> {\n const syscallJSON = await performAsyncSyscall(\n \"1.0/getDeploymentMetadata\",\n {},\n );\n const result = jsonToConvex(syscallJSON) as any;\n return {\n name: result.name,\n region: result.region ?? null,\n class: result.class,\n };\n}\n\nasync function getRequestMetadata(): Promise<RequestMetadata> {\n const { ip, userAgent, requestId } = await performAsyncSyscall(\n \"1.0/getRequestMetadata\",\n {},\n );\n return { ip, userAgent, requestId };\n}\n\nexport function setupQueryMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): QueryMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"query\",\n visibility,\n }),\n getTransactionMetrics,\n getDeploymentMetadata,\n };\n}\n\nexport function setupMutationMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): MutationMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"mutation\",\n visibility,\n }),\n getTransactionMetrics,\n getDeploymentMetadata,\n getRequestMetadata,\n };\n}\n\nexport function setupActionMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): ActionMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"action\",\n visibility,\n }),\n getDeploymentMetadata,\n getRequestMetadata,\n };\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA6B;AAU7B,qBAAoC;AAEpC,eAAe,wBAAqD;AAClE,MAAI;AACJ,MAAI;AACF,kBAAc,UAAM,oCAAoB,6BAA6B,CAAC,CAAC;AAAA,EACzE,SAAS,GAAQ;AACf,QAAI,EAAE,SAAS,SAAS,yBAAyB,GAAG;AAClD,YAAM,IAAI;AAAA,QACR;AAAA,MAEF;AAAA,IACF;AACA,UAAM;AAAA,EACR;AACA,aAAO,4BAAa,WAAW;AACjC;AAEA,eAAe,sBAGZ;AACD,QAAM,EAAE,MAAM,cAAc,IAAI,UAAM;AAAA,IACpC;AAAA,IACA,CAAC;AAAA,EACH;AACA,SAAO,EAAE,MAAM,cAAc;AAC/B;AAEA,eAAe,wBAAqD;AAClE,QAAM,cAAc,UAAM;AAAA,IACxB;AAAA,IACA,CAAC;AAAA,EACH;AACA,QAAM,aAAS,4BAAa,WAAW;AACvC,SAAO;AAAA,IACL,MAAM,OAAO;AAAA,IACb,QAAQ,OAAO,UAAU;AAAA,IACzB,OAAO,OAAO;AAAA,EAChB;AACF;AAEA,eAAe,qBAA+C;AAC5D,QAAM,EAAE,IAAI,WAAW,UAAU,IAAI,UAAM;AAAA,IACzC;AAAA,IACA,CAAC;AAAA,EACH;AACA,SAAO,EAAE,IAAI,WAAW,UAAU;AACpC;AAEO,SAAS,eACd,YACW;AACX,SAAO;AAAA,IACL,qBAAqB,aAAa;AAAA,MAChC,GAAI,MAAM,oBAAoB;AAAA,MAC9B,MAAM;AAAA,MACN;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,kBACd,YACc;AACd,SAAO;AAAA,IACL,qBAAqB,aAAa;AAAA,MAChC,GAAI,MAAM,oBAAoB;AAAA,MAC9B,MAAM;AAAA,MACN;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,gBACd,YACY;AACZ,SAAO;AAAA,IACL,qBAAqB,aAAa;AAAA,MAChC,GAAI,MAAM,oBAAoB;AAAA,MAC9B,MAAM;AAAA,MACN;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { jsonToConvex } from \"../../values/index.js\";\nimport {\n ActionMeta,\n MutationMeta,\n QueryMeta,\n RequestMetadata,\n FunctionMetadata,\n TransactionMetrics,\n DeploymentMetadata,\n} from \"../meta.js\";\nimport { performAsyncSyscall } from \"./syscall.js\";\n\nasync function getTransactionMetrics(): Promise<TransactionMetrics> {\n let syscallJSON;\n try {\n syscallJSON = await performAsyncSyscall(\"1.0/getTransactionMetrics\", {});\n } catch (e: any) {\n if (e.message?.includes(\"Unknown async operation\")) {\n throw new Error(\n \"getTransactionMetrics() can only be called from a query or mutation. \" +\n \"It is not available in actions or outside of a Convex function.\",\n );\n }\n throw e;\n }\n return jsonToConvex(syscallJSON) as any;\n}\n\nasync function getFunctionMetadata(): Promise<{\n name: string;\n componentPath: string;\n}> {\n const { name, componentPath } = await performAsyncSyscall(\n \"1.0/getFunctionMetadata\",\n {},\n );\n return {\n name,\n componentPath,\n };\n}\n\nasync function getDeploymentMetadata(): Promise<DeploymentMetadata> {\n const syscallJSON = await performAsyncSyscall(\n \"1.0/getDeploymentMetadata\",\n {},\n );\n const result = jsonToConvex(syscallJSON) as any;\n return {\n name: result.name,\n region: result.region ?? null,\n class: result.class,\n };\n}\n\nasync function getRequestMetadata(): Promise<RequestMetadata> {\n const { ip, userAgent, requestId, scheduledFunctionId } =\n await performAsyncSyscall(\"1.0/getRequestMetadata\", {});\n return { ip, userAgent, requestId, scheduledFunctionId };\n}\n\nexport function setupQueryMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): QueryMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"query\",\n visibility,\n }),\n getTransactionMetrics,\n getDeploymentMetadata,\n };\n}\n\nexport function setupMutationMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): MutationMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"mutation\",\n visibility,\n }),\n getTransactionMetrics,\n getDeploymentMetadata,\n getRequestMetadata,\n };\n}\n\nexport function setupActionMeta(\n visibility: FunctionMetadata[\"visibility\"],\n): ActionMeta {\n return {\n getFunctionMetadata: async () => ({\n ...(await getFunctionMetadata()),\n type: \"action\",\n visibility,\n }),\n getDeploym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AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,gBACd,YACY;AACZ,SAAO;AAAA,IACL,qBAAqB,aAAa;AAAA,MAChC,GAAI,MAAM,oBAAoB;AAAA,MAC9B,MAAM;AAAA,MACN;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -51,7 +51,7 @@ async function invokeMutation(func, argsStr, visibility) {
51
51
  storage: (0, import_storage_impl.setupStorageWriter)(requestId),
52
52
  scheduler: (0, import_scheduler_impl.setupMutationScheduler)(),
53
53
  meta: (0, import_meta_impl.setupMutationMeta)(visibility),
54
- runQuery: (reference, args2, options) => runUdf("query", reference, args2, options?.transactionLimits),
54
+ runQuery: (reference, args2, options) => options?.useStaleSnapshot ? runUdf("snapshotQuery", reference, args2, options?.transactionLimits) : runUdf("query", reference, args2, options?.transactionLimits),
55
55
  runMutation: (reference, args2, options) => runUdf("mutation", reference, args2, options?.transactionLimits)
56
56
  };
57
57
  const result = await invokeFunction(func, mutationCtx, args);
@@ -166,7 +166,14 @@ async function invokeQuery(func, argsStr, visibility) {
166
166
  auth: (0, import_authentication_impl.setupAuth)(requestId),
167
167
  storage: (0, import_storage_impl.setupStorageReader)(requestId),
168
168
  meta: (0, import_meta_impl.setupQueryMeta)(visibility),
169
- runQuery: (reference, args2, options) => runUdf("query", reference, args2, options?.transactionLimits)
169
+ runQuery: (reference, args2, options) => {
170
+ if (options?.useStaleSnapshot) {
171
+ throw new Error(
172
+ "`useStaleSnapshot` is only supported in mutations, not queries."
173
+ );
174
+ }
175
+ return runUdf("query", reference, args2, options?.transactionLimits);
176
+ }
170
177
  };
171
178
  const result = await invokeFunction(func, queryCtx, args);
172
179
  validateReturnValue(result);
@@ -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 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 runUdf(\"query\", reference, args, options?.transactionLimits),\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": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAQO;AAgBP,0BAAiC;AACjC,gCAAwC;AACxC,iCAA0B;AAC1B,2BAAyC;AACzC,wBAAgD;AAChD,4BAGO;AACP,0BAIO;AACP,oBAA0B;AAC1B,qBAAoC;AACpC,uBAAkC;AAClC,mBAAmC;AACnC,uBA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AAa,MAAM;AAC5B;",
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": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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S;AACX,IAAE,mBAAmB,CAAC,YAAY,iBAAiB,MAAa,OAAO;AACvE,IAAE,WAAW;AACb,SAAO;AACT;AAEA,eAAe,OACb,SACA,GACA,MACA,mBACc;AACd,QAAM,gBAAY,yBAAU,IAAI;AAChC,QAAM,cAAmC;AAAA,IACvC;AAAA,IACA,UAAM,4BAAa,SAAS;AAAA,IAC5B,OAAG,iCAAmB,CAAC;AAAA,EACzB;AACA,MAAI,mBAAmB;AACrB,gBAAY,oBAAoB;AAAA,EAClC;AACA,QAAM,SAAS,UAAM,oCAAoB,cAAc,WAAW;AAClE,aAAO,4BAAa,MAAM;AAC5B;",
6
6
  "names": ["args", "v"]
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/server/index.ts"],
4
- "sourcesContent": ["/**\n * Utilities for implementing server-side Convex query and mutation functions.\n *\n * ## Usage\n *\n * ### Code Generation\n *\n * This module is typically used alongside generated server code.\n *\n * To generate the server code, run `npx convex dev` in your Convex project.\n * This will create a `convex/_generated/server.js` file with the following\n * functions, typed for your schema:\n * - [query](https://docs.convex.dev/generated-api/server#query)\n * - [mutation](https://docs.convex.dev/generated-api/server#mutation)\n *\n * If you aren't using TypeScript and code generation, you can use these untyped\n * functions instead:\n * - {@link queryGeneric}\n * - {@link mutationGeneric}\n *\n * ### Example\n *\n * Convex functions are defined by using either the `query` or\n * `mutation` wrappers.\n *\n * Queries receive a `db` that implements the {@link GenericDatabaseReader} interface.\n *\n * ```js\n * import { query } from \"./_generated/server\";\n *\n * export default query({\n * handler: async ({ db }, { arg1, arg2 }) => {\n * // Your (read-only) code here!\n * },\n * });\n * ```\n *\n * If your function needs to write to the database, such as inserting, updating,\n * or deleting documents, use `mutation` instead which provides a `db` that\n * implements the {@link GenericDatabaseWriter} interface.\n *\n * ```js\n * import { mutation } from \"./_generated/server\";\n *\n * export default mutation({\n * handler: async ({ db }, { arg1, arg2 }) => {\n * // Your mutation code here!\n * },\n * });\n * ```\n * @module\n */\n\nexport type {\n Auth,\n AuthConfig,\n AuthProvider,\n UserIdentity,\n UserIdentityAttributes,\n} from \"./authentication.js\";\nexport * from \"./database.js\";\nexport type {\n GenericDocument,\n GenericFieldPaths,\n GenericIndexFields,\n GenericTableIndexes,\n GenericSearchIndexConfig,\n GenericTableSearchIndexes,\n GenericVectorIndexConfig,\n GenericTableVectorIndexes,\n FieldTypeFromFieldPath,\n FieldTypeFromFieldPathInner,\n GenericTableInfo,\n DocumentByInfo,\n FieldPaths,\n Indexes,\n IndexNames,\n NamedIndex,\n SearchIndexes,\n SearchIndexNames,\n NamedSearchIndex,\n VectorIndexes,\n VectorIndexNames,\n NamedVectorIndex,\n GenericDataModel,\n AnyDataModel,\n TableNamesInDataModel,\n NamedTableInfo,\n DocumentByName,\n} from \"./data_model.js\";\n\nexport type {\n Expression,\n ExpressionOrValue,\n FilterBuilder,\n} from \"./filter_builder.js\";\nexport {\n actionGeneric,\n httpActionGeneric,\n mutationGeneric,\n queryGeneric,\n internalActionGeneric,\n internalMutationGeneric,\n internalQueryGeneric,\n} from \"./impl/registration_impl.js\";\nexport type {\n TransactionMetric,\n TransactionMetrics,\n TransactionLimits,\n FunctionMetadata,\n DeploymentMetadata,\n RequestMetadata,\n QueryMeta,\n MutationMeta,\n ActionMeta,\n} from \"./meta.js\";\nexport type { IndexRange, IndexRangeBuilder } from \"./index_range_builder.js\";\nexport * from \"./pagination.js\";\nexport type { OrderedQuery, Query, QueryInitializer } from \"./query.js\";\nexport type {\n ArgsArray,\n DefaultFunctionArgs,\n FunctionVisibility,\n ActionBuilder,\n MutationBuilder,\n MutationBuilderWithTable,\n QueryBuilder,\n QueryBuilderWithTable,\n HttpActionBuilder,\n GenericActionCtx,\n GenericMutationCtx,\n GenericMutationCtxWithTable,\n GenericQueryCtx,\n GenericQueryCtxWithTable,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n PublicHttpAction,\n UnvalidatedFunction,\n ValidatedFunction,\n ReturnValueForOptionalValidator,\n ArgsArrayForOptionalValidator,\n ArgsArrayToObject,\n DefaultArgsForOptionalValidator,\n} from \"./registration.js\";\nexport * from \"./search_filter_builder.js\";\nexport * from \"./storage.js\";\nexport type { Scheduler, SchedulableFunctionReference } from \"./scheduler.js\";\nexport { cronJobs } from \"./cron.js\";\nexport type { CronJob, Crons } from \"./cron.js\";\nexport type {\n SystemFields,\n IdField,\n WithoutSystemFields,\n WithOptionalSystemFields,\n SystemIndexes,\n IndexTiebreakerField,\n} from \"./system_fields.js\";\nexport { httpRouter, HttpRouter, ROUTABLE_HTTP_METHODS } from \"./router.js\";\nexport type {\n RoutableMethod,\n RouteSpec,\n RouteSpecWithPath,\n RouteSpecWithPathPrefix,\n} from \"./router.js\";\nexport {\n anyApi,\n getFunctionName,\n makeFunctionReference,\n filterApi,\n} from \"./api.js\";\nexport type {\n ApiFromModules,\n AnyApi,\n FilterApi,\n FunctionType,\n FunctionReference,\n FunctionArgs,\n OptionalRestArgs,\n PartialApi,\n ArgsAndOptions,\n FunctionReturnType,\n ValidatorTypeToReturnType,\n} from \"./api.js\";\nexport {\n defineApp,\n defineComponent,\n componentsGeneric,\n createFunctionHandle,\n type AnyChildComponents,\n type EnvDefinition,\n type EnvFromDefinition,\n type EnvFromAppDefinition,\n type AppDefinition,\n} from \"./components/index.js\";\n/**\n * @internal\n */\nexport { currentSystemUdfInComponent } from \"./components/index.js\";\nexport { getFunctionAddress } from \"./components/index.js\";\nexport type {\n ComponentDefinition,\n AnyComponents,\n FunctionHandle,\n} from \"./components/index.js\";\n\n/**\n * @internal\n */\nexport type { Index, SearchIndex, VectorIndex } from \"./schema.js\";\n\nexport { log } from \"./log.js\";\nexport type { AuditLogBody, AuditLogValue } from \"./audit_logging.js\";\n\nexport type {\n SearchIndexConfig,\n VectorIndexConfig,\n TableDefinition,\n SchemaDefinition,\n DefineSchemaOptions,\n GenericSchema,\n DataModelFromSchemaDefinition,\n SystemDataModel,\n SystemTableNames,\n} from \"./schema.js\";\nexport { defineTable, defineSchema } from \"./schema.js\";\n\nexport type {\n VectorSearch,\n VectorSearchQuery,\n VectorFilterBuilder,\n FilterExpression,\n} from \"./vector_search.js\";\n\n/**\n * @public\n */\nexport type { BetterOmit, Expand } from \"../type_utils.js\";\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4DA,2BAAc,0BA5Dd;AAgGA,+BAQO;AAaP,2BAAc,4BArHd;AAiJA,2BAAc,uCAjJd;AAkJA,2BAAc,yBAlJd;AAoJA,kBAAyB;AAUzB,oBAA8D;AAO9D,iBAKO;AAcP,wBAUO;AAIP,IAAAA,qBAA4C;AAC5C,IAAAA,qBAAmC;AAYnC,iBAAoB;AAcpB,oBAA0C;",
4
+ "sourcesContent": ["/**\n * Utilities for implementing server-side Convex query and mutation functions.\n *\n * ## Usage\n *\n * ### Code Generation\n *\n * This module is typically used alongside generated server code.\n *\n * To generate the server code, run `npx convex dev` in your Convex project.\n * This will create a `convex/_generated/server.js` file with the following\n * functions, typed for your schema:\n * - [query](https://docs.convex.dev/generated-api/server#query)\n * - [mutation](https://docs.convex.dev/generated-api/server#mutation)\n *\n * If you aren't using TypeScript and code generation, you can use these untyped\n * functions instead:\n * - {@link queryGeneric}\n * - {@link mutationGeneric}\n *\n * ### Example\n *\n * Convex functions are defined by using either the `query` or\n * `mutation` wrappers.\n *\n * Queries receive a `db` that implements the {@link GenericDatabaseReader} interface.\n *\n * ```js\n * import { query } from \"./_generated/server\";\n *\n * export default query({\n * handler: async ({ db }, { arg1, arg2 }) => {\n * // Your (read-only) code here!\n * },\n * });\n * ```\n *\n * If your function needs to write to the database, such as inserting, updating,\n * or deleting documents, use `mutation` instead which provides a `db` that\n * implements the {@link GenericDatabaseWriter} interface.\n *\n * ```js\n * import { mutation } from \"./_generated/server\";\n *\n * export default mutation({\n * handler: async ({ db }, { arg1, arg2 }) => {\n * // Your mutation code here!\n * },\n * });\n * ```\n * @module\n */\n\nexport type {\n Auth,\n AuthConfig,\n AuthProvider,\n UserIdentity,\n UserIdentityAttributes,\n} from \"./authentication.js\";\nexport * from \"./database.js\";\nexport type {\n GenericDocument,\n GenericFieldPaths,\n GenericIndexFields,\n GenericTableIndexes,\n GenericSearchIndexConfig,\n GenericTableSearchIndexes,\n GenericVectorIndexConfig,\n GenericTableVectorIndexes,\n FieldTypeFromFieldPath,\n FieldTypeFromFieldPathInner,\n GenericTableInfo,\n DocumentByInfo,\n FieldPaths,\n Indexes,\n IndexNames,\n NamedIndex,\n SearchIndexes,\n SearchIndexNames,\n NamedSearchIndex,\n VectorIndexes,\n VectorIndexNames,\n NamedVectorIndex,\n GenericDataModel,\n AnyDataModel,\n TableNamesInDataModel,\n NamedTableInfo,\n DocumentByName,\n} from \"./data_model.js\";\n\nexport type {\n Expression,\n ExpressionOrValue,\n FilterBuilder,\n} from \"./filter_builder.js\";\nexport {\n actionGeneric,\n httpActionGeneric,\n mutationGeneric,\n queryGeneric,\n internalActionGeneric,\n internalMutationGeneric,\n internalQueryGeneric,\n} from \"./impl/registration_impl.js\";\nexport type {\n TransactionMetric,\n TransactionMetrics,\n TransactionLimits,\n FunctionMetadata,\n DeploymentMetadata,\n RequestMetadata,\n QueryMeta,\n MutationMeta,\n ActionMeta,\n} from \"./meta.js\";\nexport type { IndexRange, IndexRangeBuilder } from \"./index_range_builder.js\";\nexport * from \"./pagination.js\";\nexport type { OrderedQuery, Query, QueryInitializer } from \"./query.js\";\nexport type {\n AdvancedRunQueryOptions,\n ArgsArray,\n DefaultFunctionArgs,\n FunctionVisibility,\n ActionBuilder,\n MutationBuilder,\n MutationBuilderWithTable,\n QueryBuilder,\n QueryBuilderWithTable,\n HttpActionBuilder,\n GenericActionCtx,\n GenericMutationCtx,\n GenericMutationCtxWithTable,\n GenericQueryCtx,\n GenericQueryCtxWithTable,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n PublicHttpAction,\n UnvalidatedFunction,\n ValidatedFunction,\n ReturnValueForOptionalValidator,\n ArgsArrayForOptionalValidator,\n ArgsArrayToObject,\n DefaultArgsForOptionalValidator,\n} from \"./registration.js\";\nexport * from \"./search_filter_builder.js\";\nexport * from \"./storage.js\";\nexport type { Scheduler, SchedulableFunctionReference } from \"./scheduler.js\";\nexport { cronJobs } from \"./cron.js\";\nexport type { CronJob, Crons } from \"./cron.js\";\nexport type {\n SystemFields,\n IdField,\n WithoutSystemFields,\n WithOptionalSystemFields,\n SystemIndexes,\n IndexTiebreakerField,\n} from \"./system_fields.js\";\nexport { httpRouter, HttpRouter, ROUTABLE_HTTP_METHODS } from \"./router.js\";\nexport type {\n RoutableMethod,\n RouteSpec,\n RouteSpecWithPath,\n RouteSpecWithPathPrefix,\n} from \"./router.js\";\nexport {\n anyApi,\n getFunctionName,\n makeFunctionReference,\n filterApi,\n} from \"./api.js\";\nexport type {\n ApiFromModules,\n AnyApi,\n FilterApi,\n FunctionType,\n FunctionReference,\n FunctionArgs,\n OptionalRestArgs,\n PartialApi,\n ArgsAndOptions,\n FunctionReturnType,\n ValidatorTypeToReturnType,\n} from \"./api.js\";\nexport {\n defineApp,\n defineComponent,\n componentsGeneric,\n createFunctionHandle,\n type AnyChildComponents,\n type EnvDefinition,\n type EnvFromDefinition,\n type EnvFromAppDefinition,\n type AppDefinition,\n} from \"./components/index.js\";\n/**\n * @internal\n */\nexport { currentSystemUdfInComponent } from \"./components/index.js\";\nexport { getFunctionAddress } from \"./components/index.js\";\nexport type {\n ComponentDefinition,\n AnyComponents,\n FunctionHandle,\n} from \"./components/index.js\";\n\n/**\n * @internal\n */\nexport type { Index, SearchIndex, VectorIndex } from \"./schema.js\";\n\nexport { log } from \"./log.js\";\nexport type { AuditLogBody, AuditLogValue } from \"./audit_logging.js\";\n\nexport type {\n SearchIndexConfig,\n VectorIndexConfig,\n TableDefinition,\n SchemaDefinition,\n DefineSchemaOptions,\n GenericSchema,\n DataModelFromSchemaDefinition,\n SystemDataModel,\n SystemTableNames,\n} from \"./schema.js\";\nexport { defineTable, defineSchema } from \"./schema.js\";\n\nexport type {\n VectorSearch,\n VectorSearchQuery,\n VectorFilterBuilder,\n FilterExpression,\n} from \"./vector_search.js\";\n\n/**\n * @public\n */\nexport type { BetterOmit, Expand } from \"../type_utils.js\";\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA4DA,2BAAc,0BA5Dd;AAgGA,+BAQO;AAaP,2BAAc,4BArHd;AAkJA,2BAAc,uCAlJd;AAmJA,2BAAc,yBAnJd;AAqJA,kBAAyB;AAUzB,oBAA8D;AAO9D,iBAKO;AAcP,wBAUO;AAIP,IAAAA,qBAA4C;AAC5C,IAAAA,qBAAmC;AAYnC,iBAAoB;AAcpB,oBAA0C;",
6
6
  "names": ["import_components"]
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\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\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(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<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"],
5
5
  "mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
6
6
  "names": []
7
7
  }