convex 1.37.0 → 1.38.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 (218) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/browser.bundle.js +1 -1
  3. package/dist/browser.bundle.js.map +1 -1
  4. package/dist/cjs/bundler/debugBundle.js +2 -1
  5. package/dist/cjs/bundler/debugBundle.js.map +2 -2
  6. package/dist/cjs/bundler/index.js +6 -3
  7. package/dist/cjs/bundler/index.js.map +2 -2
  8. package/dist/cjs/bundler/serverOnly.js +37 -0
  9. package/dist/cjs/bundler/serverOnly.js.map +7 -0
  10. package/dist/cjs/cli/configure.js +5 -32
  11. package/dist/cjs/cli/configure.js.map +2 -2
  12. package/dist/cjs/cli/deploy.js +1 -1
  13. package/dist/cjs/cli/deploy.js.map +1 -1
  14. package/dist/cjs/cli/deploymentCreate.js +21 -9
  15. package/dist/cjs/cli/deploymentCreate.js.map +2 -2
  16. package/dist/cjs/cli/deploymentSelect.js +25 -0
  17. package/dist/cjs/cli/deploymentSelect.js.map +2 -2
  18. package/dist/cjs/cli/deploymentTokenCreate.js +1 -1
  19. package/dist/cjs/cli/deploymentTokenCreate.js.map +2 -2
  20. package/dist/cjs/cli/deploymentTokenDelete.js +1 -1
  21. package/dist/cjs/cli/deploymentTokenDelete.js.map +2 -2
  22. package/dist/cjs/cli/index.js +5 -2
  23. package/dist/cjs/cli/index.js.map +2 -2
  24. package/dist/cjs/cli/lib/deploymentSelection.js +4 -7
  25. package/dist/cjs/cli/lib/deploymentSelection.js.map +2 -2
  26. package/dist/cjs/cli/lib/env.js +1 -0
  27. package/dist/cjs/cli/lib/env.js.map +2 -2
  28. package/dist/cjs/cli/lib/localDeployment/anonymous.js +4 -4
  29. package/dist/cjs/cli/lib/localDeployment/anonymous.js.map +2 -2
  30. package/dist/cjs/cli/lib/localDeployment/errors.js +1 -1
  31. package/dist/cjs/cli/lib/localDeployment/errors.js.map +2 -2
  32. package/dist/cjs/cli/lib/localDeployment/localDeployment.js +64 -9
  33. package/dist/cjs/cli/lib/localDeployment/localDeployment.js.map +2 -2
  34. package/dist/cjs/cli/lib/localDeployment/utils.js +19 -7
  35. package/dist/cjs/cli/lib/localDeployment/utils.js.map +3 -3
  36. package/dist/cjs/cli/lib/utils/globalConfig.js +1 -2
  37. package/dist/cjs/cli/lib/utils/globalConfig.js.map +2 -2
  38. package/dist/cjs/cli/lib/utils/utils.js +8 -0
  39. package/dist/cjs/cli/lib/utils/utils.js.map +2 -2
  40. package/dist/cjs/index.js +1 -1
  41. package/dist/cjs/index.js.map +1 -1
  42. package/dist/cjs/server/audit_logging.js +3 -1
  43. package/dist/cjs/server/audit_logging.js.map +2 -2
  44. package/dist/cjs/server/components/index.js +1 -12
  45. package/dist/cjs/server/components/index.js.map +2 -2
  46. package/dist/cjs/server/impl/registration_impl.js +8 -5
  47. package/dist/cjs/server/impl/registration_impl.js.map +2 -2
  48. package/dist/cjs/server/index.js.map +2 -2
  49. package/dist/cjs/server/log.js.map +2 -2
  50. package/dist/cjs/server/logVars.js.map +2 -2
  51. package/dist/cjs/server/meta.js.map +1 -1
  52. package/dist/cjs-types/bundler/debugBundle.d.ts.map +1 -1
  53. package/dist/cjs-types/bundler/index.d.ts.map +1 -1
  54. package/dist/cjs-types/bundler/serverOnly.d.ts +3 -0
  55. package/dist/cjs-types/bundler/serverOnly.d.ts.map +1 -0
  56. package/dist/cjs-types/cli/configure.d.ts.map +1 -1
  57. package/dist/cjs-types/cli/deploymentCreate.d.ts +4 -0
  58. package/dist/cjs-types/cli/deploymentCreate.d.ts.map +1 -1
  59. package/dist/cjs-types/cli/deploymentSelect.d.ts.map +1 -1
  60. package/dist/cjs-types/cli/deploymentTokenCreate.d.ts.map +1 -1
  61. package/dist/cjs-types/cli/deploymentTokenDelete.d.ts.map +1 -1
  62. package/dist/cjs-types/cli/lib/deployApi/componentDefinition.d.ts +6 -6
  63. package/dist/cjs-types/cli/lib/deployApi/modules.d.ts +6 -6
  64. package/dist/cjs-types/cli/lib/deployApi/startPush.d.ts +8 -8
  65. package/dist/cjs-types/cli/lib/deploymentSelection.d.ts.map +1 -1
  66. package/dist/cjs-types/cli/lib/env.d.ts.map +1 -1
  67. package/dist/cjs-types/cli/lib/localDeployment/anonymous.d.ts.map +1 -1
  68. package/dist/cjs-types/cli/lib/localDeployment/errors.d.ts.map +1 -1
  69. package/dist/cjs-types/cli/lib/localDeployment/localDeployment.d.ts +8 -0
  70. package/dist/cjs-types/cli/lib/localDeployment/localDeployment.d.ts.map +1 -1
  71. package/dist/cjs-types/cli/lib/localDeployment/utils.d.ts +13 -4
  72. package/dist/cjs-types/cli/lib/localDeployment/utils.d.ts.map +1 -1
  73. package/dist/cjs-types/cli/lib/utils/globalConfig.d.ts +0 -1
  74. package/dist/cjs-types/cli/lib/utils/globalConfig.d.ts.map +1 -1
  75. package/dist/cjs-types/cli/lib/utils/utils.d.ts +7 -0
  76. package/dist/cjs-types/cli/lib/utils/utils.d.ts.map +1 -1
  77. package/dist/cjs-types/index.d.ts +1 -1
  78. package/dist/cjs-types/server/audit_logging.d.ts +1 -0
  79. package/dist/cjs-types/server/audit_logging.d.ts.map +1 -1
  80. package/dist/cjs-types/server/components/index.d.ts.map +1 -1
  81. package/dist/cjs-types/server/impl/registration_impl.d.ts.map +1 -1
  82. package/dist/cjs-types/server/index.d.ts +2 -0
  83. package/dist/cjs-types/server/index.d.ts.map +1 -1
  84. package/dist/cjs-types/server/log.d.ts +28 -0
  85. package/dist/cjs-types/server/log.d.ts.map +1 -1
  86. package/dist/cjs-types/server/logVars.d.ts +1 -0
  87. package/dist/cjs-types/server/logVars.d.ts.map +1 -1
  88. package/dist/cjs-types/server/meta.d.ts +2 -0
  89. package/dist/cjs-types/server/meta.d.ts.map +1 -1
  90. package/dist/cli.bundle.cjs +1583 -1520
  91. package/dist/cli.bundle.cjs.map +4 -4
  92. package/dist/esm/bundler/debugBundle.js +2 -1
  93. package/dist/esm/bundler/debugBundle.js.map +2 -2
  94. package/dist/esm/bundler/index.js +6 -3
  95. package/dist/esm/bundler/index.js.map +2 -2
  96. package/dist/esm/bundler/serverOnly.js +15 -0
  97. package/dist/esm/bundler/serverOnly.js.map +7 -0
  98. package/dist/esm/cli/configure.js +5 -32
  99. package/dist/esm/cli/configure.js.map +2 -2
  100. package/dist/esm/cli/deploy.js +1 -1
  101. package/dist/esm/cli/deploy.js.map +1 -1
  102. package/dist/esm/cli/deploymentCreate.js +21 -10
  103. package/dist/esm/cli/deploymentCreate.js.map +2 -2
  104. package/dist/esm/cli/deploymentSelect.js +25 -0
  105. package/dist/esm/cli/deploymentSelect.js.map +2 -2
  106. package/dist/esm/cli/deploymentTokenCreate.js +2 -1
  107. package/dist/esm/cli/deploymentTokenCreate.js.map +2 -2
  108. package/dist/esm/cli/deploymentTokenDelete.js +2 -1
  109. package/dist/esm/cli/deploymentTokenDelete.js.map +2 -2
  110. package/dist/esm/cli/index.js +5 -2
  111. package/dist/esm/cli/index.js.map +2 -2
  112. package/dist/esm/cli/lib/deploymentSelection.js +5 -7
  113. package/dist/esm/cli/lib/deploymentSelection.js.map +2 -2
  114. package/dist/esm/cli/lib/env.js +2 -0
  115. package/dist/esm/cli/lib/env.js.map +2 -2
  116. package/dist/esm/cli/lib/localDeployment/anonymous.js +4 -4
  117. package/dist/esm/cli/lib/localDeployment/anonymous.js.map +2 -2
  118. package/dist/esm/cli/lib/localDeployment/errors.js +1 -1
  119. package/dist/esm/cli/lib/localDeployment/errors.js.map +2 -2
  120. package/dist/esm/cli/lib/localDeployment/localDeployment.js +70 -11
  121. package/dist/esm/cli/lib/localDeployment/localDeployment.js.map +2 -2
  122. package/dist/esm/cli/lib/localDeployment/utils.js +19 -7
  123. package/dist/esm/cli/lib/localDeployment/utils.js.map +3 -3
  124. package/dist/esm/cli/lib/utils/globalConfig.js +1 -2
  125. package/dist/esm/cli/lib/utils/globalConfig.js.map +2 -2
  126. package/dist/esm/cli/lib/utils/utils.js +6 -0
  127. package/dist/esm/cli/lib/utils/utils.js.map +2 -2
  128. package/dist/esm/index.js +1 -1
  129. package/dist/esm/index.js.map +1 -1
  130. package/dist/esm/server/audit_logging.js +3 -1
  131. package/dist/esm/server/audit_logging.js.map +2 -2
  132. package/dist/esm/server/components/index.js +1 -12
  133. package/dist/esm/server/components/index.js.map +2 -2
  134. package/dist/esm/server/impl/registration_impl.js +8 -5
  135. package/dist/esm/server/impl/registration_impl.js.map +2 -2
  136. package/dist/esm/server/index.js.map +2 -2
  137. package/dist/esm/server/log.js.map +2 -2
  138. package/dist/esm/server/logVars.js.map +2 -2
  139. package/dist/esm-types/bundler/debugBundle.d.ts.map +1 -1
  140. package/dist/esm-types/bundler/index.d.ts.map +1 -1
  141. package/dist/esm-types/bundler/serverOnly.d.ts +3 -0
  142. package/dist/esm-types/bundler/serverOnly.d.ts.map +1 -0
  143. package/dist/esm-types/cli/configure.d.ts.map +1 -1
  144. package/dist/esm-types/cli/deploymentCreate.d.ts +4 -0
  145. package/dist/esm-types/cli/deploymentCreate.d.ts.map +1 -1
  146. package/dist/esm-types/cli/deploymentSelect.d.ts.map +1 -1
  147. package/dist/esm-types/cli/deploymentTokenCreate.d.ts.map +1 -1
  148. package/dist/esm-types/cli/deploymentTokenDelete.d.ts.map +1 -1
  149. package/dist/esm-types/cli/lib/deployApi/componentDefinition.d.ts +6 -6
  150. package/dist/esm-types/cli/lib/deployApi/modules.d.ts +6 -6
  151. package/dist/esm-types/cli/lib/deployApi/startPush.d.ts +8 -8
  152. package/dist/esm-types/cli/lib/deploymentSelection.d.ts.map +1 -1
  153. package/dist/esm-types/cli/lib/env.d.ts.map +1 -1
  154. package/dist/esm-types/cli/lib/localDeployment/anonymous.d.ts.map +1 -1
  155. package/dist/esm-types/cli/lib/localDeployment/errors.d.ts.map +1 -1
  156. package/dist/esm-types/cli/lib/localDeployment/localDeployment.d.ts +8 -0
  157. package/dist/esm-types/cli/lib/localDeployment/localDeployment.d.ts.map +1 -1
  158. package/dist/esm-types/cli/lib/localDeployment/utils.d.ts +13 -4
  159. package/dist/esm-types/cli/lib/localDeployment/utils.d.ts.map +1 -1
  160. package/dist/esm-types/cli/lib/utils/globalConfig.d.ts +0 -1
  161. package/dist/esm-types/cli/lib/utils/globalConfig.d.ts.map +1 -1
  162. package/dist/esm-types/cli/lib/utils/utils.d.ts +7 -0
  163. package/dist/esm-types/cli/lib/utils/utils.d.ts.map +1 -1
  164. package/dist/esm-types/index.d.ts +1 -1
  165. package/dist/esm-types/server/audit_logging.d.ts +1 -0
  166. package/dist/esm-types/server/audit_logging.d.ts.map +1 -1
  167. package/dist/esm-types/server/components/index.d.ts.map +1 -1
  168. package/dist/esm-types/server/impl/registration_impl.d.ts.map +1 -1
  169. package/dist/esm-types/server/index.d.ts +2 -0
  170. package/dist/esm-types/server/index.d.ts.map +1 -1
  171. package/dist/esm-types/server/log.d.ts +28 -0
  172. package/dist/esm-types/server/log.d.ts.map +1 -1
  173. package/dist/esm-types/server/logVars.d.ts +1 -0
  174. package/dist/esm-types/server/logVars.d.ts.map +1 -1
  175. package/dist/esm-types/server/meta.d.ts +2 -0
  176. package/dist/esm-types/server/meta.d.ts.map +1 -1
  177. package/dist/react.bundle.js +1 -1
  178. package/dist/react.bundle.js.map +1 -1
  179. package/package.json +1 -1
  180. package/schemas/convex.schema.json +1 -1
  181. package/src/bundler/debugBundle.ts +2 -1
  182. package/src/bundler/index.ts +7 -3
  183. package/src/bundler/serverOnly.ts +18 -0
  184. package/src/cli/configure.ts +2 -35
  185. package/src/cli/deploy.ts +1 -1
  186. package/src/cli/deploymentCreate.test.ts +4 -0
  187. package/src/cli/deploymentCreate.ts +23 -9
  188. package/src/cli/deploymentSelect.test.ts +60 -6
  189. package/src/cli/deploymentSelect.ts +34 -0
  190. package/src/cli/deploymentSelection.test.ts +72 -19
  191. package/src/cli/deploymentTokenCreate.ts +4 -1
  192. package/src/cli/deploymentTokenDelete.ts +9 -1
  193. package/src/cli/index.ts +6 -2
  194. package/src/cli/lib/deploymentSelection.ts +5 -7
  195. package/src/cli/lib/env.ts +2 -0
  196. package/src/cli/lib/localDeployment/anonymous.ts +5 -4
  197. package/src/cli/lib/localDeployment/errors.ts +1 -3
  198. package/src/cli/lib/localDeployment/localDeployment.ts +85 -10
  199. package/src/cli/lib/localDeployment/utils.ts +31 -7
  200. package/src/cli/lib/utils/globalConfig.ts +0 -3
  201. package/src/cli/lib/utils/utils.ts +15 -0
  202. package/src/index.ts +1 -1
  203. package/src/server/audit_logging.ts +2 -3
  204. package/src/server/components/index.ts +3 -15
  205. package/src/server/impl/registration_impl.ts +13 -7
  206. package/src/server/index.ts +0 -6
  207. package/src/server/log.ts +21 -3
  208. package/src/server/logVars.ts +0 -3
  209. package/src/server/meta.ts +0 -7
  210. package/dist/cjs/cli/disableLocalDev.js +0 -121
  211. package/dist/cjs/cli/disableLocalDev.js.map +0 -7
  212. package/dist/cjs-types/cli/disableLocalDev.d.ts +0 -6
  213. package/dist/cjs-types/cli/disableLocalDev.d.ts.map +0 -1
  214. package/dist/esm/cli/disableLocalDev.js +0 -105
  215. package/dist/esm/cli/disableLocalDev.js.map +0 -7
  216. package/dist/esm-types/cli/disableLocalDev.d.ts +0 -6
  217. package/dist/esm-types/cli/disableLocalDev.d.ts.map +0 -1
  218. package/src/cli/disableLocalDev.ts +0 -134
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/cli/lib/utils/utils.ts"],
4
- "sourcesContent": ["import { paths as PlatformDeploymentPaths } from \"@convex-dev/platform/deploymentApi\";\nimport { paths as PlatformManagementPaths } from \"@convex-dev/platform/managementApi\";\nimport { chalkStderr } from \"chalk\";\nimport os from \"os\";\nimport path from \"path\";\n\nimport { ProjectConfig } from \"../config.js\";\n\nimport { spawn } from \"child_process\";\nimport { InvalidArgumentError } from \"commander\";\nimport fetchRetryFactory, { RequestInitRetryParams } from \"fetch-retry\";\nimport { Context, ErrorType } from \"../../../bundler/context.js\";\nimport {\n failExistingSpinner,\n logError,\n logMessage,\n logWarning,\n} from \"../../../bundler/log.js\";\nimport { version } from \"../../version.js\";\nimport type { CloudDeploymentType, Project } from \"../api.js\";\nimport { promptOptions, promptSearch, promptYesNo } from \"./prompts.js\";\nimport {\n bigBrainEnableFeatureMetadata,\n projectHasExistingCloudDev,\n} from \"../localDeployment/bigBrain.js\";\nimport type {\n paths as CliManagementPaths,\n TeamResponse,\n} from \"../../generatedApi.js\";\nimport createClient from \"openapi-fetch\";\n\nconst retryingFetch = fetchRetryFactory(fetch);\n\nexport const productionProvisionHost = \"https://api.convex.dev\";\nexport const provisionHost =\n process.env.CONVEX_PROVISION_HOST || productionProvisionHost;\nexport const BIG_BRAIN_URL = `${provisionHost}/api/`;\nconst PLATFORM_MANAGEMENT_API_URL = `${provisionHost}/v1/`;\nexport const ENV_VAR_FILE_PATH = \".env.local\";\nexport const CONVEX_DEPLOY_KEY_ENV_VAR_NAME = \"CONVEX_DEPLOY_KEY\";\nexport const CONVEX_DEPLOYMENT_ENV_VAR_NAME = \"CONVEX_DEPLOYMENT\";\nexport const CONVEX_SELF_HOSTED_URL_VAR_NAME = \"CONVEX_SELF_HOSTED_URL\";\nexport const CONVEX_SELF_HOSTED_ADMIN_KEY_VAR_NAME =\n \"CONVEX_SELF_HOSTED_ADMIN_KEY\";\nconst MAX_RETRIES = 6;\n// After 3 retries, log a progress message that we're retrying the request\nconst RETRY_LOG_THRESHOLD = 3;\n\n/**\n * Processes the CONVEX_DEPLOY_KEY value to handle special sentinel values.\n *\n * - If the value is `<ignore_deploy_key>`, treats it as if the env var isn't set (returns undefined)\n * - If the value matches `<missing_deploy_key:$STRING>`, crashes with the message in $STRING\n * - Otherwise returns the value as-is\n *\n * @param ctx Context for crashing if needed\n * @param deployKey The raw deploy key value from environment or config\n * @returns The processed deploy key value or undefined\n */\nexport async function processDeployKeyValue(\n ctx: Context,\n deployKey: string | undefined,\n): Promise<string | undefined> {\n if (deployKey === undefined) {\n return undefined;\n }\n\n // Check for <ignore_deploy_key> sentinel\n if (deployKey === \"<ignore_deploy_key>\") {\n return undefined;\n }\n\n // Check for <missing_deploy_key:$STRING> sentinel\n const missingKeyPattern = /^<missing_deploy_key:(.+)>$/;\n const match = deployKey.match(missingKeyPattern);\n if (match) {\n const errorMessage = match[1];\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: errorMessage,\n });\n }\n\n return deployKey;\n}\n\nexport function parsePositiveInteger(value: string) {\n const parsedValue = parseInteger(value);\n if (parsedValue <= 0) {\n // eslint-disable-next-line no-restricted-syntax\n throw new InvalidArgumentError(\"Not a positive number.\");\n }\n return parsedValue;\n}\n\nexport function parseInteger(value: string) {\n const parsedValue = +value;\n if (isNaN(parsedValue)) {\n // eslint-disable-next-line no-restricted-syntax\n throw new InvalidArgumentError(\"Not a number.\");\n }\n return parsedValue;\n}\n\nexport type ErrorData = {\n code: string;\n message: string;\n};\n\n/**\n * Error thrown on non-2XX reponse codes to make most `fetch()` error handling\n * follow a single code path.\n */\nexport class ThrowingFetchError extends Error {\n response: Response;\n serverErrorData?: ErrorData;\n\n constructor(\n msg: string,\n {\n code,\n message,\n response,\n }: { cause?: Error; code?: string; message?: string; response: Response },\n ) {\n if (code !== undefined && message !== undefined) {\n super(`${msg}: ${code}: ${message}`);\n this.serverErrorData = { code, message };\n } else {\n super(msg);\n }\n\n Object.setPrototypeOf(this, ThrowingFetchError.prototype);\n\n this.response = response;\n }\n\n public static async fromResponse(\n response: Response,\n msg?: string,\n ): Promise<ThrowingFetchError> {\n msg = `${msg ? `${msg} ` : \"\"}${response.status} ${response.statusText}`;\n let code, message;\n try {\n ({ code, message } = await response.json());\n } catch {\n // Do nothing because the non-2XX response code is the primary error here.\n }\n return new ThrowingFetchError(msg, { code, message, response });\n }\n\n async handle(ctx: Context): Promise<never> {\n let error_type: ErrorType = \"transient\";\n await checkFetchErrorForDeprecation(ctx, this.response);\n\n let msg = this.message;\n\n if (this.response.status === 400) {\n error_type = \"invalid filesystem or env vars\";\n } else if (this.response.status === 401) {\n error_type = \"fatal\";\n msg = `${msg}\\nAuthenticate with \\`npx convex dev\\``;\n } else if (this.response.status === 404) {\n error_type = \"fatal\";\n msg = `${msg}: ${this.response.url}`;\n }\n\n return await ctx.crash({\n exitCode: 1,\n errorType: error_type,\n errForSentry: this,\n printedMessage: chalkStderr.red(msg.trim()),\n });\n }\n}\n\n/**\n * Thin wrapper around `fetch()` which throws a FetchDataError on non-2XX\n * responses which includes error code and message from the response JSON.\n * (Axios-style)\n *\n * It also accepts retry options from fetch-retry.\n */\nexport async function throwingFetch(\n resource: RequestInfo | URL,\n options: (RequestInit & RequestInitRetryParams<typeof fetch>) | undefined,\n): Promise<Response> {\n const response = await retryingFetch(resource, options);\n if (!response.ok) {\n // This error must always be handled manually.\n // eslint-disable-next-line no-restricted-syntax\n throw await ThrowingFetchError.fromResponse(\n response,\n `Error fetching ${options?.method ? options.method + \" \" : \"\"} ${\n typeof resource === \"string\"\n ? resource\n : \"url\" in resource\n ? resource.url\n : resource.toString()\n }`,\n );\n }\n return response;\n}\n\n/**\n * Handle an error a fetch error or non-2xx response.\n */\nexport async function logAndHandleFetchError(\n ctx: Context,\n err: unknown,\n): Promise<never> {\n // Fail the spinner so the stderr lines appear\n failExistingSpinner();\n\n if (err instanceof ThrowingFetchError) {\n return await err.handle(ctx);\n } else {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"transient\",\n errForSentry: err,\n printedMessage: chalkStderr.red(err),\n });\n }\n}\n\nfunction logDeprecationWarning(ctx: Context, deprecationMessage: string) {\n if (ctx.deprecationMessagePrinted) {\n return;\n }\n ctx.deprecationMessagePrinted = true;\n logWarning(chalkStderr.yellow(deprecationMessage));\n}\n\nasync function checkFetchErrorForDeprecation(ctx: Context, resp: Response) {\n const headers = resp.headers;\n if (headers) {\n const deprecationState = headers.get(\"x-convex-deprecation-state\");\n const deprecationMessage = headers.get(\"x-convex-deprecation-message\");\n switch (deprecationState) {\n case null:\n break;\n case \"Deprecated\":\n // This version is deprecated. Print a warning and crash.\n\n // Gotcha:\n // 1. Don't use `logDeprecationWarning` because we should always print\n // why this we crashed (even if we printed a warning earlier).\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: chalkStderr.red(deprecationMessage),\n });\n default:\n // The error included a deprecation warning. Print, but handle the\n // error normally (it was for another reason).\n logDeprecationWarning(\n ctx,\n deprecationMessage || \"(no deprecation message included)\",\n );\n break;\n }\n }\n}\n\n/// Call this method after a successful API response to conditionally print the\n/// \"please upgrade\" message.\nexport function deprecationCheckWarning(ctx: Context, resp: Response) {\n const headers = resp.headers;\n if (headers) {\n const deprecationState = headers.get(\"x-convex-deprecation-state\");\n const deprecationMessage = headers.get(\"x-convex-deprecation-message\");\n switch (deprecationState) {\n case null:\n break;\n case \"Deprecated\":\n // This should never happen because such states are errors, not warnings.\n // eslint-disable-next-line no-restricted-syntax\n throw new Error(\n \"Called deprecationCheckWarning on a fatal error. This is a bug.\",\n );\n default:\n logDeprecationWarning(\n ctx,\n deprecationMessage || \"(no deprecation message included)\",\n );\n break;\n }\n }\n}\n\nexport async function hasTeam(ctx: Context, teamSlug: string) {\n const teams = (await typedBigBrainClient(ctx).GET(\"/teams\")).data!;\n return teams.some((team) => team.slug === teamSlug);\n}\n\nexport async function validateOrSelectTeam(\n ctx: Context,\n teamSlug: string | undefined,\n promptMessage: string,\n): Promise<{ team: TeamResponse; chosen: boolean }> {\n const teams = (await typedBigBrainClient(ctx).GET(\"/teams\")).data!;\n if (teams.length === 0) {\n await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n errForSentry: \"No teams found\",\n printedMessage: chalkStderr.red(\"Error: No teams found\"),\n });\n }\n if (!teamSlug) {\n // Prompt the user to select if they belong to more than one team.\n switch (teams.length) {\n case 1:\n return { team: teams[0], chosen: false };\n default: {\n const teamSlug = await promptSearch(ctx, {\n message: promptMessage,\n choices: teams.map((team) => ({\n name: `${team.name} (${team.slug})`,\n value: team.slug,\n })),\n });\n const team = teams.find((team) => team.slug === teamSlug);\n if (!team) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `Error: Failed to select team`,\n });\n }\n return { team, chosen: true };\n }\n }\n } else {\n // Validate the chosen team.\n const team = teams.find((team) => team.slug === teamSlug);\n if (!team) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `Error: Team ${teamSlug} not found, fix the --team option or remove it`,\n });\n }\n return { team, chosen: false };\n }\n}\n\nexport async function selectDevDeploymentType(\n ctx: Context,\n {\n chosenConfiguration,\n newOrExisting,\n teamSlug,\n projectSlug,\n userHasChosenSomethingInteractively,\n // from `--configure --dev-deployment local|cloud`\n devDeploymentFromFlag,\n // from `--cloud or --local`\n forceDevDeployment,\n }:\n | {\n chosenConfiguration: \"new\" | \"existing\" | \"ask\" | null;\n newOrExisting: \"existing\";\n teamSlug: string;\n projectSlug: string;\n userHasChosenSomethingInteractively: boolean;\n devDeploymentFromFlag: \"cloud\" | \"local\" | undefined;\n forceDevDeployment: \"cloud\" | \"local\" | undefined;\n }\n | {\n chosenConfiguration: \"new\" | \"existing\" | \"ask\" | null;\n newOrExisting: \"new\";\n teamSlug: string;\n // For new projects we don't know the project slug yet.\n projectSlug: undefined;\n userHasChosenSomethingInteractively: boolean;\n devDeploymentFromFlag: \"cloud\" | \"local\" | undefined;\n forceDevDeployment: \"cloud\" | \"local\" | undefined;\n },\n): Promise<{ devDeployment: \"cloud\" | \"local\" }> {\n if (forceDevDeployment) return { devDeployment: forceDevDeployment };\n if (devDeploymentFromFlag) return { devDeployment: devDeploymentFromFlag };\n\n if (newOrExisting === \"existing\" && chosenConfiguration === null) {\n // Don't suggest local dev if developer already has a cloud deployment.\n if (await projectHasExistingCloudDev(ctx, { projectSlug, teamSlug })) {\n // TODO Expand rollout to offer local dev in this case. ENG-8307\n return { devDeployment: \"cloud\" };\n }\n }\n\n // To avoid breaking previously non-interactive flows, don't prompt if enough\n // flags were specified for configure not to already have needed input.\n if (chosenConfiguration !== \"ask\" && !userHasChosenSomethingInteractively) {\n return { devDeployment: \"cloud\" };\n }\n\n // For creating a first project (no projects exist) or joining a first project\n // (one project exists), always use cloud since it's a smoother experience.\n const isFirstProject =\n (await bigBrainEnableFeatureMetadata(ctx)).totalProjects.kind !==\n \"multiple\";\n if (isFirstProject) {\n return { devDeployment: \"cloud\" };\n }\n\n // For now default is always cloud.\n const devDeployment: \"cloud\" | \"local\" = await promptOptions(ctx, {\n message:\n \"Use cloud or local dev deployment? For more see https://docs.convex.dev/cli/local-deployments\",\n default: \"cloud\",\n choices: [\n { name: \"cloud deployment\", value: \"cloud\" },\n { name: \"local deployment (BETA)\", value: \"local\" },\n ],\n });\n return { devDeployment };\n}\n\nexport async function logNoDefaultRegionMessage(teamSlug: string) {\n const { teamDashboardUrl } = await import(\"../dashboard.js\");\n const noDefaultRegionMessage = chalkStderr.gray(\n `Tip: you can configure a default region for your team at ${chalkStderr.underline(`${teamDashboardUrl(teamSlug)}/settings`)}`,\n );\n logMessage(noDefaultRegionMessage);\n}\n\nexport async function selectRegionOrUseDefault(\n ctx: Context,\n selectedTeam: TeamResponse,\n deploymentType: CloudDeploymentType,\n) {\n if (!process.stdin.isTTY) {\n // Use the team default in non-interactive terminals\n if (!selectedTeam.defaultRegion) {\n await logNoDefaultRegionMessage(selectedTeam.slug);\n }\n return selectedTeam.defaultRegion ?? null;\n }\n const selectedRegionName =\n selectedTeam.defaultRegion ??\n (await selectRegion(ctx, selectedTeam.id, deploymentType));\n if (!selectedTeam.defaultRegion) {\n // Log after the user chooses a region\n await logNoDefaultRegionMessage(selectedTeam.slug);\n }\n return selectedRegionName;\n}\n\nexport async function selectRegion(\n ctx: Context,\n teamId: number,\n deploymentType: CloudDeploymentType,\n): Promise<string> {\n const regionsResponse = (\n await typedPlatformClient(ctx).GET(\n \"/teams/{team_id}/list_deployment_regions\",\n {\n params: {\n path: { team_id: `${teamId}` },\n },\n },\n )\n ).data!;\n const choices = regionsResponse.items\n .filter((item) => Boolean(item.available))\n .map((item) => ({\n name: item.displayName,\n value: item.name,\n }))\n .sort((a, b) => {\n // Show US region first if it exists\n if (a.value === \"aws-us-east-1\") return -1;\n if (b.value === \"aws-us-east-1\") return 1;\n return 0;\n });\n return await promptOptions(ctx, {\n message: `Where should this ${deploymentType} deployment run?`,\n suffix: `\\n${chalkStderr.gray(\n \"See https://www.convex.dev/pricing for pricing\",\n )}`,\n choices,\n });\n}\n\nexport async function hasProject(\n ctx: Context,\n teamSlug: string,\n projectSlug: string,\n) {\n try {\n const projects: Project[] = (\n await typedBigBrainClient(ctx).GET(\"/teams/{team_slug}/projects\", {\n params: {\n path: {\n team_slug: teamSlug,\n },\n },\n })\n ).data!;\n return !!projects.find((project) => project.slug === projectSlug);\n } catch {\n return false;\n }\n}\n\nexport async function hasProjects(ctx: Context) {\n return !!(await bigBrainAPI({ ctx, method: \"GET\", path: `has_projects` }));\n}\n\nexport async function validateOrSelectProject(\n ctx: Context,\n projectSlug: string | undefined,\n teamSlug: string,\n singleProjectPrompt: string,\n multiProjectPrompt: string,\n): Promise<string | null> {\n const projects: Project[] = (\n await typedBigBrainClient(ctx).GET(\"/teams/{team_slug}/projects\", {\n params: {\n path: {\n team_slug: teamSlug,\n },\n },\n })\n ).data!;\n if (projects.length === 0) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `No existing projects! Run this command again and choose \"create a new project.\"`,\n });\n }\n if (!projectSlug) {\n const nonDemoProjects = projects.filter((project) => !project.isDemo);\n if (nonDemoProjects.length === 0) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `No existing non-demo projects! Run this command again and choose \"create a new project.\"`,\n });\n }\n // Prompt the user to select project.\n switch (nonDemoProjects.length) {\n case 1: {\n const project = nonDemoProjects[0];\n const confirmed = await promptYesNo(ctx, {\n message: `${singleProjectPrompt} ${project.name} (${project.slug})?`,\n });\n\n if (!confirmed) {\n return null;\n }\n return nonDemoProjects[0].slug;\n }\n default:\n return await promptSearch(ctx, {\n message: multiProjectPrompt,\n choices: nonDemoProjects.map((project: Project) => ({\n name: `${project.name} (${project.slug})`,\n value: project.slug,\n })),\n });\n }\n } else {\n // Validate the chosen project.\n if (!projects.find((project) => project.slug === projectSlug)) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `Error: Project ${projectSlug} not found, fix the --project option or remove it`,\n });\n }\n return projectSlug;\n }\n}\n\n/**\n * @param ctx\n * @returns a Record of dependency name to dependency version for dependencies\n * and devDependencies\n */\nexport async function loadPackageJson(\n ctx: Context,\n includePeerDeps = false,\n): Promise<Record<string, string>> {\n let packageJson;\n try {\n packageJson = ctx.fs.readUtf8File(\"package.json\");\n } catch (err) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `Unable to read your package.json: ${\n err as any\n }. Make sure you're running this command from the root directory of a Convex app that contains the package.json`,\n });\n }\n let obj;\n try {\n obj = JSON.parse(packageJson);\n } catch (err) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n errForSentry: err,\n printedMessage: `Unable to parse package.json: ${err as any}`,\n });\n }\n if (typeof obj !== \"object\") {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: \"Expected to parse an object from package.json\",\n });\n }\n const packages = {\n ...(includePeerDeps ? (obj.peerDependencies ?? {}) : {}),\n ...(obj.dependencies ?? {}),\n ...(obj.devDependencies ?? {}),\n };\n return packages;\n}\n\nexport async function ensureHasConvexDependency(ctx: Context, cmd: string) {\n const packages = await loadPackageJson(ctx, true);\n const hasConvexDependency = \"convex\" in packages;\n if (!hasConvexDependency) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `In order to ${cmd}, add \\`convex\\` to your package.json dependencies.`,\n });\n }\n}\n\n/** Return a new array with elements of the passed in array sorted by a key lambda */\nexport const sorted = <T>(arr: T[], key: (el: T) => any): T[] => {\n const newArr = [...arr];\n const cmp = (a: T, b: T) => {\n if (key(a) < key(b)) return -1;\n if (key(a) > key(b)) return 1;\n return 0;\n };\n return newArr.sort(cmp);\n};\n\nexport function functionsDir(\n configPath: string,\n projectConfig: ProjectConfig,\n): string {\n return path.join(path.dirname(configPath), projectConfig.functions);\n}\n\nfunction convexName() {\n // Use a different directory for config files generated for tests\n if (process.env.CONVEX_PROVISION_HOST) {\n const port = process.env.CONVEX_PROVISION_HOST.split(\":\")[2];\n if (port === undefined || port === \"8050\") {\n return `convex-test`;\n } else {\n return `convex-test-${port}`;\n }\n }\n return \"convex\";\n}\n\nexport function rootDirectory(): string {\n return path.join(os.homedir(), `.${convexName()}`);\n}\n\nexport function cacheDir() {\n const name = convexName();\n const platform = process.platform;\n if (platform === \"win32\") {\n // On Windows, `LOCALAPPDATA` is usually set, but fall back to\n // `USERPROFILE` if not, and fall back to homedir if all else fails.\n if (process.env.LOCALAPPDATA) {\n return path.join(process.env.LOCALAPPDATA, name);\n }\n if (process.env.USERPROFILE) {\n return path.join(process.env.USERPROFILE, \"AppData\", \"Local\", name);\n }\n return path.join(os.homedir(), \"AppData\", \"Local\", name);\n }\n return path.join(os.homedir(), \".cache\", name);\n}\n\n/**\n * Fetch with appropriate headers for the Convex Management API.\n *\n * This fetch() also has retries and throws if the response is not ok.\n */\nexport function bigBrainFetch(ctx: Context): typeof fetch {\n const authHeader = ctx.bigBrainAuth()?.header;\n const bigBrainHeaders: Record<string, string> = authHeader\n ? {\n Authorization: authHeader,\n \"Convex-Client\": `npm-cli-${version}`,\n }\n : {\n \"Convex-Client\": `npm-cli-${version}`,\n };\n return (resource: RequestInfo | URL, options: RequestInit | undefined) => {\n const { headers: optionsHeaders, ...rest } = options || {};\n // Use the options headers if they exist. Otherwise, use the request headers\n const headers = {\n ...bigBrainHeaders,\n ...(optionsHeaders ??\n (resource instanceof Request\n ? Object.fromEntries(resource.headers.entries())\n : {})),\n };\n const opts = {\n retries: MAX_RETRIES,\n retryDelay,\n headers,\n ...rest,\n };\n\n return throwingFetch(resource, opts);\n };\n}\n\nexport async function bigBrainAPI<T = any>({\n ctx,\n method,\n path,\n data,\n}: {\n ctx: Context;\n method: \"GET\" | \"POST\" | \"HEAD\";\n path: string;\n data?: any;\n}): Promise<T> {\n const dataString =\n data === undefined\n ? undefined\n : typeof data === \"string\"\n ? data\n : JSON.stringify(data);\n try {\n return await bigBrainAPIMaybeThrows({\n ctx,\n method,\n path,\n data: dataString,\n });\n } catch (err: unknown) {\n return await logAndHandleFetchError(ctx, err);\n }\n}\n\n/**\n * Typed API client with a fetch() implemention that includes retries and crashes on errors.\n * It is always safe to call `.data!` on the response: any error would throw or crash.\n *\n * Pass { throw: true } to throw ThrowingFetchErrors instead of exiting the process.\n */\nfunction typedApiClientFactory<T>(\n baseUrl: string,\n fetchBuilder: (ctx: Context) => typeof fetch,\n) {\n return (ctx: Context, options: { throw?: boolean } = {}) => {\n type Paths = T extends CliManagementPaths\n ? CliManagementPaths\n : T extends PlatformManagementPaths\n ? PlatformManagementPaths\n : T extends PlatformDeploymentPaths\n ? PlatformDeploymentPaths\n : never;\n const client = createClient<Paths>({\n baseUrl,\n fetch: fetchBuilder(ctx),\n });\n\n // Wrap the client with error handling - go back to proxy since middleware doesn't catch parsing errors\n return new Proxy(client, {\n get(target, prop) {\n const originalMethod = target[prop as keyof typeof target];\n\n if (\n prop === \"GET\" ||\n prop === \"POST\" ||\n prop === \"HEAD\" ||\n prop === \"OPTIONS\" ||\n prop === \"PUT\" ||\n prop === \"DELETE\" ||\n prop === \"PATCH\" ||\n prop === \"TRACE\"\n ) {\n return async (...args: any[]) => {\n try {\n return await (originalMethod as Function).apply(target, args);\n } catch (err: unknown) {\n if (options.throw) {\n // eslint-disable-next-line no-restricted-syntax\n throw err;\n }\n return await logAndHandleFetchError(ctx, err);\n }\n };\n }\n\n return originalMethod;\n },\n });\n };\n}\n\nexport const typedBigBrainClient = typedApiClientFactory<CliManagementPaths>(\n BIG_BRAIN_URL,\n bigBrainFetch,\n);\nexport const typedPlatformClient =\n typedApiClientFactory<PlatformManagementPaths>(\n PLATFORM_MANAGEMENT_API_URL,\n bigBrainFetch,\n );\n\nexport function typedDeploymentClient(\n ctx: Context,\n args: { deploymentUrl: string; adminKey: string },\n options: { throw?: boolean } = {},\n) {\n return typedApiClientFactory<PlatformDeploymentPaths>(\n `${args.deploymentUrl}/api/v1`,\n (ctx) =>\n deploymentFetch(ctx, {\n deploymentUrl: args.deploymentUrl,\n adminKey: args.adminKey,\n }),\n )(ctx, options);\n}\n\nexport async function bigBrainAPIMaybeThrows({\n ctx,\n method,\n path,\n data,\n}: {\n ctx: Context;\n method: \"GET\" | \"POST\" | \"HEAD\";\n path: string;\n data?: any;\n}): Promise<any> {\n const fetch = bigBrainFetch(ctx);\n const dataString =\n data === undefined\n ? method === \"POST\"\n ? JSON.stringify({})\n : undefined\n : typeof data === \"string\"\n ? data\n : JSON.stringify(data);\n const res = await fetch(new URL(path, BIG_BRAIN_URL), {\n method,\n ...(dataString ? { body: dataString } : {}),\n headers:\n method === \"POST\"\n ? {\n \"Content-Type\": \"application/json\",\n }\n : {},\n });\n deprecationCheckWarning(ctx, res);\n if (res.status === 200) {\n return await res.json();\n }\n}\n\n/**\n * Polls an arbitrary function until a condition is met.\n *\n * @param fetch Function performing a fetch, returning resulting data.\n * @param condition This function will terminate polling when it returns `true`.\n * @param waitMs How long to wait in between fetches.\n * @returns The resulting data from `fetch`.\n */\nexport const poll = async function <Result>(\n fetch: () => Promise<Result>,\n condition: (data: Result) => boolean,\n waitMs = 1000,\n) {\n let result = await fetch();\n while (!condition(result)) {\n await wait(waitMs);\n result = await fetch();\n }\n return result;\n};\n\nconst wait = function (waitMs: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, waitMs);\n });\n};\n\nexport function waitForever() {\n // This never resolves\n return new Promise((_) => {\n // ignore\n });\n}\n\n// Returns a promise and a function that resolves the promise.\nexport function waitUntilCalled(): [Promise<unknown>, () => void] {\n let onCalled: (v: unknown) => void;\n const waitPromise = new Promise((resolve) => (onCalled = resolve));\n return [waitPromise, () => onCalled(null)];\n}\n\nconst BYTE_UNITS: [number, string][] = [\n [1 << 30, \"GiB\"],\n [1_000_000_000, \"GB\"],\n [1 << 20, \"MiB\"],\n [1_000_000, \"MB\"],\n [1 << 10, \"KiB\"],\n [1_000, \"KB\"],\n];\n\n/**\n * Format a byte count into a human-friendly string.\n *\n * Picks the unit (binary or decimal) that divides most cleanly.\n * Shows one decimal place only when it divides exactly (e.g. \"4.1 MiB\").\n * Falls back to raw bytes when no unit divides cleanly.\n */\nexport function formatSize(n: number): string {\n if (n === 0) {\n return \"0 bytes\";\n }\n for (const [unitSize, unitName] of BYTE_UNITS) {\n if (n < unitSize) {\n continue;\n }\n if (n % unitSize === 0) {\n return `${n / unitSize} ${unitName}`;\n }\n if ((n * 10) % unitSize === 0) {\n const whole = Math.floor(n / unitSize);\n const frac = Math.floor((n * 10) / unitSize) % 10;\n return `${whole}.${frac} ${unitName}`;\n }\n }\n return `${n} bytes`;\n}\n\nexport function formatDuration(ms: number): string {\n const twoDigits = (n: number, unit: string) =>\n `${n.toLocaleString(\"en-US\", { maximumFractionDigits: 2 })}${unit}`;\n\n if (ms < 1e-3) {\n return twoDigits(ms * 1e9, \"ns\");\n }\n if (ms < 1) {\n return twoDigits(ms * 1e3, \"\u00B5s\");\n }\n if (ms < 1e3) {\n return twoDigits(ms, \"ms\");\n }\n const s = ms / 1e3;\n if (s < 60) {\n return twoDigits(ms / 1e3, \"s\");\n }\n return twoDigits(s / 60, \"m\");\n}\n\nexport function getCurrentTimeString() {\n const now = new Date();\n const hours = String(now.getHours()).padStart(2, \"0\");\n const minutes = String(now.getMinutes()).padStart(2, \"0\");\n const seconds = String(now.getSeconds()).padStart(2, \"0\");\n return `${hours}:${minutes}:${seconds}`;\n}\n\n// We don't allow running commands in project subdirectories yet,\n// but we can provide better errors if we look around.\nexport async function findParentConfigs(ctx: Context): Promise<{\n parentPackageJson: string;\n parentConvexJson?: string | undefined;\n}> {\n const parentPackageJson = findUp(ctx, \"package.json\");\n if (!parentPackageJson) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage:\n \"No package.json found. To create a new project using Convex, see https://docs.convex.dev/home#quickstarts\",\n });\n }\n const candidateConvexJson =\n parentPackageJson &&\n path.join(path.dirname(parentPackageJson), \"convex.json\");\n const parentConvexJson =\n candidateConvexJson && ctx.fs.exists(candidateConvexJson)\n ? candidateConvexJson\n : undefined;\n return {\n parentPackageJson,\n parentConvexJson,\n };\n}\n\n/**\n * Finds a file in the current working directory or a parent.\n *\n * @returns The absolute path of the first file found or undefined.\n */\nfunction findUp(ctx: Context, filename: string): string | undefined {\n let curDir = path.resolve(\".\");\n let parentDir = curDir;\n do {\n const candidate = path.join(curDir, filename);\n if (ctx.fs.exists(candidate)) {\n return candidate;\n }\n curDir = parentDir;\n parentDir = path.dirname(curDir);\n } while (parentDir !== curDir);\n return;\n}\n\n/**\n * Returns whether there's an existing project config. Throws\n * if this is not a valid directory for a project config.\n */\nexport async function isInExistingProject(ctx: Context) {\n const { parentPackageJson, parentConvexJson } = await findParentConfigs(ctx);\n if (parentPackageJson !== path.resolve(\"package.json\")) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: \"Run this command from the root directory of a project.\",\n });\n }\n return !!parentConvexJson;\n}\n\n// `spawnAsync` is the async version of Node's `spawnSync` (and `spawn`).\n//\n// By default, this returns the produced `stdout` and `stderror` and\n// an error if one was encountered (to mirror `spawnSync`).\n//\n// If `stdio` is set to `\"inherit\"`, pipes `stdout` and `stderror` (\n// pausing the spinner if one is running) and rejects the promise\n// on errors (to mirror `execFileSync`).\nexport function spawnAsync(\n ctx: Context,\n command: string,\n args: ReadonlyArray<string>,\n): Promise<{\n stdout: string;\n stderr: string;\n status: null | number;\n error?: Error | undefined;\n}>;\nexport function spawnAsync(\n ctx: Context,\n command: string,\n args: ReadonlyArray<string>,\n options: { stdio: \"inherit\"; shell?: boolean },\n): Promise<void>;\nexport function spawnAsync(\n _ctx: Context,\n command: string,\n args: ReadonlyArray<string>,\n options?: { stdio: \"inherit\"; shell?: boolean },\n) {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, { shell: options?.shell });\n let stdout = \"\";\n let stderr = \"\";\n\n const pipeOutput = options?.stdio === \"inherit\";\n\n if (pipeOutput) {\n child.stdout.on(\"data\", (text) =>\n logMessage(text.toString(\"utf-8\").trimEnd()),\n );\n child.stderr.on(\"data\", (text) =>\n logError(text.toString(\"utf-8\").trimEnd()),\n );\n } else {\n child.stdout.on(\"data\", (data) => {\n stdout += data.toString(\"utf-8\");\n });\n\n child.stderr.on(\"data\", (data) => {\n stderr += data.toString(\"utf-8\");\n });\n }\n\n const completionListener = (code: number | null) => {\n child.removeListener(\"error\", errorListener);\n const result = pipeOutput\n ? { status: code }\n : { stdout, stderr, status: code };\n if (code !== 0) {\n const argumentString =\n args && args.length > 0 ? ` ${args.join(\" \")}` : \"\";\n const error = new Error(\n `\\`${command}${argumentString}\\` exited with non-zero code: ${code}`,\n );\n if (pipeOutput) {\n reject({ ...result, error });\n } else {\n resolve({ ...result, error });\n }\n } else {\n resolve(result);\n }\n };\n\n const errorListener = (error: Error) => {\n child.removeListener(\"exit\", completionListener);\n child.removeListener(\"close\", completionListener);\n if (pipeOutput) {\n reject({ error, status: null });\n } else {\n resolve({ error, status: null });\n }\n };\n\n if (pipeOutput) {\n child.once(\"exit\", completionListener);\n } else {\n child.once(\"close\", completionListener);\n }\n child.once(\"error\", errorListener);\n });\n}\n\nconst IDEMPOTENT_METHODS = [\"GET\", \"HEAD\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"];\n\nfunction retryDelay(\n attempt: number,\n _error: Error | null,\n _response: Response | null,\n): number {\n // immediate, 1s delay, 2s delay, 4s delay, etc.\n const delay = attempt === 0 ? 1 : 2 ** (attempt - 1) * 1000;\n const randomSum = delay * 0.2 * Math.random();\n return delay + randomSum;\n}\n\nfunction deploymentFetchRetryOn(\n onError?: (err: any, attempt: number) => void,\n method?: string,\n) {\n const shouldRetry = function (\n _attempt: number,\n error: Error | null,\n response: Response | null,\n ): { kind: \"retry\"; error: any } | { kind: \"stop\" } {\n // Retry on network errors.\n if (error !== null) {\n // TODO filter out all SSL errors\n // https://github.com/nodejs/node/blob/8a41d9b636be86350cd32847c3f89d327c4f6ff7/src/crypto/crypto_common.cc#L218-L245\n return { kind: \"retry\", error: error };\n }\n // Retry on 404s since these can sometimes happen with newly created\n // deployments for POSTs.\n if (response?.status === 404) {\n return {\n kind: \"retry\",\n error: `Received response with status ${response.status}`,\n };\n }\n\n // Whatever the error code it doesn't hurt to retry idempotent requests.\n if (\n response &&\n !response.ok &&\n method &&\n IDEMPOTENT_METHODS.includes(method.toUpperCase())\n ) {\n // ...but it's a bit annoying to wait for things we know won't succced\n if (\n [\n 400, // Bad Request\n 401, // Unauthorized\n 402, // PaymentRequired\n 403, // Forbidden\n 405, // Method Not Allowed\n 406, // Not Acceptable\n 412, // Precondition Failed\n 413, // Payload Too Large\n 414, // URI Too Long\n 415, // Unsupported Media Type\n 416, // Range Not Satisfiable\n ].includes(response.status)\n ) {\n return {\n kind: \"stop\",\n };\n }\n return {\n kind: \"retry\",\n error: `Received response with status ${response.status}`,\n };\n }\n\n return { kind: \"stop\" };\n };\n\n return function (\n attempt: number,\n error: Error | null,\n response: Response | null,\n ) {\n const result = shouldRetry(attempt, error, response);\n if (result.kind === \"retry\") {\n onError?.(result.error, attempt);\n }\n if (attempt >= MAX_RETRIES) {\n // Stop retrying if we've exhausted all retries, but do this after we've\n // called `onError` so that the caller can still log the error.\n return false;\n }\n return result.kind === \"retry\";\n };\n}\n\n/**\n * Unlike `deploymentFetch`, this does not add on any headers, so the caller\n * must supply any headers.\n */\nexport function bareDeploymentFetch(\n _ctx: Context,\n options: {\n deploymentUrl: string;\n onError?: (err: any) => void;\n },\n): typeof throwingFetch {\n const { deploymentUrl, onError } = options;\n const onErrorWithAttempt = (err: any, attempt: number) => {\n onError?.(err);\n if (attempt >= RETRY_LOG_THRESHOLD) {\n logMessage(\n chalkStderr.gray(\n `Retrying request (attempt ${attempt}/${MAX_RETRIES})...`,\n ),\n );\n }\n };\n return (resource: RequestInfo | URL, options: RequestInit | undefined) => {\n const url =\n resource instanceof URL\n ? resource.pathname\n : typeof resource === \"string\"\n ? new URL(resource, deploymentUrl)\n : new URL(resource.url, deploymentUrl);\n const func = throwingFetch(url, {\n retryDelay,\n retryOn: deploymentFetchRetryOn(onErrorWithAttempt, options?.method),\n ...options,\n });\n return func;\n };\n}\n\n/**\n * This returns a `fetch` function that will fetch against `deploymentUrl`.\n *\n * It will also set the `Authorization` header, `Content-Type` header, and\n * the `Convex-Client` header if they are not set in the `fetch`.\n */\nexport function deploymentFetch(\n _ctx: Context,\n options: {\n deploymentUrl: string;\n adminKey: string;\n onError?: (err: any) => void;\n },\n): typeof fetch {\n const { deploymentUrl, adminKey, onError } = options;\n const onErrorWithAttempt = (err: any, attempt: number) => {\n onError?.(err);\n if (attempt >= RETRY_LOG_THRESHOLD) {\n logMessage(\n chalkStderr.gray(\n `Retrying request (attempt ${attempt}/${MAX_RETRIES})...`,\n ),\n );\n }\n };\n return (resource: RequestInfo | URL, options: RequestInit | undefined) => {\n const url =\n resource instanceof URL\n ? resource.pathname\n : typeof resource === \"string\"\n ? new URL(resource, deploymentUrl)\n : new URL(resource.url, deploymentUrl);\n\n const headers = new Headers(options?.headers || {});\n if (!headers.has(\"Authorization\")) {\n headers.set(\"Authorization\", `Convex ${adminKey}`);\n }\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n if (!headers.has(\"Convex-Client\")) {\n headers.set(\"Convex-Client\", `npm-cli-${version}`);\n }\n const func = throwingFetch(url, {\n retryDelay,\n retryOn: deploymentFetchRetryOn(onErrorWithAttempt, options?.method),\n ...options,\n headers,\n });\n return func;\n };\n}\n\n/**\n * Whether this is likely to be a WebContainer,\n * WebContainers can't complete the WorkOS login but where that login flow\n * fails has changed with the environment.\n */\nexport function isWebContainer(): boolean {\n // Dynamic require as used here doesn't work with tsx\n if (process.env.CONVEX_RUNNING_LIVE_IN_MONOREPO) {\n return false;\n }\n const dynamicRequire = require;\n if (process.versions.webcontainer === undefined) {\n return false;\n }\n let blitzInternalEnv: unknown;\n try {\n blitzInternalEnv = dynamicRequire(\"@blitz/internal/env\");\n // totally fine for this require to fail\n // eslint-disable-next-line no-empty\n } catch {}\n return blitzInternalEnv !== null && blitzInternalEnv !== undefined;\n}\n\n// For (rare) special behaviors based on package.json details.\nexport async function currentPackageHomepage(\n ctx: Context,\n): Promise<string | null> {\n const { parentPackageJson: packageJsonPath } = await findParentConfigs(ctx);\n let packageJson: any;\n try {\n const packageJsonString = ctx.fs.readUtf8File(packageJsonPath);\n packageJson = JSON.parse(packageJsonString);\n } catch (error: any) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `Couldn't parse \"${packageJsonPath}\". Make sure it's a valid JSON. Error: ${error}`,\n });\n }\n const name = packageJson[\"homepage\"];\n if (typeof name !== \"string\") {\n // wrong type or missing\n return null;\n }\n return name;\n}\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;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;AAEA,mBAA4B;AAC5B,gBAAe;AACf,kBAAiB;AAIjB,2BAAsB;AACtB,uBAAqC;AACrC,yBAA0D;AAE1D,iBAKO;AACP,qBAAwB;AAExB,qB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AA0B;AAExC,MAAI,QAAQ,IAAI,iCAAiC;AAC/C,WAAO;AAAA,EACT;AACA,QAAM,iBAAiB;AACvB,MAAI,QAAQ,SAAS,iBAAiB,QAAW;AAC/C,WAAO;AAAA,EACT;AACA,MAAI;AACJ,MAAI;AACF,uBAAmB,eAAe,qBAAqB;AAAA,EAGzD,QAAQ;AAAA,EAAC;AACT,SAAO,qBAAqB,QAAQ,qBAAqB;AAC3D;AAGA,eAAsB,uBACpB,KACwB;AACxB,QAAM,EAAE,mBAAmB,gBAAgB,IAAI,MAAM,kBAAkB,GAAG;AAC1E,MAAI;AACJ,MAAI;AACF,UAAM,oBAAoB,IAAI,GAAG,aAAa,eAAe;AAC7D,kBAAc,KAAK,MAAM,iBAAiB;AAAA,EAC5C,SAAS,OAAY;AACnB,WAAO,MAAM,IAAI,MAAM;AAAA,MACrB,UAAU;AAAA,MACV,WAAW;AAAA,MACX,gBAAgB,mBAAmB,eAAe,0CAA0C,KAAK;AAAA,IACnG,CAAC;AAAA,EACH;AACA,QAAM,OAAO,YAAY,UAAU;AACnC,MAAI,OAAO,SAAS,UAAU;AAE5B,WAAO;AAAA,EACT;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import { paths as PlatformDeploymentPaths } from \"@convex-dev/platform/deploymentApi\";\nimport { paths as PlatformManagementPaths } from \"@convex-dev/platform/managementApi\";\nimport { chalkStderr } from \"chalk\";\nimport os from \"os\";\nimport path from \"path\";\n\nimport { ProjectConfig } from \"../config.js\";\n\nimport { spawn } from \"child_process\";\nimport { InvalidArgumentError } from \"commander\";\nimport fetchRetryFactory, { RequestInitRetryParams } from \"fetch-retry\";\nimport { Context, ErrorType } from \"../../../bundler/context.js\";\nimport {\n failExistingSpinner,\n logError,\n logMessage,\n logWarning,\n} from \"../../../bundler/log.js\";\nimport { version } from \"../../version.js\";\nimport type { CloudDeploymentType, Project } from \"../api.js\";\nimport { promptOptions, promptSearch, promptYesNo } from \"./prompts.js\";\nimport {\n bigBrainEnableFeatureMetadata,\n projectHasExistingCloudDev,\n} from \"../localDeployment/bigBrain.js\";\nimport type {\n paths as CliManagementPaths,\n TeamResponse,\n} from \"../../generatedApi.js\";\nimport createClient from \"openapi-fetch\";\n\nconst retryingFetch = fetchRetryFactory(fetch);\n\nexport const productionProvisionHost = \"https://api.convex.dev\";\nexport const provisionHost =\n process.env.CONVEX_PROVISION_HOST || productionProvisionHost;\nexport const BIG_BRAIN_URL = `${provisionHost}/api/`;\nconst PLATFORM_MANAGEMENT_API_URL = `${provisionHost}/v1/`;\nexport const ENV_VAR_FILE_PATH = \".env.local\";\nexport const CONVEX_DEPLOY_KEY_ENV_VAR_NAME = \"CONVEX_DEPLOY_KEY\";\n// Alias for CONVEX_DEPLOY_KEY. Accepted anywhere CONVEX_DEPLOY_KEY is.\nexport const CONVEX_DEPLOYMENT_TOKEN_ENV_VAR_NAME = \"CONVEX_DEPLOYMENT_TOKEN\";\nexport const CONVEX_DEPLOYMENT_ENV_VAR_NAME = \"CONVEX_DEPLOYMENT\";\nexport const CONVEX_SELF_HOSTED_URL_VAR_NAME = \"CONVEX_SELF_HOSTED_URL\";\nexport const CONVEX_SELF_HOSTED_ADMIN_KEY_VAR_NAME =\n \"CONVEX_SELF_HOSTED_ADMIN_KEY\";\nconst MAX_RETRIES = 6;\n// After 3 retries, log a progress message that we're retrying the request\nconst RETRY_LOG_THRESHOLD = 3;\n\n/**\n * Processes the CONVEX_DEPLOY_KEY value to handle special sentinel values.\n *\n * - If the value is `<ignore_deploy_key>`, treats it as if the env var isn't set (returns undefined)\n * - If the value matches `<missing_deploy_key:$STRING>`, crashes with the message in $STRING\n * - Otherwise returns the value as-is\n *\n * @param ctx Context for crashing if needed\n * @param deployKey The raw deploy key value from environment or config\n * @returns The processed deploy key value or undefined\n */\nexport async function processDeployKeyValue(\n ctx: Context,\n deployKey: string | undefined,\n): Promise<string | undefined> {\n if (deployKey === undefined) {\n return undefined;\n }\n\n // Check for <ignore_deploy_key> sentinel\n if (deployKey === \"<ignore_deploy_key>\") {\n return undefined;\n }\n\n // Check for <missing_deploy_key:$STRING> sentinel\n const missingKeyPattern = /^<missing_deploy_key:(.+)>$/;\n const match = deployKey.match(missingKeyPattern);\n if (match) {\n const errorMessage = match[1];\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: errorMessage,\n });\n }\n\n return deployKey;\n}\n\n/**\n * Reads the deploy key from environment variables, accepting either\n * CONVEX_DEPLOY_KEY or its alias CONVEX_DEPLOYMENT_TOKEN. CONVEX_DEPLOY_KEY\n * takes precedence when both are set.\n */\nexport function readDeployKeyFromEnv(\n getEnv: (name: string) => string | undefined | null,\n): string | undefined {\n const fromDeployKey = getEnv(CONVEX_DEPLOY_KEY_ENV_VAR_NAME);\n const fromToken = getEnv(CONVEX_DEPLOYMENT_TOKEN_ENV_VAR_NAME);\n return fromDeployKey || fromToken || undefined;\n}\n\nexport function parsePositiveInteger(value: string) {\n const parsedValue = parseInteger(value);\n if (parsedValue <= 0) {\n // eslint-disable-next-line no-restricted-syntax\n throw new InvalidArgumentError(\"Not a positive number.\");\n }\n return parsedValue;\n}\n\nexport function parseInteger(value: string) {\n const parsedValue = +value;\n if (isNaN(parsedValue)) {\n // eslint-disable-next-line no-restricted-syntax\n throw new InvalidArgumentError(\"Not a number.\");\n }\n return parsedValue;\n}\n\nexport type ErrorData = {\n code: string;\n message: string;\n};\n\n/**\n * Error thrown on non-2XX reponse codes to make most `fetch()` error handling\n * follow a single code path.\n */\nexport class ThrowingFetchError extends Error {\n response: Response;\n serverErrorData?: ErrorData;\n\n constructor(\n msg: string,\n {\n code,\n message,\n response,\n }: { cause?: Error; code?: string; message?: string; response: Response },\n ) {\n if (code !== undefined && message !== undefined) {\n super(`${msg}: ${code}: ${message}`);\n this.serverErrorData = { code, message };\n } else {\n super(msg);\n }\n\n Object.setPrototypeOf(this, ThrowingFetchError.prototype);\n\n this.response = response;\n }\n\n public static async fromResponse(\n response: Response,\n msg?: string,\n ): Promise<ThrowingFetchError> {\n msg = `${msg ? `${msg} ` : \"\"}${response.status} ${response.statusText}`;\n let code, message;\n try {\n ({ code, message } = await response.json());\n } catch {\n // Do nothing because the non-2XX response code is the primary error here.\n }\n return new ThrowingFetchError(msg, { code, message, response });\n }\n\n async handle(ctx: Context): Promise<never> {\n let error_type: ErrorType = \"transient\";\n await checkFetchErrorForDeprecation(ctx, this.response);\n\n let msg = this.message;\n\n if (this.response.status === 400) {\n error_type = \"invalid filesystem or env vars\";\n } else if (this.response.status === 401) {\n error_type = \"fatal\";\n msg = `${msg}\\nAuthenticate with \\`npx convex dev\\``;\n } else if (this.response.status === 404) {\n error_type = \"fatal\";\n msg = `${msg}: ${this.response.url}`;\n }\n\n return await ctx.crash({\n exitCode: 1,\n errorType: error_type,\n errForSentry: this,\n printedMessage: chalkStderr.red(msg.trim()),\n });\n }\n}\n\n/**\n * Thin wrapper around `fetch()` which throws a FetchDataError on non-2XX\n * responses which includes error code and message from the response JSON.\n * (Axios-style)\n *\n * It also accepts retry options from fetch-retry.\n */\nexport async function throwingFetch(\n resource: RequestInfo | URL,\n options: (RequestInit & RequestInitRetryParams<typeof fetch>) | undefined,\n): Promise<Response> {\n const response = await retryingFetch(resource, options);\n if (!response.ok) {\n // This error must always be handled manually.\n // eslint-disable-next-line no-restricted-syntax\n throw await ThrowingFetchError.fromResponse(\n response,\n `Error fetching ${options?.method ? options.method + \" \" : \"\"} ${\n typeof resource === \"string\"\n ? resource\n : \"url\" in resource\n ? resource.url\n : resource.toString()\n }`,\n );\n }\n return response;\n}\n\n/**\n * Handle an error a fetch error or non-2xx response.\n */\nexport async function logAndHandleFetchError(\n ctx: Context,\n err: unknown,\n): Promise<never> {\n // Fail the spinner so the stderr lines appear\n failExistingSpinner();\n\n if (err instanceof ThrowingFetchError) {\n return await err.handle(ctx);\n } else {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"transient\",\n errForSentry: err,\n printedMessage: chalkStderr.red(err),\n });\n }\n}\n\nfunction logDeprecationWarning(ctx: Context, deprecationMessage: string) {\n if (ctx.deprecationMessagePrinted) {\n return;\n }\n ctx.deprecationMessagePrinted = true;\n logWarning(chalkStderr.yellow(deprecationMessage));\n}\n\nasync function checkFetchErrorForDeprecation(ctx: Context, resp: Response) {\n const headers = resp.headers;\n if (headers) {\n const deprecationState = headers.get(\"x-convex-deprecation-state\");\n const deprecationMessage = headers.get(\"x-convex-deprecation-message\");\n switch (deprecationState) {\n case null:\n break;\n case \"Deprecated\":\n // This version is deprecated. Print a warning and crash.\n\n // Gotcha:\n // 1. Don't use `logDeprecationWarning` because we should always print\n // why this we crashed (even if we printed a warning earlier).\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: chalkStderr.red(deprecationMessage),\n });\n default:\n // The error included a deprecation warning. Print, but handle the\n // error normally (it was for another reason).\n logDeprecationWarning(\n ctx,\n deprecationMessage || \"(no deprecation message included)\",\n );\n break;\n }\n }\n}\n\n/// Call this method after a successful API response to conditionally print the\n/// \"please upgrade\" message.\nexport function deprecationCheckWarning(ctx: Context, resp: Response) {\n const headers = resp.headers;\n if (headers) {\n const deprecationState = headers.get(\"x-convex-deprecation-state\");\n const deprecationMessage = headers.get(\"x-convex-deprecation-message\");\n switch (deprecationState) {\n case null:\n break;\n case \"Deprecated\":\n // This should never happen because such states are errors, not warnings.\n // eslint-disable-next-line no-restricted-syntax\n throw new Error(\n \"Called deprecationCheckWarning on a fatal error. This is a bug.\",\n );\n default:\n logDeprecationWarning(\n ctx,\n deprecationMessage || \"(no deprecation message included)\",\n );\n break;\n }\n }\n}\n\nexport async function hasTeam(ctx: Context, teamSlug: string) {\n const teams = (await typedBigBrainClient(ctx).GET(\"/teams\")).data!;\n return teams.some((team) => team.slug === teamSlug);\n}\n\nexport async function validateOrSelectTeam(\n ctx: Context,\n teamSlug: string | undefined,\n promptMessage: string,\n): Promise<{ team: TeamResponse; chosen: boolean }> {\n const teams = (await typedBigBrainClient(ctx).GET(\"/teams\")).data!;\n if (teams.length === 0) {\n await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n errForSentry: \"No teams found\",\n printedMessage: chalkStderr.red(\"Error: No teams found\"),\n });\n }\n if (!teamSlug) {\n // Prompt the user to select if they belong to more than one team.\n switch (teams.length) {\n case 1:\n return { team: teams[0], chosen: false };\n default: {\n const teamSlug = await promptSearch(ctx, {\n message: promptMessage,\n choices: teams.map((team) => ({\n name: `${team.name} (${team.slug})`,\n value: team.slug,\n })),\n });\n const team = teams.find((team) => team.slug === teamSlug);\n if (!team) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `Error: Failed to select team`,\n });\n }\n return { team, chosen: true };\n }\n }\n } else {\n // Validate the chosen team.\n const team = teams.find((team) => team.slug === teamSlug);\n if (!team) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `Error: Team ${teamSlug} not found, fix the --team option or remove it`,\n });\n }\n return { team, chosen: false };\n }\n}\n\nexport async function selectDevDeploymentType(\n ctx: Context,\n {\n chosenConfiguration,\n newOrExisting,\n teamSlug,\n projectSlug,\n userHasChosenSomethingInteractively,\n // from `--configure --dev-deployment local|cloud`\n devDeploymentFromFlag,\n // from `--cloud or --local`\n forceDevDeployment,\n }:\n | {\n chosenConfiguration: \"new\" | \"existing\" | \"ask\" | null;\n newOrExisting: \"existing\";\n teamSlug: string;\n projectSlug: string;\n userHasChosenSomethingInteractively: boolean;\n devDeploymentFromFlag: \"cloud\" | \"local\" | undefined;\n forceDevDeployment: \"cloud\" | \"local\" | undefined;\n }\n | {\n chosenConfiguration: \"new\" | \"existing\" | \"ask\" | null;\n newOrExisting: \"new\";\n teamSlug: string;\n // For new projects we don't know the project slug yet.\n projectSlug: undefined;\n userHasChosenSomethingInteractively: boolean;\n devDeploymentFromFlag: \"cloud\" | \"local\" | undefined;\n forceDevDeployment: \"cloud\" | \"local\" | undefined;\n },\n): Promise<{ devDeployment: \"cloud\" | \"local\" }> {\n if (forceDevDeployment) return { devDeployment: forceDevDeployment };\n if (devDeploymentFromFlag) return { devDeployment: devDeploymentFromFlag };\n\n if (newOrExisting === \"existing\" && chosenConfiguration === null) {\n // Don't suggest local dev if developer already has a cloud deployment.\n if (await projectHasExistingCloudDev(ctx, { projectSlug, teamSlug })) {\n // TODO Expand rollout to offer local dev in this case. ENG-8307\n return { devDeployment: \"cloud\" };\n }\n }\n\n // To avoid breaking previously non-interactive flows, don't prompt if enough\n // flags were specified for configure not to already have needed input.\n if (chosenConfiguration !== \"ask\" && !userHasChosenSomethingInteractively) {\n return { devDeployment: \"cloud\" };\n }\n\n // For creating a first project (no projects exist) or joining a first project\n // (one project exists), always use cloud since it's a smoother experience.\n const isFirstProject =\n (await bigBrainEnableFeatureMetadata(ctx)).totalProjects.kind !==\n \"multiple\";\n if (isFirstProject) {\n return { devDeployment: \"cloud\" };\n }\n\n // For now default is always cloud.\n const devDeployment: \"cloud\" | \"local\" = await promptOptions(ctx, {\n message:\n \"Use cloud or local dev deployment? For more see https://docs.convex.dev/cli/local-deployments\",\n default: \"cloud\",\n choices: [\n { name: \"cloud deployment\", value: \"cloud\" },\n { name: \"local deployment (BETA)\", value: \"local\" },\n ],\n });\n return { devDeployment };\n}\n\nexport async function logNoDefaultRegionMessage(teamSlug: string) {\n const { teamDashboardUrl } = await import(\"../dashboard.js\");\n const noDefaultRegionMessage = chalkStderr.gray(\n `Tip: you can configure a default region for your team at ${chalkStderr.underline(`${teamDashboardUrl(teamSlug)}/settings`)}`,\n );\n logMessage(noDefaultRegionMessage);\n}\n\nexport async function selectRegionOrUseDefault(\n ctx: Context,\n selectedTeam: TeamResponse,\n deploymentType: CloudDeploymentType,\n) {\n if (!process.stdin.isTTY) {\n // Use the team default in non-interactive terminals\n if (!selectedTeam.defaultRegion) {\n await logNoDefaultRegionMessage(selectedTeam.slug);\n }\n return selectedTeam.defaultRegion ?? null;\n }\n const selectedRegionName =\n selectedTeam.defaultRegion ??\n (await selectRegion(ctx, selectedTeam.id, deploymentType));\n if (!selectedTeam.defaultRegion) {\n // Log after the user chooses a region\n await logNoDefaultRegionMessage(selectedTeam.slug);\n }\n return selectedRegionName;\n}\n\nexport async function selectRegion(\n ctx: Context,\n teamId: number,\n deploymentType: CloudDeploymentType,\n): Promise<string> {\n const regionsResponse = (\n await typedPlatformClient(ctx).GET(\n \"/teams/{team_id}/list_deployment_regions\",\n {\n params: {\n path: { team_id: `${teamId}` },\n },\n },\n )\n ).data!;\n const choices = regionsResponse.items\n .filter((item) => Boolean(item.available))\n .map((item) => ({\n name: item.displayName,\n value: item.name,\n }))\n .sort((a, b) => {\n // Show US region first if it exists\n if (a.value === \"aws-us-east-1\") return -1;\n if (b.value === \"aws-us-east-1\") return 1;\n return 0;\n });\n return await promptOptions(ctx, {\n message: `Where should this ${deploymentType} deployment run?`,\n suffix: `\\n${chalkStderr.gray(\n \"See https://www.convex.dev/pricing for pricing\",\n )}`,\n choices,\n });\n}\n\nexport async function hasProject(\n ctx: Context,\n teamSlug: string,\n projectSlug: string,\n) {\n try {\n const projects: Project[] = (\n await typedBigBrainClient(ctx).GET(\"/teams/{team_slug}/projects\", {\n params: {\n path: {\n team_slug: teamSlug,\n },\n },\n })\n ).data!;\n return !!projects.find((project) => project.slug === projectSlug);\n } catch {\n return false;\n }\n}\n\nexport async function hasProjects(ctx: Context) {\n return !!(await bigBrainAPI({ ctx, method: \"GET\", path: `has_projects` }));\n}\n\nexport async function validateOrSelectProject(\n ctx: Context,\n projectSlug: string | undefined,\n teamSlug: string,\n singleProjectPrompt: string,\n multiProjectPrompt: string,\n): Promise<string | null> {\n const projects: Project[] = (\n await typedBigBrainClient(ctx).GET(\"/teams/{team_slug}/projects\", {\n params: {\n path: {\n team_slug: teamSlug,\n },\n },\n })\n ).data!;\n if (projects.length === 0) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `No existing projects! Run this command again and choose \"create a new project.\"`,\n });\n }\n if (!projectSlug) {\n const nonDemoProjects = projects.filter((project) => !project.isDemo);\n if (nonDemoProjects.length === 0) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `No existing non-demo projects! Run this command again and choose \"create a new project.\"`,\n });\n }\n // Prompt the user to select project.\n switch (nonDemoProjects.length) {\n case 1: {\n const project = nonDemoProjects[0];\n const confirmed = await promptYesNo(ctx, {\n message: `${singleProjectPrompt} ${project.name} (${project.slug})?`,\n });\n\n if (!confirmed) {\n return null;\n }\n return nonDemoProjects[0].slug;\n }\n default:\n return await promptSearch(ctx, {\n message: multiProjectPrompt,\n choices: nonDemoProjects.map((project: Project) => ({\n name: `${project.name} (${project.slug})`,\n value: project.slug,\n })),\n });\n }\n } else {\n // Validate the chosen project.\n if (!projects.find((project) => project.slug === projectSlug)) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `Error: Project ${projectSlug} not found, fix the --project option or remove it`,\n });\n }\n return projectSlug;\n }\n}\n\n/**\n * @param ctx\n * @returns a Record of dependency name to dependency version for dependencies\n * and devDependencies\n */\nexport async function loadPackageJson(\n ctx: Context,\n includePeerDeps = false,\n): Promise<Record<string, string>> {\n let packageJson;\n try {\n packageJson = ctx.fs.readUtf8File(\"package.json\");\n } catch (err) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `Unable to read your package.json: ${\n err as any\n }. Make sure you're running this command from the root directory of a Convex app that contains the package.json`,\n });\n }\n let obj;\n try {\n obj = JSON.parse(packageJson);\n } catch (err) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n errForSentry: err,\n printedMessage: `Unable to parse package.json: ${err as any}`,\n });\n }\n if (typeof obj !== \"object\") {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: \"Expected to parse an object from package.json\",\n });\n }\n const packages = {\n ...(includePeerDeps ? (obj.peerDependencies ?? {}) : {}),\n ...(obj.dependencies ?? {}),\n ...(obj.devDependencies ?? {}),\n };\n return packages;\n}\n\nexport async function ensureHasConvexDependency(ctx: Context, cmd: string) {\n const packages = await loadPackageJson(ctx, true);\n const hasConvexDependency = \"convex\" in packages;\n if (!hasConvexDependency) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `In order to ${cmd}, add \\`convex\\` to your package.json dependencies.`,\n });\n }\n}\n\n/** Return a new array with elements of the passed in array sorted by a key lambda */\nexport const sorted = <T>(arr: T[], key: (el: T) => any): T[] => {\n const newArr = [...arr];\n const cmp = (a: T, b: T) => {\n if (key(a) < key(b)) return -1;\n if (key(a) > key(b)) return 1;\n return 0;\n };\n return newArr.sort(cmp);\n};\n\nexport function functionsDir(\n configPath: string,\n projectConfig: ProjectConfig,\n): string {\n return path.join(path.dirname(configPath), projectConfig.functions);\n}\n\nfunction convexName() {\n // Use a different directory for config files generated for tests\n if (process.env.CONVEX_PROVISION_HOST) {\n const port = process.env.CONVEX_PROVISION_HOST.split(\":\")[2];\n if (port === undefined || port === \"8050\") {\n return `convex-test`;\n } else {\n return `convex-test-${port}`;\n }\n }\n return \"convex\";\n}\n\nexport function rootDirectory(): string {\n return path.join(os.homedir(), `.${convexName()}`);\n}\n\nexport function cacheDir() {\n const name = convexName();\n const platform = process.platform;\n if (platform === \"win32\") {\n // On Windows, `LOCALAPPDATA` is usually set, but fall back to\n // `USERPROFILE` if not, and fall back to homedir if all else fails.\n if (process.env.LOCALAPPDATA) {\n return path.join(process.env.LOCALAPPDATA, name);\n }\n if (process.env.USERPROFILE) {\n return path.join(process.env.USERPROFILE, \"AppData\", \"Local\", name);\n }\n return path.join(os.homedir(), \"AppData\", \"Local\", name);\n }\n return path.join(os.homedir(), \".cache\", name);\n}\n\n/**\n * Fetch with appropriate headers for the Convex Management API.\n *\n * This fetch() also has retries and throws if the response is not ok.\n */\nexport function bigBrainFetch(ctx: Context): typeof fetch {\n const authHeader = ctx.bigBrainAuth()?.header;\n const bigBrainHeaders: Record<string, string> = authHeader\n ? {\n Authorization: authHeader,\n \"Convex-Client\": `npm-cli-${version}`,\n }\n : {\n \"Convex-Client\": `npm-cli-${version}`,\n };\n return (resource: RequestInfo | URL, options: RequestInit | undefined) => {\n const { headers: optionsHeaders, ...rest } = options || {};\n // Use the options headers if they exist. Otherwise, use the request headers\n const headers = {\n ...bigBrainHeaders,\n ...(optionsHeaders ??\n (resource instanceof Request\n ? Object.fromEntries(resource.headers.entries())\n : {})),\n };\n const opts = {\n retries: MAX_RETRIES,\n retryDelay,\n headers,\n ...rest,\n };\n\n return throwingFetch(resource, opts);\n };\n}\n\nexport async function bigBrainAPI<T = any>({\n ctx,\n method,\n path,\n data,\n}: {\n ctx: Context;\n method: \"GET\" | \"POST\" | \"HEAD\";\n path: string;\n data?: any;\n}): Promise<T> {\n const dataString =\n data === undefined\n ? undefined\n : typeof data === \"string\"\n ? data\n : JSON.stringify(data);\n try {\n return await bigBrainAPIMaybeThrows({\n ctx,\n method,\n path,\n data: dataString,\n });\n } catch (err: unknown) {\n return await logAndHandleFetchError(ctx, err);\n }\n}\n\n/**\n * Typed API client with a fetch() implemention that includes retries and crashes on errors.\n * It is always safe to call `.data!` on the response: any error would throw or crash.\n *\n * Pass { throw: true } to throw ThrowingFetchErrors instead of exiting the process.\n */\nfunction typedApiClientFactory<T>(\n baseUrl: string,\n fetchBuilder: (ctx: Context) => typeof fetch,\n) {\n return (ctx: Context, options: { throw?: boolean } = {}) => {\n type Paths = T extends CliManagementPaths\n ? CliManagementPaths\n : T extends PlatformManagementPaths\n ? PlatformManagementPaths\n : T extends PlatformDeploymentPaths\n ? PlatformDeploymentPaths\n : never;\n const client = createClient<Paths>({\n baseUrl,\n fetch: fetchBuilder(ctx),\n });\n\n // Wrap the client with error handling - go back to proxy since middleware doesn't catch parsing errors\n return new Proxy(client, {\n get(target, prop) {\n const originalMethod = target[prop as keyof typeof target];\n\n if (\n prop === \"GET\" ||\n prop === \"POST\" ||\n prop === \"HEAD\" ||\n prop === \"OPTIONS\" ||\n prop === \"PUT\" ||\n prop === \"DELETE\" ||\n prop === \"PATCH\" ||\n prop === \"TRACE\"\n ) {\n return async (...args: any[]) => {\n try {\n return await (originalMethod as Function).apply(target, args);\n } catch (err: unknown) {\n if (options.throw) {\n // eslint-disable-next-line no-restricted-syntax\n throw err;\n }\n return await logAndHandleFetchError(ctx, err);\n }\n };\n }\n\n return originalMethod;\n },\n });\n };\n}\n\nexport const typedBigBrainClient = typedApiClientFactory<CliManagementPaths>(\n BIG_BRAIN_URL,\n bigBrainFetch,\n);\nexport const typedPlatformClient =\n typedApiClientFactory<PlatformManagementPaths>(\n PLATFORM_MANAGEMENT_API_URL,\n bigBrainFetch,\n );\n\nexport function typedDeploymentClient(\n ctx: Context,\n args: { deploymentUrl: string; adminKey: string },\n options: { throw?: boolean } = {},\n) {\n return typedApiClientFactory<PlatformDeploymentPaths>(\n `${args.deploymentUrl}/api/v1`,\n (ctx) =>\n deploymentFetch(ctx, {\n deploymentUrl: args.deploymentUrl,\n adminKey: args.adminKey,\n }),\n )(ctx, options);\n}\n\nexport async function bigBrainAPIMaybeThrows({\n ctx,\n method,\n path,\n data,\n}: {\n ctx: Context;\n method: \"GET\" | \"POST\" | \"HEAD\";\n path: string;\n data?: any;\n}): Promise<any> {\n const fetch = bigBrainFetch(ctx);\n const dataString =\n data === undefined\n ? method === \"POST\"\n ? JSON.stringify({})\n : undefined\n : typeof data === \"string\"\n ? data\n : JSON.stringify(data);\n const res = await fetch(new URL(path, BIG_BRAIN_URL), {\n method,\n ...(dataString ? { body: dataString } : {}),\n headers:\n method === \"POST\"\n ? {\n \"Content-Type\": \"application/json\",\n }\n : {},\n });\n deprecationCheckWarning(ctx, res);\n if (res.status === 200) {\n return await res.json();\n }\n}\n\n/**\n * Polls an arbitrary function until a condition is met.\n *\n * @param fetch Function performing a fetch, returning resulting data.\n * @param condition This function will terminate polling when it returns `true`.\n * @param waitMs How long to wait in between fetches.\n * @returns The resulting data from `fetch`.\n */\nexport const poll = async function <Result>(\n fetch: () => Promise<Result>,\n condition: (data: Result) => boolean,\n waitMs = 1000,\n) {\n let result = await fetch();\n while (!condition(result)) {\n await wait(waitMs);\n result = await fetch();\n }\n return result;\n};\n\nconst wait = function (waitMs: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, waitMs);\n });\n};\n\nexport function waitForever() {\n // This never resolves\n return new Promise((_) => {\n // ignore\n });\n}\n\n// Returns a promise and a function that resolves the promise.\nexport function waitUntilCalled(): [Promise<unknown>, () => void] {\n let onCalled: (v: unknown) => void;\n const waitPromise = new Promise((resolve) => (onCalled = resolve));\n return [waitPromise, () => onCalled(null)];\n}\n\nconst BYTE_UNITS: [number, string][] = [\n [1 << 30, \"GiB\"],\n [1_000_000_000, \"GB\"],\n [1 << 20, \"MiB\"],\n [1_000_000, \"MB\"],\n [1 << 10, \"KiB\"],\n [1_000, \"KB\"],\n];\n\n/**\n * Format a byte count into a human-friendly string.\n *\n * Picks the unit (binary or decimal) that divides most cleanly.\n * Shows one decimal place only when it divides exactly (e.g. \"4.1 MiB\").\n * Falls back to raw bytes when no unit divides cleanly.\n */\nexport function formatSize(n: number): string {\n if (n === 0) {\n return \"0 bytes\";\n }\n for (const [unitSize, unitName] of BYTE_UNITS) {\n if (n < unitSize) {\n continue;\n }\n if (n % unitSize === 0) {\n return `${n / unitSize} ${unitName}`;\n }\n if ((n * 10) % unitSize === 0) {\n const whole = Math.floor(n / unitSize);\n const frac = Math.floor((n * 10) / unitSize) % 10;\n return `${whole}.${frac} ${unitName}`;\n }\n }\n return `${n} bytes`;\n}\n\nexport function formatDuration(ms: number): string {\n const twoDigits = (n: number, unit: string) =>\n `${n.toLocaleString(\"en-US\", { maximumFractionDigits: 2 })}${unit}`;\n\n if (ms < 1e-3) {\n return twoDigits(ms * 1e9, \"ns\");\n }\n if (ms < 1) {\n return twoDigits(ms * 1e3, \"\u00B5s\");\n }\n if (ms < 1e3) {\n return twoDigits(ms, \"ms\");\n }\n const s = ms / 1e3;\n if (s < 60) {\n return twoDigits(ms / 1e3, \"s\");\n }\n return twoDigits(s / 60, \"m\");\n}\n\nexport function getCurrentTimeString() {\n const now = new Date();\n const hours = String(now.getHours()).padStart(2, \"0\");\n const minutes = String(now.getMinutes()).padStart(2, \"0\");\n const seconds = String(now.getSeconds()).padStart(2, \"0\");\n return `${hours}:${minutes}:${seconds}`;\n}\n\n// We don't allow running commands in project subdirectories yet,\n// but we can provide better errors if we look around.\nexport async function findParentConfigs(ctx: Context): Promise<{\n parentPackageJson: string;\n parentConvexJson?: string | undefined;\n}> {\n const parentPackageJson = findUp(ctx, \"package.json\");\n if (!parentPackageJson) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage:\n \"No package.json found. To create a new project using Convex, see https://docs.convex.dev/home#quickstarts\",\n });\n }\n const candidateConvexJson =\n parentPackageJson &&\n path.join(path.dirname(parentPackageJson), \"convex.json\");\n const parentConvexJson =\n candidateConvexJson && ctx.fs.exists(candidateConvexJson)\n ? candidateConvexJson\n : undefined;\n return {\n parentPackageJson,\n parentConvexJson,\n };\n}\n\n/**\n * Finds a file in the current working directory or a parent.\n *\n * @returns The absolute path of the first file found or undefined.\n */\nfunction findUp(ctx: Context, filename: string): string | undefined {\n let curDir = path.resolve(\".\");\n let parentDir = curDir;\n do {\n const candidate = path.join(curDir, filename);\n if (ctx.fs.exists(candidate)) {\n return candidate;\n }\n curDir = parentDir;\n parentDir = path.dirname(curDir);\n } while (parentDir !== curDir);\n return;\n}\n\n/**\n * Returns whether there's an existing project config. Throws\n * if this is not a valid directory for a project config.\n */\nexport async function isInExistingProject(ctx: Context) {\n const { parentPackageJson, parentConvexJson } = await findParentConfigs(ctx);\n if (parentPackageJson !== path.resolve(\"package.json\")) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: \"Run this command from the root directory of a project.\",\n });\n }\n return !!parentConvexJson;\n}\n\n// `spawnAsync` is the async version of Node's `spawnSync` (and `spawn`).\n//\n// By default, this returns the produced `stdout` and `stderror` and\n// an error if one was encountered (to mirror `spawnSync`).\n//\n// If `stdio` is set to `\"inherit\"`, pipes `stdout` and `stderror` (\n// pausing the spinner if one is running) and rejects the promise\n// on errors (to mirror `execFileSync`).\nexport function spawnAsync(\n ctx: Context,\n command: string,\n args: ReadonlyArray<string>,\n): Promise<{\n stdout: string;\n stderr: string;\n status: null | number;\n error?: Error | undefined;\n}>;\nexport function spawnAsync(\n ctx: Context,\n command: string,\n args: ReadonlyArray<string>,\n options: { stdio: \"inherit\"; shell?: boolean },\n): Promise<void>;\nexport function spawnAsync(\n _ctx: Context,\n command: string,\n args: ReadonlyArray<string>,\n options?: { stdio: \"inherit\"; shell?: boolean },\n) {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, { shell: options?.shell });\n let stdout = \"\";\n let stderr = \"\";\n\n const pipeOutput = options?.stdio === \"inherit\";\n\n if (pipeOutput) {\n child.stdout.on(\"data\", (text) =>\n logMessage(text.toString(\"utf-8\").trimEnd()),\n );\n child.stderr.on(\"data\", (text) =>\n logError(text.toString(\"utf-8\").trimEnd()),\n );\n } else {\n child.stdout.on(\"data\", (data) => {\n stdout += data.toString(\"utf-8\");\n });\n\n child.stderr.on(\"data\", (data) => {\n stderr += data.toString(\"utf-8\");\n });\n }\n\n const completionListener = (code: number | null) => {\n child.removeListener(\"error\", errorListener);\n const result = pipeOutput\n ? { status: code }\n : { stdout, stderr, status: code };\n if (code !== 0) {\n const argumentString =\n args && args.length > 0 ? ` ${args.join(\" \")}` : \"\";\n const error = new Error(\n `\\`${command}${argumentString}\\` exited with non-zero code: ${code}`,\n );\n if (pipeOutput) {\n reject({ ...result, error });\n } else {\n resolve({ ...result, error });\n }\n } else {\n resolve(result);\n }\n };\n\n const errorListener = (error: Error) => {\n child.removeListener(\"exit\", completionListener);\n child.removeListener(\"close\", completionListener);\n if (pipeOutput) {\n reject({ error, status: null });\n } else {\n resolve({ error, status: null });\n }\n };\n\n if (pipeOutput) {\n child.once(\"exit\", completionListener);\n } else {\n child.once(\"close\", completionListener);\n }\n child.once(\"error\", errorListener);\n });\n}\n\nconst IDEMPOTENT_METHODS = [\"GET\", \"HEAD\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"];\n\nfunction retryDelay(\n attempt: number,\n _error: Error | null,\n _response: Response | null,\n): number {\n // immediate, 1s delay, 2s delay, 4s delay, etc.\n const delay = attempt === 0 ? 1 : 2 ** (attempt - 1) * 1000;\n const randomSum = delay * 0.2 * Math.random();\n return delay + randomSum;\n}\n\nfunction deploymentFetchRetryOn(\n onError?: (err: any, attempt: number) => void,\n method?: string,\n) {\n const shouldRetry = function (\n _attempt: number,\n error: Error | null,\n response: Response | null,\n ): { kind: \"retry\"; error: any } | { kind: \"stop\" } {\n // Retry on network errors.\n if (error !== null) {\n // TODO filter out all SSL errors\n // https://github.com/nodejs/node/blob/8a41d9b636be86350cd32847c3f89d327c4f6ff7/src/crypto/crypto_common.cc#L218-L245\n return { kind: \"retry\", error: error };\n }\n // Retry on 404s since these can sometimes happen with newly created\n // deployments for POSTs.\n if (response?.status === 404) {\n return {\n kind: \"retry\",\n error: `Received response with status ${response.status}`,\n };\n }\n\n // Whatever the error code it doesn't hurt to retry idempotent requests.\n if (\n response &&\n !response.ok &&\n method &&\n IDEMPOTENT_METHODS.includes(method.toUpperCase())\n ) {\n // ...but it's a bit annoying to wait for things we know won't succced\n if (\n [\n 400, // Bad Request\n 401, // Unauthorized\n 402, // PaymentRequired\n 403, // Forbidden\n 405, // Method Not Allowed\n 406, // Not Acceptable\n 412, // Precondition Failed\n 413, // Payload Too Large\n 414, // URI Too Long\n 415, // Unsupported Media Type\n 416, // Range Not Satisfiable\n ].includes(response.status)\n ) {\n return {\n kind: \"stop\",\n };\n }\n return {\n kind: \"retry\",\n error: `Received response with status ${response.status}`,\n };\n }\n\n return { kind: \"stop\" };\n };\n\n return function (\n attempt: number,\n error: Error | null,\n response: Response | null,\n ) {\n const result = shouldRetry(attempt, error, response);\n if (result.kind === \"retry\") {\n onError?.(result.error, attempt);\n }\n if (attempt >= MAX_RETRIES) {\n // Stop retrying if we've exhausted all retries, but do this after we've\n // called `onError` so that the caller can still log the error.\n return false;\n }\n return result.kind === \"retry\";\n };\n}\n\n/**\n * Unlike `deploymentFetch`, this does not add on any headers, so the caller\n * must supply any headers.\n */\nexport function bareDeploymentFetch(\n _ctx: Context,\n options: {\n deploymentUrl: string;\n onError?: (err: any) => void;\n },\n): typeof throwingFetch {\n const { deploymentUrl, onError } = options;\n const onErrorWithAttempt = (err: any, attempt: number) => {\n onError?.(err);\n if (attempt >= RETRY_LOG_THRESHOLD) {\n logMessage(\n chalkStderr.gray(\n `Retrying request (attempt ${attempt}/${MAX_RETRIES})...`,\n ),\n );\n }\n };\n return (resource: RequestInfo | URL, options: RequestInit | undefined) => {\n const url =\n resource instanceof URL\n ? resource.pathname\n : typeof resource === \"string\"\n ? new URL(resource, deploymentUrl)\n : new URL(resource.url, deploymentUrl);\n const func = throwingFetch(url, {\n retryDelay,\n retryOn: deploymentFetchRetryOn(onErrorWithAttempt, options?.method),\n ...options,\n });\n return func;\n };\n}\n\n/**\n * This returns a `fetch` function that will fetch against `deploymentUrl`.\n *\n * It will also set the `Authorization` header, `Content-Type` header, and\n * the `Convex-Client` header if they are not set in the `fetch`.\n */\nexport function deploymentFetch(\n _ctx: Context,\n options: {\n deploymentUrl: string;\n adminKey: string;\n onError?: (err: any) => void;\n },\n): typeof fetch {\n const { deploymentUrl, adminKey, onError } = options;\n const onErrorWithAttempt = (err: any, attempt: number) => {\n onError?.(err);\n if (attempt >= RETRY_LOG_THRESHOLD) {\n logMessage(\n chalkStderr.gray(\n `Retrying request (attempt ${attempt}/${MAX_RETRIES})...`,\n ),\n );\n }\n };\n return (resource: RequestInfo | URL, options: RequestInit | undefined) => {\n const url =\n resource instanceof URL\n ? resource.pathname\n : typeof resource === \"string\"\n ? new URL(resource, deploymentUrl)\n : new URL(resource.url, deploymentUrl);\n\n const headers = new Headers(options?.headers || {});\n if (!headers.has(\"Authorization\")) {\n headers.set(\"Authorization\", `Convex ${adminKey}`);\n }\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n if (!headers.has(\"Convex-Client\")) {\n headers.set(\"Convex-Client\", `npm-cli-${version}`);\n }\n const func = throwingFetch(url, {\n retryDelay,\n retryOn: deploymentFetchRetryOn(onErrorWithAttempt, options?.method),\n ...options,\n headers,\n });\n return func;\n };\n}\n\n/**\n * Whether this is likely to be a WebContainer,\n * WebContainers can't complete the WorkOS login but where that login flow\n * fails has changed with the environment.\n */\nexport function isWebContainer(): boolean {\n // Dynamic require as used here doesn't work with tsx\n if (process.env.CONVEX_RUNNING_LIVE_IN_MONOREPO) {\n return false;\n }\n const dynamicRequire = require;\n if (process.versions.webcontainer === undefined) {\n return false;\n }\n let blitzInternalEnv: unknown;\n try {\n blitzInternalEnv = dynamicRequire(\"@blitz/internal/env\");\n // totally fine for this require to fail\n // eslint-disable-next-line no-empty\n } catch {}\n return blitzInternalEnv !== null && blitzInternalEnv !== undefined;\n}\n\n// For (rare) special behaviors based on package.json details.\nexport async function currentPackageHomepage(\n ctx: Context,\n): Promise<string | null> {\n const { parentPackageJson: packageJsonPath } = await findParentConfigs(ctx);\n let packageJson: any;\n try {\n const packageJsonString = ctx.fs.readUtf8File(packageJsonPath);\n packageJson = JSON.parse(packageJsonString);\n } catch (error: any) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `Couldn't parse \"${packageJsonPath}\". Make sure it's a valid JSON. Error: ${error}`,\n });\n }\n const name = packageJson[\"homepage\"];\n if (typeof name !== \"string\") {\n // wrong type or missing\n return null;\n }\n return name;\n}\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;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", "createClient", "ctx", "fetch", "options"]
7
7
  }
package/dist/cjs/index.js CHANGED
@@ -21,5 +21,5 @@ __export(index_exports, {
21
21
  version: () => version
22
22
  });
23
23
  module.exports = __toCommonJS(index_exports);
24
- const version = "1.37.0";
24
+ const version = "1.38.0";
25
25
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/index.ts"],
4
- "sourcesContent": ["export const version = \"1.37.0\";\n"],
4
+ "sourcesContent": ["export const version = \"1.38.0\";\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,MAAM,UAAU;",
6
6
  "names": []
7
7
  }
@@ -22,6 +22,7 @@ __export(audit_logging_exports, {
22
22
  cloneWithSentinels: () => cloneWithSentinels
23
23
  });
24
24
  module.exports = __toCommonJS(audit_logging_exports);
25
+ var import__ = require("../index.js");
25
26
  var import_syscall = require("./impl/syscall.js");
26
27
  var import_logVars = require("./logVars.js");
27
28
  function validateKey(key) {
@@ -61,7 +62,8 @@ function cloneWithSentinels(body) {
61
62
  }
62
63
  const audit = async (body) => {
63
64
  await (0, import_syscall.performAsyncSyscall)("1.0/auditLog", {
64
- body: cloneWithSentinels(body)
65
+ body: cloneWithSentinels(body),
66
+ version: import__.version
65
67
  });
66
68
  };
67
69
  //# sourceMappingURL=audit_logging.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/server/audit_logging.ts"],
4
- "sourcesContent": ["import { performAsyncSyscall } from \"./impl/syscall.js\";\nimport { LogVar, varNames } from \"./logVars.js\";\n\nexport type AuditLogBody = { [key: string]: AuditLogValue };\nexport type AuditLogValue =\n | null\n | undefined\n | boolean\n | number\n | string\n | LogVar\n | AuditLogValue[]\n | { [key: string]: AuditLogValue };\n\ntype JsonValue =\n | null\n | undefined\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nfunction validateKey(key: string) {\n if (key.startsWith(\"$\")) {\n throw new Error(`Audit log body keys must not start with \"$\": \"${key}\"`);\n }\n}\n\nfunction cloneValue(value: AuditLogValue): JsonValue {\n if (typeof value === \"symbol\") {\n if (!(value in varNames)) {\n throw new Error(\n `Unknown audit var symbol: ${String(value)}. Use one of log.var.requestId, log.var.ip, log.var.userAgent, or log.var.now.`,\n );\n }\n return { $var: varNames[value] };\n }\n if (value === null || value === undefined || typeof value !== \"object\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(cloneValue);\n }\n const result: { [key: string]: JsonValue } = {};\n for (const [key, val] of Object.entries(value)) {\n validateKey(key);\n result[key] = cloneValue(val);\n }\n return result;\n}\n\n/**\n * Deep-clone the body, replacing audit var symbols with sentinel objects\n * like `{ $var: \"ip\" }`.\n */\nexport function cloneWithSentinels(body: AuditLogBody): {\n [key: string]: JsonValue;\n} {\n const result: { [key: string]: JsonValue } = {};\n for (const [key, val] of Object.entries(body)) {\n validateKey(key);\n result[key] = cloneValue(val);\n }\n return result;\n}\n\n/**\n * @internal\n */\nexport const audit = async (body: AuditLogBody): Promise<void> => {\n await performAsyncSyscall(\"1.0/auditLog\", {\n body: cloneWithSentinels(body),\n });\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAoC;AACpC,qBAAiC;AAsBjC,SAAS,YAAY,KAAa;AAChC,MAAI,IAAI,WAAW,GAAG,GAAG;AACvB,UAAM,IAAI,MAAM,iDAAiD,GAAG,GAAG;AAAA,EACzE;AACF;AAEA,SAAS,WAAW,OAAiC;AACnD,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,EAAE,SAAS,0BAAW;AACxB,YAAM,IAAI;AAAA,QACR,6BAA6B,OAAO,KAAK,CAAC;AAAA,MAC5C;AAAA,IACF;AACA,WAAO,EAAE,MAAM,wBAAS,KAAK,EAAE;AAAA,EACjC;AACA,MAAI,UAAU,QAAQ,UAAU,UAAa,OAAO,UAAU,UAAU;AACtE,WAAO;AAAA,EACT;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,UAAU;AAAA,EAC7B;AACA,QAAM,SAAuC,CAAC;AAC9C,aAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC9C,gBAAY,GAAG;AACf,WAAO,GAAG,IAAI,WAAW,GAAG;AAAA,EAC9B;AACA,SAAO;AACT;AAMO,SAAS,mBAAmB,MAEjC;AACA,QAAM,SAAuC,CAAC;AAC9C,aAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC7C,gBAAY,GAAG;AACf,WAAO,GAAG,IAAI,WAAW,GAAG;AAAA,EAC9B;AACA,SAAO;AACT;AAKO,MAAM,QAAQ,OAAO,SAAsC;AAChE,YAAM,oCAAoB,gBAAgB;AAAA,IACxC,MAAM,mBAAmB,IAAI;AAAA,EAC/B,CAAC;AACH;",
4
+ "sourcesContent": ["import { version } from \"../index.js\";\nimport { performAsyncSyscall } from \"./impl/syscall.js\";\nimport { LogVar, varNames } from \"./logVars.js\";\n\nexport type AuditLogBody = { [key: string]: AuditLogValue };\nexport type AuditLogValue =\n | null\n | undefined\n | boolean\n | number\n | string\n | LogVar\n | AuditLogValue[]\n | { [key: string]: AuditLogValue };\n\ntype JsonValue =\n | null\n | undefined\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nfunction validateKey(key: string) {\n if (key.startsWith(\"$\")) {\n throw new Error(`Audit log body keys must not start with \"$\": \"${key}\"`);\n }\n}\n\nfunction cloneValue(value: AuditLogValue): JsonValue {\n if (typeof value === \"symbol\") {\n if (!(value in varNames)) {\n throw new Error(\n `Unknown audit var symbol: ${String(value)}. Use one of log.var.requestId, log.var.ip, log.var.userAgent, or log.var.now.`,\n );\n }\n return { $var: varNames[value] };\n }\n if (value === null || value === undefined || typeof value !== \"object\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(cloneValue);\n }\n const result: { [key: string]: JsonValue } = {};\n for (const [key, val] of Object.entries(value)) {\n validateKey(key);\n result[key] = cloneValue(val);\n }\n return result;\n}\n\n/**\n * Deep-clone the body, replacing audit var symbols with sentinel objects\n * like `{ $var: \"ip\" }`.\n */\nexport function cloneWithSentinels(body: AuditLogBody): {\n [key: string]: JsonValue;\n} {\n const result: { [key: string]: JsonValue } = {};\n for (const [key, val] of Object.entries(body)) {\n validateKey(key);\n result[key] = cloneValue(val);\n }\n return result;\n}\n\nexport const audit = async (body: AuditLogBody): Promise<void> => {\n await performAsyncSyscall(\"1.0/auditLog\", {\n body: cloneWithSentinels(body),\n version,\n });\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAAwB;AACxB,qBAAoC;AACpC,qBAAiC;AAsBjC,SAAS,YAAY,KAAa;AAChC,MAAI,IAAI,WAAW,GAAG,GAAG;AACvB,UAAM,IAAI,MAAM,iDAAiD,GAAG,GAAG;AAAA,EACzE;AACF;AAEA,SAAS,WAAW,OAAiC;AACnD,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,EAAE,SAAS,0BAAW;AACxB,YAAM,IAAI;AAAA,QACR,6BAA6B,OAAO,KAAK,CAAC;AAAA,MAC5C;AAAA,IACF;AACA,WAAO,EAAE,MAAM,wBAAS,KAAK,EAAE;AAAA,EACjC;AACA,MAAI,UAAU,QAAQ,UAAU,UAAa,OAAO,UAAU,UAAU;AACtE,WAAO;AAAA,EACT;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MAAM,IAAI,UAAU;AAAA,EAC7B;AACA,QAAM,SAAuC,CAAC;AAC9C,aAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC9C,gBAAY,GAAG;AACf,WAAO,GAAG,IAAI,WAAW,GAAG;AAAA,EAC9B;AACA,SAAO;AACT;AAMO,SAAS,mBAAmB,MAEjC;AACA,QAAM,SAAuC,CAAC;AAC9C,aAAW,CAAC,KAAK,GAAG,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC7C,gBAAY,GAAG;AACf,WAAO,GAAG,IAAI,WAAW,GAAG;AAAA,EAC9B;AACA,SAAO;AACT;AAEO,MAAM,QAAQ,OAAO,SAAsC;AAChE,YAAM,oCAAoB,gBAAgB;AAAA,IACxC,MAAM,mBAAmB,IAAI;AAAA,IAC7B;AAAA,EACF,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -176,19 +176,10 @@ function serializeChildComponents(childComponents) {
176
176
  });
177
177
  }
178
178
  function exportComponentForAnalysis() {
179
- const args = Object.entries(
180
- this._args
181
- ).map(([name, validator]) => [
182
- name,
183
- {
184
- type: "value",
185
- value: JSON.stringify(validator.json)
186
- }
187
- ]);
188
179
  const definitionType = {
189
180
  type: "childComponent",
190
181
  name: this._name,
191
- args
182
+ args: []
192
183
  };
193
184
  const childComponents = serializeChildComponents(this._childComponents);
194
185
  const httpMounts = buildHttpMounts(this._childComponents);
@@ -204,13 +195,11 @@ function defineComponent(name) {
204
195
  const ret = {
205
196
  _isRoot: false,
206
197
  _name: name,
207
- _args: {},
208
198
  _childComponents: [],
209
199
  _exportTree: {},
210
200
  _onInitCallbacks: {},
211
201
  export: exportComponentForAnalysis,
212
202
  use,
213
- // pretend to conform to ComponentDefinition, which temporarily expects __args
214
203
  ...{}
215
204
  };
216
205
  return ret;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/server/components/index.ts"],
4
- "sourcesContent": ["import { PropertyValidators, convexToJson } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport {\n AnyFunctionReference,\n FunctionReference,\n FunctionType,\n} from \"../api.js\";\nimport { performAsyncSyscall } from \"../impl/syscall.js\";\nimport { DefaultFunctionArgs } from \"../registration.js\";\nimport {\n AppDefinitionAnalysis,\n ComponentDefinitionAnalysis,\n ComponentDefinitionType,\n} from \"./definition.js\";\nimport {\n getFunctionAddress,\n setReferencePath,\n toReferencePath,\n} from \"./paths.js\";\nexport { getFunctionAddress } from \"./paths.js\";\n\n/**\n * A serializable reference to a Convex function.\n * Passing a this reference to another component allows that component to call this\n * function during the current function execution or at any later time.\n * Function handles are used like `api.folder.function` FunctionReferences,\n * e.g. `ctx.scheduler.runAfter(0, functionReference, args)`.\n *\n * A function reference is stable across code pushes but it's possible\n * the Convex function it refers to might no longer exist.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type FunctionHandle<\n Type extends FunctionType,\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n> = string & FunctionReference<Type, \"internal\", Args, ReturnType>;\n\n/**\n * Create a serializable reference to a Convex function.\n * Passing a this reference to another component allows that component to call this\n * function during the current function execution or at any later time.\n * Function handles are used like `api.folder.function` FunctionReferences,\n * e.g. `ctx.scheduler.runAfter(0, functionReference, args)`.\n *\n * A function reference is stable across code pushes but it's possible\n * the Convex function it refers to might no longer exist.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport async function createFunctionHandle<\n Type extends FunctionType,\n Args extends DefaultFunctionArgs,\n ReturnType,\n>(\n functionReference: FunctionReference<\n Type,\n \"public\" | \"internal\",\n Args,\n ReturnType\n >,\n): Promise<FunctionHandle<Type, Args, ReturnType>> {\n const address = getFunctionAddress(functionReference);\n return await performAsyncSyscall(\"1.0/createFunctionHandle\", {\n ...address,\n version,\n });\n}\n\ninterface ComponentExports {\n [key: string]: FunctionReference<any, any, any, any> | ComponentExports;\n}\n\n/**\n * An object of this type should be the default export of a\n * convex.config.ts file in a component definition directory.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type ComponentDefinition<Exports extends ComponentExports = any> = {\n /**\n * Install a component with the given definition in this component definition.\n *\n * Takes a component definition and an optional name.\n *\n * For editor tooling this method expects a {@link ComponentDefinition}\n * but at runtime the object that is imported will be a {@link ImportedComponentDefinition}\n */\n use<Definition extends ComponentDefinition<any>>(\n definition: Definition,\n options?: {\n name?: string;\n httpPrefix?: string;\n },\n ): InstalledComponent<Definition>;\n\n /**\n * Internal type-only property tracking exports provided.\n *\n * @deprecated This is a type-only property, don't use it.\n */\n __exports: Exports;\n};\n\ntype ComponentDefinitionExports<T extends ComponentDefinition<any>> =\n T[\"__exports\"];\n\n/**\n * An object of this type should be the default export of a\n * convex.config.ts file in a component-aware convex directory.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type AppDefinition = {\n /**\n * Install a component with the given definition in this component definition.\n *\n * Takes a component definition and an optional name.\n *\n * For editor tooling this method expects a {@link ComponentDefinition}\n * but at runtime the object that is imported will be a {@link ImportedComponentDefinition}\n */\n use<Definition extends ComponentDefinition<any>>(\n definition: Definition,\n options?: {\n name?: string;\n httpPrefix?: string;\n },\n ): InstalledComponent<Definition>;\n};\n\ninterface ExportTree {\n // Tree with serialized `Reference`s as leaves.\n [key: string]: string | ExportTree;\n}\n\ntype CommonDefinitionData = {\n _isRoot: boolean;\n _childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][];\n _exportTree: ExportTree;\n};\n\ntype ComponentDefinitionData = CommonDefinitionData & {\n _args: PropertyValidators;\n _name: string;\n _onInitCallbacks: Record<string, (argsStr: string) => string>;\n};\ntype AppDefinitionData = CommonDefinitionData & {\n _httpPrefix?: string;\n};\n\n/**\n * Used to refer to an already-installed component.\n */\nclass InstalledComponent<Definition extends ComponentDefinition<any>> {\n /**\n * @internal\n */\n _definition: Definition;\n\n /**\n * @internal\n */\n _name: string;\n\n constructor(definition: Definition, name: string) {\n this._definition = definition;\n this._name = name;\n setReferencePath(this, `_reference/childComponent/${name}`);\n }\n\n get exports(): ComponentDefinitionExports<Definition> {\n return createExports(this._name, []);\n }\n}\n\nfunction createExports(name: string, pathParts: string[]): any {\n const handler: ProxyHandler<any> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createExports(name, newParts);\n } else if (prop === toReferencePath) {\n let reference = `_reference/childComponent/${name}`;\n for (const part of pathParts) {\n reference += `/${part}`;\n }\n return reference;\n } else {\n return undefined;\n }\n },\n };\n return new Proxy({}, handler);\n}\n\nfunction use<Definition extends ComponentDefinition<any>>(\n this: CommonDefinitionData,\n definition: Definition,\n options?: {\n name?: string;\n httpPrefix?: string;\n },\n): InstalledComponent<Definition> {\n // At runtime an imported component will have this shape.\n const importedComponentDefinition =\n definition as unknown as ImportedComponentDefinition;\n if (typeof importedComponentDefinition.componentDefinitionPath !== \"string\") {\n throw new Error(\n \"Component definition does not have the required componentDefinitionPath property. This code only works in Convex runtime.\",\n );\n }\n const name =\n options?.name ??\n // added recently\n importedComponentDefinition.defaultName ??\n // can be removed once backend is out\n importedComponentDefinition.componentDefinitionPath.split(\"/\").pop()!;\n\n if (typeof name !== \"string\") {\n throw new Error(\n `Component name must be a string. Received: ${typeof name}`,\n );\n }\n if (name.length === 0) {\n // \"\" is used internally as the name for the root component, so\n // users shouldn\u2019t try to define child components with an empty name.\n throw new Error(\"Component name cannot be empty.\");\n }\n\n const httpPrefix = options?.httpPrefix;\n if (httpPrefix !== undefined) {\n if (!httpPrefix.startsWith(\"/\")) {\n throw new Error(\n `httpPrefix must start with \"/\". Received: \"${httpPrefix}\"`,\n );\n }\n }\n\n this._childComponents.push([\n name,\n importedComponentDefinition,\n {},\n httpPrefix,\n ]);\n return new InstalledComponent(definition, name);\n}\n\n/**\n * The runtime type of a ComponentDefinition. TypeScript will claim\n * the default export of a module like \"cool-component/convex.config.js\"\n * is a `@link ComponentDefinition}, but during component definition evaluation\n * this is its type instead.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type ImportedComponentDefinition = {\n componentDefinitionPath: string;\n defaultName: string;\n};\n\nfunction exportAppForAnalysis(\n this: ComponentDefinition<any> & AppDefinitionData,\n): AppDefinitionAnalysis {\n const definitionType = { type: \"app\" as const };\n const childComponents = serializeChildComponents(this._childComponents);\n const httpMounts = buildHttpMounts(this._childComponents);\n return {\n definitionType,\n ...(this._httpPrefix !== undefined\n ? { httpPrefix: normalizeHttpPrefix(this._httpPrefix) }\n : {}),\n childComponents: childComponents as any,\n httpMounts,\n exports: serializeExportTree(this._exportTree),\n };\n}\n\nfunction serializeExportTree(tree: ExportTree): any {\n const branch: any[] = [];\n for (const [key, child] of Object.entries(tree)) {\n let node;\n if (typeof child === \"string\") {\n node = { type: \"leaf\", leaf: child };\n } else {\n node = serializeExportTree(child);\n }\n branch.push([key, node]);\n }\n return { type: \"branch\", branch };\n}\n\nfunction normalizeHttpPrefix(prefix: string): string {\n // Ensure the prefix ends with \"/\" as required by HttpMountPath in Rust.\n return prefix.endsWith(\"/\") ? prefix : prefix + \"/\";\n}\n\nfunction buildHttpMounts(\n childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][],\n): Record<string, string> {\n const httpMounts: Record<string, string> = {};\n for (const [name, , , httpPrefix] of childComponents) {\n if (httpPrefix !== undefined) {\n const normalized = normalizeHttpPrefix(httpPrefix);\n httpMounts[normalized] = `_reference/childComponent/${name}`;\n }\n }\n return httpMounts;\n}\n\nfunction serializeChildComponents(\n childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][],\n): {\n name: string;\n path: string;\n args: [string, { type: \"value\"; value: string }][] | null;\n}[] {\n return childComponents.map(([name, definition, p]) => {\n // Note: httpPrefix (4th element) is used separately in buildHttpMounts()\n let args: [string, { type: \"value\"; value: string }][] | null = null;\n if (p !== null) {\n args = [];\n for (const [name, value] of Object.entries(p)) {\n if (value !== undefined) {\n args.push([\n name,\n { type: \"value\", value: JSON.stringify(convexToJson(value)) },\n ]);\n }\n }\n }\n // we know that components carry this extra information\n const path = definition.componentDefinitionPath;\n if (!path)\n throw new Error(\n \"no .componentPath for component definition \" +\n JSON.stringify(definition, null, 2),\n );\n\n return {\n name: name!,\n path: path!,\n args,\n };\n });\n}\n\nfunction exportComponentForAnalysis(\n this: ComponentDefinition<any> & ComponentDefinitionData,\n): ComponentDefinitionAnalysis {\n const args: [string, { type: \"value\"; value: string }][] = Object.entries(\n this._args,\n ).map(([name, validator]) => [\n name,\n {\n type: \"value\",\n value: JSON.stringify(validator.json),\n },\n ]);\n const definitionType: ComponentDefinitionType = {\n type: \"childComponent\" as const,\n name: this._name,\n args,\n };\n const childComponents = serializeChildComponents(this._childComponents);\n const httpMounts = buildHttpMounts(this._childComponents);\n return {\n name: this._name,\n definitionType,\n childComponents: childComponents as any,\n httpMounts,\n exports: serializeExportTree(this._exportTree),\n };\n}\n\n// This is what is actually contained in a ComponentDefinition.\ntype RuntimeComponentDefinition = Omit<ComponentDefinition<any>, \"__exports\"> &\n ComponentDefinitionData & {\n export: () => ComponentDefinitionAnalysis;\n };\ntype RuntimeAppDefinition = AppDefinition &\n AppDefinitionData & {\n export: () => AppDefinitionAnalysis;\n };\n\n/**\n * Define a component, a piece of a Convex deployment with namespaced resources.\n *\n * The default\n * the default export of a module like \"cool-component/convex.config.js\"\n * is a `@link ComponentDefinition}, but during component definition evaluation\n * this is its type instead.\n *\n * @param name Name must be alphanumeric plus underscores. Typically these are\n * lowercase with underscores like `\"onboarding_flow_tracker\"`.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport function defineComponent<Exports extends ComponentExports = any>(\n name: string,\n): ComponentDefinition<Exports> {\n const ret: RuntimeComponentDefinition = {\n _isRoot: false,\n _name: name,\n _args: {},\n _childComponents: [],\n _exportTree: {},\n _onInitCallbacks: {},\n\n export: exportComponentForAnalysis,\n use,\n\n // pretend to conform to ComponentDefinition, which temporarily expects __args\n ...({} as { __args: any; __exports: any }),\n };\n return ret as any as ComponentDefinition<Exports>;\n}\n\n/**\n * Attach components, reuseable pieces of a Convex deployment, to this Convex app.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport function defineApp(options?: { httpPrefix?: string }): AppDefinition {\n const httpPrefix = options?.httpPrefix;\n if (httpPrefix !== undefined && !httpPrefix.startsWith(\"/\")) {\n throw new Error(\n `httpPrefix must start with \"/\". Received: \"${httpPrefix}\"`,\n );\n }\n const ret: RuntimeAppDefinition = {\n _isRoot: true,\n _childComponents: [],\n _exportTree: {},\n ...(httpPrefix !== undefined ? { _httpPrefix: httpPrefix } : {}),\n\n export: exportAppForAnalysis,\n use,\n };\n return ret as AppDefinition;\n}\n\ntype AnyInterfaceType = {\n [key: string]: AnyInterfaceType;\n} & AnyFunctionReference;\nexport type AnyComponentReference = Record<string, AnyInterfaceType>;\n\nexport type AnyChildComponents = Record<string, AnyComponentReference>;\n\n/**\n * @internal\n */\nexport function currentSystemUdfInComponent(\n componentId: string,\n): AnyComponentReference {\n return {\n [toReferencePath]: `_reference/currentSystemUdfInComponent/${componentId}`,\n };\n}\n\nfunction createChildComponents(\n root: string,\n pathParts: string[],\n): AnyChildComponents {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createChildComponents(root, newParts);\n } else if (prop === toReferencePath) {\n if (pathParts.length < 1) {\n const found = [root, ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`${root}.childComponent.functionName\\`. Found: \\`${found}\\``,\n );\n }\n return `_reference/childComponent/` + pathParts.join(\"/\");\n } else {\n return undefined;\n }\n },\n };\n return new Proxy({}, handler);\n}\n\nexport const componentsGeneric = () => createChildComponents(\"components\", []);\n\nexport type AnyComponents = AnyChildComponents;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAiD;AACjD,eAAwB;AAMxB,qBAAoC;AAOpC,mBAIO;AACP,IAAAA,gBAAmC;AAkCnC,eAAsB,qBAK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F;AACA,SAAO,IAAI,MAAM,CAAC,GAAG,OAAO;AAC9B;AAEO,MAAM,oBAAoB,MAAM,sBAAsB,cAAc,CAAC,CAAC;",
4
+ "sourcesContent": ["import { convexToJson } from \"../../values/index.js\";\nimport { version } from \"../../index.js\";\nimport {\n AnyFunctionReference,\n FunctionReference,\n FunctionType,\n} from \"../api.js\";\nimport { performAsyncSyscall } from \"../impl/syscall.js\";\nimport { DefaultFunctionArgs } from \"../registration.js\";\nimport {\n AppDefinitionAnalysis,\n ComponentDefinitionAnalysis,\n ComponentDefinitionType,\n} from \"./definition.js\";\nimport {\n getFunctionAddress,\n setReferencePath,\n toReferencePath,\n} from \"./paths.js\";\nexport { getFunctionAddress } from \"./paths.js\";\n\n/**\n * A serializable reference to a Convex function.\n * Passing a this reference to another component allows that component to call this\n * function during the current function execution or at any later time.\n * Function handles are used like `api.folder.function` FunctionReferences,\n * e.g. `ctx.scheduler.runAfter(0, functionReference, args)`.\n *\n * A function reference is stable across code pushes but it's possible\n * the Convex function it refers to might no longer exist.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type FunctionHandle<\n Type extends FunctionType,\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n> = string & FunctionReference<Type, \"internal\", Args, ReturnType>;\n\n/**\n * Create a serializable reference to a Convex function.\n * Passing a this reference to another component allows that component to call this\n * function during the current function execution or at any later time.\n * Function handles are used like `api.folder.function` FunctionReferences,\n * e.g. `ctx.scheduler.runAfter(0, functionReference, args)`.\n *\n * A function reference is stable across code pushes but it's possible\n * the Convex function it refers to might no longer exist.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport async function createFunctionHandle<\n Type extends FunctionType,\n Args extends DefaultFunctionArgs,\n ReturnType,\n>(\n functionReference: FunctionReference<\n Type,\n \"public\" | \"internal\",\n Args,\n ReturnType\n >,\n): Promise<FunctionHandle<Type, Args, ReturnType>> {\n const address = getFunctionAddress(functionReference);\n return await performAsyncSyscall(\"1.0/createFunctionHandle\", {\n ...address,\n version,\n });\n}\n\ninterface ComponentExports {\n [key: string]: FunctionReference<any, any, any, any> | ComponentExports;\n}\n\n/**\n * An object of this type should be the default export of a\n * convex.config.ts file in a component definition directory.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type ComponentDefinition<Exports extends ComponentExports = any> = {\n /**\n * Install a component with the given definition in this component definition.\n *\n * Takes a component definition and an optional name.\n *\n * For editor tooling this method expects a {@link ComponentDefinition}\n * but at runtime the object that is imported will be a {@link ImportedComponentDefinition}\n */\n use<Definition extends ComponentDefinition<any>>(\n definition: Definition,\n options?: {\n name?: string;\n httpPrefix?: string;\n },\n ): InstalledComponent<Definition>;\n\n /**\n * Internal type-only property tracking exports provided.\n *\n * @deprecated This is a type-only property, don't use it.\n */\n __exports: Exports;\n};\n\ntype ComponentDefinitionExports<T extends ComponentDefinition<any>> =\n T[\"__exports\"];\n\n/**\n * An object of this type should be the default export of a\n * convex.config.ts file in a component-aware convex directory.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type AppDefinition = {\n /**\n * Install a component with the given definition in this component definition.\n *\n * Takes a component definition and an optional name.\n *\n * For editor tooling this method expects a {@link ComponentDefinition}\n * but at runtime the object that is imported will be a {@link ImportedComponentDefinition}\n */\n use<Definition extends ComponentDefinition<any>>(\n definition: Definition,\n options?: {\n name?: string;\n httpPrefix?: string;\n },\n ): InstalledComponent<Definition>;\n};\n\ninterface ExportTree {\n // Tree with serialized `Reference`s as leaves.\n [key: string]: string | ExportTree;\n}\n\ntype CommonDefinitionData = {\n _isRoot: boolean;\n _childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][];\n _exportTree: ExportTree;\n};\n\ntype ComponentDefinitionData = CommonDefinitionData & {\n _name: string;\n _onInitCallbacks: Record<string, (argsStr: string) => string>;\n};\ntype AppDefinitionData = CommonDefinitionData & {\n _httpPrefix?: string;\n};\n\n/**\n * Used to refer to an already-installed component.\n */\nclass InstalledComponent<Definition extends ComponentDefinition<any>> {\n /**\n * @internal\n */\n _definition: Definition;\n\n /**\n * @internal\n */\n _name: string;\n\n constructor(definition: Definition, name: string) {\n this._definition = definition;\n this._name = name;\n setReferencePath(this, `_reference/childComponent/${name}`);\n }\n\n get exports(): ComponentDefinitionExports<Definition> {\n return createExports(this._name, []);\n }\n}\n\nfunction createExports(name: string, pathParts: string[]): any {\n const handler: ProxyHandler<any> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createExports(name, newParts);\n } else if (prop === toReferencePath) {\n let reference = `_reference/childComponent/${name}`;\n for (const part of pathParts) {\n reference += `/${part}`;\n }\n return reference;\n } else {\n return undefined;\n }\n },\n };\n return new Proxy({}, handler);\n}\n\nfunction use<Definition extends ComponentDefinition<any>>(\n this: CommonDefinitionData,\n definition: Definition,\n options?: {\n name?: string;\n httpPrefix?: string;\n },\n): InstalledComponent<Definition> {\n // At runtime an imported component will have this shape.\n const importedComponentDefinition =\n definition as unknown as ImportedComponentDefinition;\n if (typeof importedComponentDefinition.componentDefinitionPath !== \"string\") {\n throw new Error(\n \"Component definition does not have the required componentDefinitionPath property. This code only works in Convex runtime.\",\n );\n }\n const name =\n options?.name ??\n // added recently\n importedComponentDefinition.defaultName ??\n // can be removed once backend is out\n importedComponentDefinition.componentDefinitionPath.split(\"/\").pop()!;\n\n if (typeof name !== \"string\") {\n throw new Error(\n `Component name must be a string. Received: ${typeof name}`,\n );\n }\n if (name.length === 0) {\n // \"\" is used internally as the name for the root component, so\n // users shouldn\u2019t try to define child components with an empty name.\n throw new Error(\"Component name cannot be empty.\");\n }\n\n const httpPrefix = options?.httpPrefix;\n if (httpPrefix !== undefined) {\n if (!httpPrefix.startsWith(\"/\")) {\n throw new Error(\n `httpPrefix must start with \"/\". Received: \"${httpPrefix}\"`,\n );\n }\n }\n\n this._childComponents.push([\n name,\n importedComponentDefinition,\n {},\n httpPrefix,\n ]);\n return new InstalledComponent(definition, name);\n}\n\n/**\n * The runtime type of a ComponentDefinition. TypeScript will claim\n * the default export of a module like \"cool-component/convex.config.js\"\n * is a `@link ComponentDefinition}, but during component definition evaluation\n * this is its type instead.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport type ImportedComponentDefinition = {\n componentDefinitionPath: string;\n defaultName: string;\n};\n\nfunction exportAppForAnalysis(\n this: ComponentDefinition<any> & AppDefinitionData,\n): AppDefinitionAnalysis {\n const definitionType = { type: \"app\" as const };\n const childComponents = serializeChildComponents(this._childComponents);\n const httpMounts = buildHttpMounts(this._childComponents);\n return {\n definitionType,\n ...(this._httpPrefix !== undefined\n ? { httpPrefix: normalizeHttpPrefix(this._httpPrefix) }\n : {}),\n childComponents: childComponents as any,\n httpMounts,\n exports: serializeExportTree(this._exportTree),\n };\n}\n\nfunction serializeExportTree(tree: ExportTree): any {\n const branch: any[] = [];\n for (const [key, child] of Object.entries(tree)) {\n let node;\n if (typeof child === \"string\") {\n node = { type: \"leaf\", leaf: child };\n } else {\n node = serializeExportTree(child);\n }\n branch.push([key, node]);\n }\n return { type: \"branch\", branch };\n}\n\nfunction normalizeHttpPrefix(prefix: string): string {\n // Ensure the prefix ends with \"/\" as required by HttpMountPath in Rust.\n return prefix.endsWith(\"/\") ? prefix : prefix + \"/\";\n}\n\nfunction buildHttpMounts(\n childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][],\n): Record<string, string> {\n const httpMounts: Record<string, string> = {};\n for (const [name, , , httpPrefix] of childComponents) {\n if (httpPrefix !== undefined) {\n const normalized = normalizeHttpPrefix(httpPrefix);\n httpMounts[normalized] = `_reference/childComponent/${name}`;\n }\n }\n return httpMounts;\n}\n\nfunction serializeChildComponents(\n childComponents: [\n string,\n ImportedComponentDefinition,\n Record<string, any> | null,\n string | undefined,\n ][],\n): {\n name: string;\n path: string;\n args: [string, { type: \"value\"; value: string }][] | null;\n}[] {\n return childComponents.map(([name, definition, p]) => {\n // Note: httpPrefix (4th element) is used separately in buildHttpMounts()\n let args: [string, { type: \"value\"; value: string }][] | null = null;\n if (p !== null) {\n args = [];\n for (const [name, value] of Object.entries(p)) {\n if (value !== undefined) {\n args.push([\n name,\n { type: \"value\", value: JSON.stringify(convexToJson(value)) },\n ]);\n }\n }\n }\n // we know that components carry this extra information\n const path = definition.componentDefinitionPath;\n if (!path)\n throw new Error(\n \"no .componentPath for component definition \" +\n JSON.stringify(definition, null, 2),\n );\n\n return {\n name: name!,\n path: path!,\n args,\n };\n });\n}\n\nfunction exportComponentForAnalysis(\n this: ComponentDefinition<any> & ComponentDefinitionData,\n): ComponentDefinitionAnalysis {\n const definitionType: ComponentDefinitionType = {\n type: \"childComponent\" as const,\n name: this._name,\n args: [],\n };\n const childComponents = serializeChildComponents(this._childComponents);\n const httpMounts = buildHttpMounts(this._childComponents);\n return {\n name: this._name,\n definitionType,\n childComponents: childComponents as any,\n httpMounts,\n exports: serializeExportTree(this._exportTree),\n };\n}\n\n// This is what is actually contained in a ComponentDefinition.\ntype RuntimeComponentDefinition = Omit<ComponentDefinition<any>, \"__exports\"> &\n ComponentDefinitionData & {\n export: () => ComponentDefinitionAnalysis;\n };\ntype RuntimeAppDefinition = AppDefinition &\n AppDefinitionData & {\n export: () => AppDefinitionAnalysis;\n };\n\n/**\n * Define a component, a piece of a Convex deployment with namespaced resources.\n *\n * The default\n * the default export of a module like \"cool-component/convex.config.js\"\n * is a `@link ComponentDefinition}, but during component definition evaluation\n * this is its type instead.\n *\n * @param name Name must be alphanumeric plus underscores. Typically these are\n * lowercase with underscores like `\"onboarding_flow_tracker\"`.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport function defineComponent<Exports extends ComponentExports = any>(\n name: string,\n): ComponentDefinition<Exports> {\n const ret: RuntimeComponentDefinition = {\n _isRoot: false,\n _name: name,\n _childComponents: [],\n _exportTree: {},\n _onInitCallbacks: {},\n\n export: exportComponentForAnalysis,\n use,\n\n ...({} as { __exports: any }),\n };\n return ret as any as ComponentDefinition<Exports>;\n}\n\n/**\n * Attach components, reuseable pieces of a Convex deployment, to this Convex app.\n *\n * This is a feature of components, which are in beta.\n * This API is unstable and may change in subsequent releases.\n */\nexport function defineApp(options?: { httpPrefix?: string }): AppDefinition {\n const httpPrefix = options?.httpPrefix;\n if (httpPrefix !== undefined && !httpPrefix.startsWith(\"/\")) {\n throw new Error(\n `httpPrefix must start with \"/\". Received: \"${httpPrefix}\"`,\n );\n }\n const ret: RuntimeAppDefinition = {\n _isRoot: true,\n _childComponents: [],\n _exportTree: {},\n ...(httpPrefix !== undefined ? { _httpPrefix: httpPrefix } : {}),\n\n export: exportAppForAnalysis,\n use,\n };\n return ret as AppDefinition;\n}\n\ntype AnyInterfaceType = {\n [key: string]: AnyInterfaceType;\n} & AnyFunctionReference;\nexport type AnyComponentReference = Record<string, AnyInterfaceType>;\n\nexport type AnyChildComponents = Record<string, AnyComponentReference>;\n\n/**\n * @internal\n */\nexport function currentSystemUdfInComponent(\n componentId: string,\n): AnyComponentReference {\n return {\n [toReferencePath]: `_reference/currentSystemUdfInComponent/${componentId}`,\n };\n}\n\nfunction createChildComponents(\n root: string,\n pathParts: string[],\n): AnyChildComponents {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createChildComponents(root, newParts);\n } else if (prop === toReferencePath) {\n if (pathParts.length < 1) {\n const found = [root, ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`${root}.childComponent.functionName\\`. Found: \\`${found}\\``,\n );\n }\n return `_reference/childComponent/` + pathParts.join(\"/\");\n } else {\n return undefined;\n }\n },\n };\n return new Proxy({}, handler);\n}\n\nexport const componentsGeneric = () => createChildComponents(\"components\", []);\n\nexport type AnyComponents = AnyChildComponents;\n"],
5
+ "mappings": ";;;;;;;;;;;;;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O,MAAM,oBAAoB,MAAM,sBAAsB,cAAc,CAAC,CAAC;",
6
6
  "names": ["import_paths", "name"]
7
7
  }
@@ -51,9 +51,9 @@ 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) => runUdf("query", reference, args2),
55
- runSnapshotQuery: (reference, args2) => runUdf("snapshotQuery", reference, args2),
56
- runMutation: (reference, args2) => runUdf("mutation", reference, args2)
54
+ runQuery: (reference, args2, options) => runUdf("query", reference, args2, options?.transactionLimits),
55
+ runSnapshotQuery: (reference, args2, options) => runUdf("snapshotQuery", reference, args2, options?.transactionLimits),
56
+ runMutation: (reference, args2, options) => runUdf("mutation", reference, args2, options?.transactionLimits)
57
57
  };
58
58
  const result = await invokeFunction(func, mutationCtx, args);
59
59
  validateReturnValue(result);
@@ -167,7 +167,7 @@ async function invokeQuery(func, argsStr, visibility) {
167
167
  auth: (0, import_authentication_impl.setupAuth)(requestId),
168
168
  storage: (0, import_storage_impl.setupStorageReader)(requestId),
169
169
  meta: (0, import_meta_impl.setupQueryMeta)(visibility),
170
- runQuery: (reference, args2) => runUdf("query", reference, args2)
170
+ runQuery: (reference, args2, options) => runUdf("query", reference, args2, options?.transactionLimits)
171
171
  };
172
172
  const result = await invokeFunction(func, queryCtx, args);
173
173
  validateReturnValue(result);
@@ -258,13 +258,16 @@ const httpActionGeneric = (func) => {
258
258
  q._handler = func;
259
259
  return q;
260
260
  };
261
- async function runUdf(udfType, f, args) {
261
+ async function runUdf(udfType, f, args, transactionLimits) {
262
262
  const queryArgs = (0, import_common.parseArgs)(args);
263
263
  const syscallArgs = {
264
264
  udfType,
265
265
  args: (0, import_values.convexToJson)(queryArgs),
266
266
  ...(0, import_paths.getFunctionAddress)(f)
267
267
  };
268
+ if (transactionLimits) {
269
+ syscallArgs.transactionLimits = transactionLimits;
270
+ }
268
271
  const result = await (0, import_syscall.performAsyncSyscall)("1.0/runUdf", syscallArgs);
269
272
  return (0, import_values.jsonToConvex)(result);
270
273
  }