convex 1.45.0 → 1.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -6
- package/dist/browser.bundle.js +1 -1
- package/dist/browser.bundle.js.map +2 -2
- package/dist/cjs/browser/http_client.js.map +2 -2
- package/dist/cjs/browser/query_options.js.map +2 -2
- package/dist/cjs/browser/simple_client.js.map +2 -2
- package/dist/cjs/browser/sync/optimistic_updates.js.map +1 -1
- package/dist/cjs/browser/sync/optimistic_updates_impl.js.map +2 -2
- package/dist/cjs/cli/codegen.js +2 -0
- package/dist/cjs/cli/codegen.js.map +2 -2
- package/dist/cjs/cli/deploy.js +1 -0
- package/dist/cjs/cli/deploy.js.map +2 -2
- package/dist/cjs/cli/docs.js +3 -36
- package/dist/cjs/cli/docs.js.map +2 -2
- package/dist/cjs/cli/lib/checkForLargeIndexDeletion.js +101 -60
- package/dist/cjs/cli/lib/checkForLargeIndexDeletion.js.map +2 -2
- package/dist/cjs/cli/lib/checkForSlowSchemaValidation.js +107 -0
- package/dist/cjs/cli/lib/checkForSlowSchemaValidation.js.map +7 -0
- package/dist/cjs/cli/lib/codegen.js.map +2 -2
- package/dist/cjs/cli/lib/components.js +12 -0
- package/dist/cjs/cli/lib/components.js.map +2 -2
- package/dist/cjs/cli/lib/deploy2.js +29 -2
- package/dist/cjs/cli/lib/deploy2.js.map +2 -2
- package/dist/cjs/cli/lib/deployApi/evaluateSchema.js +73 -0
- package/dist/cjs/cli/lib/deployApi/evaluateSchema.js.map +7 -0
- package/dist/cjs/cli/lib/deployApi/finishPush.js +1 -0
- package/dist/cjs/cli/lib/deployApi/finishPush.js.map +2 -2
- package/dist/cjs/cli/lib/deployApi/startPush.js +1 -1
- package/dist/cjs/cli/lib/deployApi/startPush.js.map +2 -2
- package/dist/cjs/cli/lib/dev.js +1 -0
- package/dist/cjs/cli/lib/dev.js.map +2 -2
- package/dist/cjs/cli/lib/generatedFunctionLogsApi.js.map +1 -1
- package/dist/cjs/cli/lib/localDeployment/run.js +30 -1
- package/dist/cjs/cli/lib/localDeployment/run.js.map +2 -2
- package/dist/cjs/cli/lib/localDeployment/upgrade.js +6 -5
- package/dist/cjs/cli/lib/localDeployment/upgrade.js.map +2 -2
- package/dist/cjs/cli/lib/localDeployment/utils.js +5 -1
- package/dist/cjs/cli/lib/localDeployment/utils.js.map +2 -2
- package/dist/cjs/cli/lib/run.js +1 -0
- package/dist/cjs/cli/lib/run.js.map +2 -2
- package/dist/cjs/cli/lib/utils/utils.js +36 -29
- package/dist/cjs/cli/lib/utils/utils.js.map +2 -2
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/nextjs/index.js.map +2 -2
- package/dist/cjs/react/client.js.map +2 -2
- package/dist/cjs/react/hydration.js.map +2 -2
- package/dist/cjs/react/queries_observer.js.map +2 -2
- package/dist/cjs/react/use_paginated_query2.js.map +2 -2
- package/dist/cjs/react/use_queries.js.map +2 -2
- package/dist/cjs/server/api.js.map +2 -2
- package/dist/cjs/server/components/index.js.map +2 -2
- package/dist/cjs/server/cron.js +10 -10
- package/dist/cjs/server/cron.js.map +2 -2
- package/dist/cjs/server/impl/actions_impl.js.map +2 -2
- package/dist/cjs/server/impl/meta_impl.js +8 -2
- package/dist/cjs/server/impl/meta_impl.js.map +2 -2
- package/dist/cjs/server/impl/scheduler_impl.js.map +2 -2
- package/dist/cjs/server/index.js.map +2 -2
- package/dist/cjs/server/meta.js.map +1 -1
- package/dist/cjs/server/registration.js.map +1 -1
- package/dist/cjs/server/scheduler.js.map +1 -1
- package/dist/cjs/server/schema.js +50 -3
- package/dist/cjs/server/schema.js.map +2 -2
- package/dist/cjs/values/validator.js +1 -1
- package/dist/cjs/values/validator.js.map +2 -2
- package/dist/cjs/values/validators.js +81 -25
- package/dist/cjs/values/validators.js.map +2 -2
- package/dist/cjs-types/browser/http_client.d.ts +5 -5
- package/dist/cjs-types/browser/http_client.d.ts.map +1 -1
- package/dist/cjs-types/browser/query_options.d.ts +2 -2
- package/dist/cjs-types/browser/query_options.d.ts.map +1 -1
- package/dist/cjs-types/browser/simple_client.d.ts +6 -6
- package/dist/cjs-types/browser/simple_client.d.ts.map +1 -1
- package/dist/cjs-types/browser/sync/optimistic_updates.d.ts +4 -4
- package/dist/cjs-types/browser/sync/optimistic_updates.d.ts.map +1 -1
- package/dist/cjs-types/browser/sync/optimistic_updates_impl.d.ts.map +1 -1
- package/dist/cjs-types/cli/codegen.d.ts.map +1 -1
- package/dist/cjs-types/cli/docs.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/checkForLargeIndexDeletion.d.ts +26 -5
- package/dist/cjs-types/cli/lib/checkForLargeIndexDeletion.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/checkForSlowSchemaValidation.d.ts +14 -0
- package/dist/cjs-types/cli/lib/checkForSlowSchemaValidation.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/codegen.d.ts +1 -0
- package/dist/cjs-types/cli/lib/codegen.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/components.d.ts +1 -0
- package/dist/cjs-types/cli/lib/components.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deploy2.d.ts +6 -0
- package/dist/cjs-types/cli/lib/deploy2.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/deployApi/evaluateSchema.d.ts +453 -0
- package/dist/cjs-types/cli/lib/deployApi/evaluateSchema.d.ts.map +1 -0
- package/dist/cjs-types/cli/lib/deployApi/finishPush.d.ts +1 -2
- package/dist/cjs-types/cli/lib/deployApi/finishPush.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/dev.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/generatedFunctionLogsApi.d.ts +2 -0
- package/dist/cjs-types/cli/lib/generatedFunctionLogsApi.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/localDeployment/run.d.ts +2 -0
- package/dist/cjs-types/cli/lib/localDeployment/run.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/localDeployment/upgrade.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/localDeployment/utils.d.ts +1 -0
- package/dist/cjs-types/cli/lib/localDeployment/utils.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/run.d.ts.map +1 -1
- package/dist/cjs-types/cli/lib/utils/utils.d.ts +5 -5
- package/dist/cjs-types/cli/lib/utils/utils.d.ts.map +1 -1
- package/dist/cjs-types/index.d.ts +1 -1
- package/dist/cjs-types/nextjs/index.d.ts +6 -6
- package/dist/cjs-types/nextjs/index.d.ts.map +1 -1
- package/dist/cjs-types/react/client.d.ts +15 -15
- package/dist/cjs-types/react/client.d.ts.map +1 -1
- package/dist/cjs-types/react/hydration.d.ts +3 -3
- package/dist/cjs-types/react/hydration.d.ts.map +1 -1
- package/dist/cjs-types/react/queries_observer.d.ts +9 -9
- package/dist/cjs-types/react/queries_observer.d.ts.map +1 -1
- package/dist/cjs-types/react/use_paginated_query2.d.ts.map +1 -1
- package/dist/cjs-types/react/use_queries.d.ts +14 -6
- package/dist/cjs-types/react/use_queries.d.ts.map +1 -1
- package/dist/cjs-types/server/api.d.ts +157 -7
- package/dist/cjs-types/server/api.d.ts.map +1 -1
- package/dist/cjs-types/server/components/index.d.ts +2 -2
- package/dist/cjs-types/server/components/index.d.ts.map +1 -1
- package/dist/cjs-types/server/cron.d.ts +21 -20
- package/dist/cjs-types/server/cron.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/actions_impl.d.ts +4 -4
- package/dist/cjs-types/server/impl/actions_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/meta_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/impl/scheduler_impl.d.ts.map +1 -1
- package/dist/cjs-types/server/index.d.ts +1 -1
- package/dist/cjs-types/server/index.d.ts.map +1 -1
- package/dist/cjs-types/server/meta.d.ts.map +1 -1
- package/dist/cjs-types/server/registration.d.ts +7 -7
- package/dist/cjs-types/server/registration.d.ts.map +1 -1
- package/dist/cjs-types/server/scheduler.d.ts +9 -7
- package/dist/cjs-types/server/scheduler.d.ts.map +1 -1
- package/dist/cjs-types/server/schema.d.ts +1 -0
- package/dist/cjs-types/server/schema.d.ts.map +1 -1
- package/dist/cjs-types/values/validator.d.ts.map +1 -1
- package/dist/cjs-types/values/validators.d.ts +30 -0
- package/dist/cjs-types/values/validators.d.ts.map +1 -1
- package/dist/cli.bundle.cjs +347 -133
- package/dist/cli.bundle.cjs.map +4 -4
- package/dist/esm/browser/http_client.js.map +2 -2
- package/dist/esm/browser/query_options.js.map +2 -2
- package/dist/esm/browser/simple_client.js.map +2 -2
- package/dist/esm/browser/sync/optimistic_updates_impl.js.map +2 -2
- package/dist/esm/cli/codegen.js +2 -0
- package/dist/esm/cli/codegen.js.map +2 -2
- package/dist/esm/cli/deploy.js +1 -0
- package/dist/esm/cli/deploy.js.map +2 -2
- package/dist/esm/cli/docs.js +3 -43
- package/dist/esm/cli/docs.js.map +2 -2
- package/dist/esm/cli/lib/checkForLargeIndexDeletion.js +100 -60
- package/dist/esm/cli/lib/checkForLargeIndexDeletion.js.map +2 -2
- package/dist/esm/cli/lib/checkForSlowSchemaValidation.js +85 -0
- package/dist/esm/cli/lib/checkForSlowSchemaValidation.js.map +7 -0
- package/dist/esm/cli/lib/codegen.js.map +2 -2
- package/dist/esm/cli/lib/components.js +12 -0
- package/dist/esm/cli/lib/components.js.map +2 -2
- package/dist/esm/cli/lib/deploy2.js +30 -2
- package/dist/esm/cli/lib/deploy2.js.map +2 -2
- package/dist/esm/cli/lib/deployApi/evaluateSchema.js +46 -0
- package/dist/esm/cli/lib/deployApi/evaluateSchema.js.map +7 -0
- package/dist/esm/cli/lib/deployApi/finishPush.js +1 -1
- package/dist/esm/cli/lib/deployApi/finishPush.js.map +2 -2
- package/dist/esm/cli/lib/deployApi/startPush.js +1 -1
- package/dist/esm/cli/lib/deployApi/startPush.js.map +2 -2
- package/dist/esm/cli/lib/dev.js +1 -0
- package/dist/esm/cli/lib/dev.js.map +2 -2
- package/dist/esm/cli/lib/localDeployment/run.js +30 -2
- package/dist/esm/cli/lib/localDeployment/run.js.map +2 -2
- package/dist/esm/cli/lib/localDeployment/upgrade.js +4 -3
- package/dist/esm/cli/lib/localDeployment/upgrade.js.map +2 -2
- package/dist/esm/cli/lib/localDeployment/utils.js +3 -0
- package/dist/esm/cli/lib/localDeployment/utils.js.map +2 -2
- package/dist/esm/cli/lib/run.js +1 -0
- package/dist/esm/cli/lib/run.js.map +2 -2
- package/dist/esm/cli/lib/utils/utils.js +36 -30
- package/dist/esm/cli/lib/utils/utils.js.map +2 -2
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/nextjs/index.js.map +2 -2
- package/dist/esm/react/client.js.map +2 -2
- package/dist/esm/react/hydration.js +3 -1
- package/dist/esm/react/hydration.js.map +2 -2
- package/dist/esm/react/queries_observer.js +3 -1
- package/dist/esm/react/queries_observer.js.map +2 -2
- package/dist/esm/react/use_paginated_query2.js +3 -1
- package/dist/esm/react/use_paginated_query2.js.map +2 -2
- package/dist/esm/react/use_queries.js.map +2 -2
- package/dist/esm/server/api.js.map +2 -2
- package/dist/esm/server/components/index.js.map +2 -2
- package/dist/esm/server/cron.js +13 -11
- package/dist/esm/server/cron.js.map +2 -2
- package/dist/esm/server/impl/actions_impl.js.map +2 -2
- package/dist/esm/server/impl/meta_impl.js +9 -3
- package/dist/esm/server/impl/meta_impl.js.map +2 -2
- package/dist/esm/server/impl/scheduler_impl.js.map +2 -2
- package/dist/esm/server/index.js.map +2 -2
- package/dist/esm/server/schema.js +50 -3
- package/dist/esm/server/schema.js.map +2 -2
- package/dist/esm/values/validator.js +1 -1
- package/dist/esm/values/validator.js.map +2 -2
- package/dist/esm/values/validators.js +81 -25
- package/dist/esm/values/validators.js.map +2 -2
- package/dist/esm-types/browser/http_client.d.ts +5 -5
- package/dist/esm-types/browser/http_client.d.ts.map +1 -1
- package/dist/esm-types/browser/query_options.d.ts +2 -2
- package/dist/esm-types/browser/query_options.d.ts.map +1 -1
- package/dist/esm-types/browser/simple_client.d.ts +6 -6
- package/dist/esm-types/browser/simple_client.d.ts.map +1 -1
- package/dist/esm-types/browser/sync/optimistic_updates.d.ts +4 -4
- package/dist/esm-types/browser/sync/optimistic_updates.d.ts.map +1 -1
- package/dist/esm-types/browser/sync/optimistic_updates_impl.d.ts.map +1 -1
- package/dist/esm-types/cli/codegen.d.ts.map +1 -1
- package/dist/esm-types/cli/docs.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/checkForLargeIndexDeletion.d.ts +26 -5
- package/dist/esm-types/cli/lib/checkForLargeIndexDeletion.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/checkForSlowSchemaValidation.d.ts +14 -0
- package/dist/esm-types/cli/lib/checkForSlowSchemaValidation.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/codegen.d.ts +1 -0
- package/dist/esm-types/cli/lib/codegen.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/components.d.ts +1 -0
- package/dist/esm-types/cli/lib/components.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deploy2.d.ts +6 -0
- package/dist/esm-types/cli/lib/deploy2.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/deployApi/evaluateSchema.d.ts +453 -0
- package/dist/esm-types/cli/lib/deployApi/evaluateSchema.d.ts.map +1 -0
- package/dist/esm-types/cli/lib/deployApi/finishPush.d.ts +1 -2
- package/dist/esm-types/cli/lib/deployApi/finishPush.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/dev.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/generatedFunctionLogsApi.d.ts +2 -0
- package/dist/esm-types/cli/lib/generatedFunctionLogsApi.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/localDeployment/run.d.ts +2 -0
- package/dist/esm-types/cli/lib/localDeployment/run.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/localDeployment/upgrade.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/localDeployment/utils.d.ts +1 -0
- package/dist/esm-types/cli/lib/localDeployment/utils.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/run.d.ts.map +1 -1
- package/dist/esm-types/cli/lib/utils/utils.d.ts +5 -5
- package/dist/esm-types/cli/lib/utils/utils.d.ts.map +1 -1
- package/dist/esm-types/index.d.ts +1 -1
- package/dist/esm-types/nextjs/index.d.ts +6 -6
- package/dist/esm-types/nextjs/index.d.ts.map +1 -1
- package/dist/esm-types/react/client.d.ts +15 -15
- package/dist/esm-types/react/client.d.ts.map +1 -1
- package/dist/esm-types/react/hydration.d.ts +3 -3
- package/dist/esm-types/react/hydration.d.ts.map +1 -1
- package/dist/esm-types/react/queries_observer.d.ts +9 -9
- package/dist/esm-types/react/queries_observer.d.ts.map +1 -1
- package/dist/esm-types/react/use_paginated_query2.d.ts.map +1 -1
- package/dist/esm-types/react/use_queries.d.ts +14 -6
- package/dist/esm-types/react/use_queries.d.ts.map +1 -1
- package/dist/esm-types/server/api.d.ts +157 -7
- package/dist/esm-types/server/api.d.ts.map +1 -1
- package/dist/esm-types/server/components/index.d.ts +2 -2
- package/dist/esm-types/server/components/index.d.ts.map +1 -1
- package/dist/esm-types/server/cron.d.ts +21 -20
- package/dist/esm-types/server/cron.d.ts.map +1 -1
- package/dist/esm-types/server/impl/actions_impl.d.ts +4 -4
- package/dist/esm-types/server/impl/actions_impl.d.ts.map +1 -1
- package/dist/esm-types/server/impl/meta_impl.d.ts.map +1 -1
- package/dist/esm-types/server/impl/scheduler_impl.d.ts.map +1 -1
- package/dist/esm-types/server/index.d.ts +1 -1
- package/dist/esm-types/server/index.d.ts.map +1 -1
- package/dist/esm-types/server/meta.d.ts.map +1 -1
- package/dist/esm-types/server/registration.d.ts +7 -7
- package/dist/esm-types/server/registration.d.ts.map +1 -1
- package/dist/esm-types/server/scheduler.d.ts +9 -7
- package/dist/esm-types/server/scheduler.d.ts.map +1 -1
- package/dist/esm-types/server/schema.d.ts +1 -0
- package/dist/esm-types/server/schema.d.ts.map +1 -1
- package/dist/esm-types/values/validator.d.ts.map +1 -1
- package/dist/esm-types/values/validators.d.ts +30 -0
- package/dist/esm-types/values/validators.d.ts.map +1 -1
- package/dist/react.bundle.js +1 -1
- package/dist/react.bundle.js.map +2 -2
- package/package.json +5 -5
- package/src/browser/http_client.ts +43 -10
- package/src/browser/query_options.ts +11 -5
- package/src/browser/simple_client.ts +35 -14
- package/src/browser/sync/optimistic_updates.ts +17 -4
- package/src/browser/sync/optimistic_updates_impl.ts +17 -4
- package/src/cli/codegen.ts +1 -0
- package/src/cli/deploy.ts +1 -0
- package/src/cli/docs.ts +3 -44
- package/src/cli/lib/checkForLargeIndexDeletion.ts +154 -82
- package/src/cli/lib/checkForSlowSchemaValidation.ts +130 -0
- package/src/cli/lib/codegen.ts +1 -0
- package/src/cli/lib/components.ts +17 -0
- package/src/cli/lib/deploy2.ts +56 -1
- package/src/cli/lib/deployApi/evaluateSchema.ts +62 -0
- package/src/cli/lib/deployApi/finishPush.ts +1 -1
- package/src/cli/lib/deployApi/startPush.ts +1 -1
- package/src/cli/lib/dev.ts +1 -0
- package/src/cli/lib/generatedFunctionLogsApi.ts +2 -0
- package/src/cli/lib/localDeployment/run.ts +44 -2
- package/src/cli/lib/localDeployment/upgrade.ts +4 -6
- package/src/cli/lib/localDeployment/utils.ts +6 -0
- package/src/cli/lib/run.ts +1 -0
- package/src/cli/lib/utils/utils.ts +63 -35
- package/src/index.ts +1 -1
- package/src/nextjs/index.ts +19 -8
- package/src/react/client.ts +73 -30
- package/src/react/hydration.tsx +14 -6
- package/src/react/queries_observer.ts +19 -16
- package/src/react/use_paginated_query2.ts +10 -6
- package/src/react/use_queries.ts +23 -7
- package/src/server/api.ts +220 -14
- package/src/server/components/index.ts +4 -6
- package/src/server/cron.ts +34 -24
- package/src/server/impl/actions_impl.ts +13 -4
- package/src/server/impl/meta_impl.ts +8 -1
- package/src/server/impl/scheduler_impl.ts +13 -6
- package/src/server/index.ts +1 -0
- package/src/server/meta.ts +25 -0
- package/src/server/registration.ts +28 -7
- package/src/server/scheduler.ts +22 -7
- package/src/server/schema.ts +55 -0
- package/src/values/validator.ts +3 -1
- package/src/values/validators.ts +84 -26
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/browser/http_client.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n FunctionReference,\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n} from \"../server/api.js\";\nimport { parseArgs, validateDeploymentUrl } from \"../common/index.js\";\nimport { version } from \"../index.js\";\nimport {\n ConvexError,\n JSONValue,\n convexToJson,\n jsonToConvex,\n} from \"../values/index.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n logForFunction,\n Logger,\n} from \"./logging.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n UserIdentityAttributes,\n} from \"../server/index.js\";\n\nexport const STATUS_CODE_OK = 200;\nexport const STATUS_CODE_BAD_REQUEST = 400;\n// Special custom 5xx HTTP status code to mean that the UDF returned an error.\n//\n// Must match the constant of the same name in the backend.\nexport const STATUS_CODE_UDF_FAILED = 560;\n\n// Allow fetch to be shimmed in for Node.js < 18\nlet specifiedFetch: typeof globalThis.fetch | undefined = undefined;\nexport function setFetch(f: typeof globalThis.fetch) {\n specifiedFetch = f;\n}\n\nexport type HttpMutationOptions = {\n /**\n * Skip the default queue of mutations and run this immediately.\n *\n * This allows the same HttpConvexClient to be used to request multiple\n * mutations in parallel, something not possible with WebSocket-based clients.\n */\n skipQueue: boolean;\n};\n\n/**\n * A Convex client that runs queries and mutations over HTTP.\n *\n * This client is stateful (it has user credentials and queues mutations)\n * so take care to avoid sharing it between requests in a server.\n *\n * This is appropriate for server-side code (like Netlify Lambdas) or non-reactive\n * webapps.\n *\n * @public\n */\nexport class ConvexHttpClient {\n private readonly address: string;\n private auth: string | undefined;\n private adminAuth: string | undefined;\n private encodedTsPromise?: Promise<string>;\n private debug: boolean;\n private fetchOptions?: FetchOptions;\n private fetch?: typeof globalThis.fetch | undefined;\n private logger: Logger;\n private mutationQueue: Array<{\n mutation: FunctionReference<\"mutation\">;\n args: FunctionArgs<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }> = [];\n private isProcessingQueue: boolean = false;\n\n /**\n * Create a new {@link ConvexHttpClient}.\n *\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - An object of options.\n * - `skipConvexDeploymentUrlCheck` - Skip validating that the Convex deployment URL looks like\n * `https://happy-animal-123.convex.cloud` or localhost. This can be useful if running a self-hosted\n * Convex backend that uses a different URL.\n * - `logger` - A logger or a boolean. If not provided, logs to the console.\n * You can construct your own logger to customize logging to log elsewhere\n * or not log at all, or use `false` as a shorthand for a no-op logger.\n * A logger is an object with 4 methods: log(), warn(), error(), and logVerbose().\n * These methods can receive multiple arguments of any types, like console.log().\n * - `auth` - A JWT containing identity claims accessible in Convex functions.\n * This identity may expire so it may be necessary to call `setAuth()` later,\n * but for short-lived clients it's convenient to specify this value here.\n * - `fetch` - A custom fetch implementation to use for all HTTP requests made by this client.\n */\n constructor(\n address: string,\n options?: {\n skipConvexDeploymentUrlCheck?: boolean;\n logger?: Logger | boolean;\n auth?: string;\n fetch?: typeof globalThis.fetch;\n },\n ) {\n if (typeof options === \"boolean\") {\n throw new Error(\n \"skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.\",\n );\n }\n const opts = options ?? {};\n if (opts.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n this.logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: false });\n this.address = address;\n this.debug = true;\n this.auth = undefined;\n this.adminAuth = undefined;\n this.fetch = options?.fetch;\n if (options?.auth) {\n this.setAuth(options.auth);\n }\n }\n\n /**\n * Obtain the {@link ConvexHttpClient}'s URL to its backend.\n * @deprecated Use url, which returns the url without /api at the end.\n *\n * @returns The URL to the Convex backend, including the client's API version.\n */\n backendUrl(): string {\n return `${this.address}/api`;\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n *\n * Should be called whenever the token changes (i.e. due to expiration and refresh).\n *\n * @param value - JWT-encoded OpenID Connect identity token.\n */\n setAuth(value: string) {\n this.clearAuth();\n this.auth = value;\n }\n\n /**\n * Set admin auth token to allow calling internal queries, mutations, and actions\n * and acting as an identity.\n *\n * @internal\n */\n setAdminAuth(token: string, actingAsIdentity?: UserIdentityAttributes) {\n this.clearAuth();\n if (actingAsIdentity !== undefined) {\n // Encode the identity to a base64 string\n const bytes = new TextEncoder().encode(JSON.stringify(actingAsIdentity));\n const actingAsIdentityEncoded = btoa(String.fromCodePoint(...bytes));\n this.adminAuth = `${token}:${actingAsIdentityEncoded}`;\n } else {\n this.adminAuth = token;\n }\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.auth = undefined;\n this.adminAuth = undefined;\n }\n\n /**\n * Sets whether the result log lines should be printed on the console or not.\n *\n * @internal\n */\n setDebug(debug: boolean) {\n this.debug = debug;\n }\n\n /**\n * Used to customize the fetch behavior in some runtimes.\n *\n * @internal\n */\n setFetchOptions(fetchOptions: FetchOptions) {\n this.fetchOptions = fetchOptions;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Execute a Convex query function at the same timestamp as every other\n * consistent query execution run by this HTTP client.\n *\n * This doesn't make sense for long-lived ConvexHttpClients as Convex\n * backends can read a limited amount into the past: beyond 30 seconds\n * in the past may not be available.\n *\n * Create a new client to use a consistent time.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n *\n * @deprecated This API is experimental: it may change or disappear.\n */\n async consistentQuery<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n\n const timestampPromise = this.getTimestamp();\n return await this.queryInner(query, queryArgs, { timestampPromise });\n }\n\n private async getTimestamp() {\n if (this.encodedTsPromise) {\n return this.encodedTsPromise;\n }\n return (this.encodedTsPromise = this.getTimestampInner());\n }\n\n private async getTimestampInner() {\n const localFetch = this.fetch || specifiedFetch || fetch;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n const response = await localFetch(`${this.address}/api/query_ts`, {\n ...this.fetchOptions,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok) {\n throw new Error(await response.text());\n }\n const { ts } = (await response.json()) as { ts: string };\n return ts;\n }\n\n /**\n * Execute a Convex query function.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n async query<Query extends FunctionReference<\"query\">>(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n return await this.queryInner(query, queryArgs, {});\n }\n\n private async queryInner<Query extends FunctionReference<\"query\">>(\n query: Query,\n queryArgs: FunctionArgs<Query>,\n options: { timestampPromise?: Promise<string> },\n ): Promise<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n const args = [convexToJson(queryArgs)];\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n\n const timestamp = options.timestampPromise\n ? await options.timestampPromise\n : undefined;\n\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args,\n ...(timestamp ? { ts: timestamp } : {}),\n });\n const endpoint = timestamp\n ? `${this.address}/api/query_at_ts`\n : `${this.address}/api/query`;\n\n const response = await localFetch(endpoint, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"query\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async mutationInner<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n mutationArgs: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n const name = getFunctionName(mutation);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(mutationArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/mutation`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"mutation\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async processMutationQueue() {\n if (this.isProcessingQueue) {\n return;\n }\n\n this.isProcessingQueue = true;\n while (this.mutationQueue.length > 0) {\n const { mutation, args, resolve, reject } = this.mutationQueue.shift()!;\n try {\n const result = await this.mutationInner(mutation, args);\n resolve(result);\n } catch (error) {\n reject(error);\n }\n }\n this.isProcessingQueue = false;\n }\n\n private enqueueMutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n return new Promise((resolve, reject) => {\n this.mutationQueue.push({ mutation, args, resolve, reject });\n void this.processMutationQueue();\n });\n }\n\n /**\n * Execute a Convex mutation function. Mutations are queued by default.\n *\n * @param name - The name of the mutation.\n * @param args - The arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - An optional object containing\n * @returns A promise of the mutation's result.\n */\n async mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n ...args: ArgsAndOptions<Mutation, HttpMutationOptions>\n ): Promise<FunctionReturnType<Mutation>> {\n const [fnArgs, options] = args;\n const mutationArgs = parseArgs(fnArgs);\n const queued = !options?.skipQueue;\n\n if (queued) {\n return await this.enqueueMutation(mutation, mutationArgs);\n } else {\n return await this.mutationInner(mutation, mutationArgs);\n }\n }\n\n /**\n * Execute a Convex action function. Actions are not queued.\n *\n * @param name - The name of the action.\n * @param args - The arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n async action<Action extends FunctionReference<\"action\">>(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const actionArgs = parseArgs(args[0]);\n const name = getFunctionName(action);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(actionArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/action`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"action\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n /**\n * Execute a Convex function of an unknown type. These function calls are not queued.\n *\n * @param name - The name of the function.\n * @param args - The arguments object for the function. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the function's result.\n *\n * @internal\n */\n async function<\n AnyFunction extends FunctionReference<\"query\" | \"mutation\" | \"action\">,\n >(\n anyFunction: AnyFunction | string,\n componentPath?: string,\n ...args: OptionalRestArgs<AnyFunction>\n ): Promise<FunctionReturnType<AnyFunction>> {\n const functionArgs = parseArgs(args[0]);\n const name =\n typeof anyFunction === \"string\"\n ? anyFunction\n : getFunctionName(anyFunction);\n const body = JSON.stringify({\n componentPath: componentPath,\n path: name,\n format: \"convex_encoded_json\",\n args: convexToJson(functionArgs),\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/function`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"any\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n}\n\nfunction forwardErrorData(errorData: JSONValue, error: ConvexError<string>) {\n (error as ConvexError<any>).data = jsonToConvex(errorData);\n return error;\n}\n\n/**\n * @internal\n */\ntype FetchOptions = { cache: \"force-cache\" | \"no-store\" };\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["import {\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n FunctionReference,\n FunctionReference_future,\n} from \"../server/api.js\";\nimport { parseArgs, validateDeploymentUrl } from \"../common/index.js\";\nimport { version } from \"../index.js\";\nimport {\n ConvexError,\n JSONValue,\n convexToJson,\n jsonToConvex,\n} from \"../values/index.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n logForFunction,\n Logger,\n} from \"./logging.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n UserIdentityAttributes,\n} from \"../server/index.js\";\n\nexport const STATUS_CODE_OK = 200;\nexport const STATUS_CODE_BAD_REQUEST = 400;\n// Special custom 5xx HTTP status code to mean that the UDF returned an error.\n//\n// Must match the constant of the same name in the backend.\nexport const STATUS_CODE_UDF_FAILED = 560;\n\n// Allow fetch to be shimmed in for Node.js < 18\nlet specifiedFetch: typeof globalThis.fetch | undefined = undefined;\nexport function setFetch(f: typeof globalThis.fetch) {\n specifiedFetch = f;\n}\n\nexport type HttpMutationOptions = {\n /**\n * Skip the default queue of mutations and run this immediately.\n *\n * This allows the same HttpConvexClient to be used to request multiple\n * mutations in parallel, something not possible with WebSocket-based clients.\n */\n skipQueue: boolean;\n};\n\n/**\n * A Convex client that runs queries and mutations over HTTP.\n *\n * This client is stateful (it has user credentials and queues mutations)\n * so take care to avoid sharing it between requests in a server.\n *\n * This is appropriate for server-side code (like Netlify Lambdas) or non-reactive\n * webapps.\n *\n * @public\n */\nexport class ConvexHttpClient {\n private readonly address: string;\n private auth: string | undefined;\n private adminAuth: string | undefined;\n private encodedTsPromise?: Promise<string>;\n private debug: boolean;\n private fetchOptions?: FetchOptions;\n private fetch?: typeof globalThis.fetch | undefined;\n private logger: Logger;\n private mutationQueue: Array<{\n mutation:\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">;\n args: FunctionArgs<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }> = [];\n private isProcessingQueue: boolean = false;\n\n /**\n * Create a new {@link ConvexHttpClient}.\n *\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - An object of options.\n * - `skipConvexDeploymentUrlCheck` - Skip validating that the Convex deployment URL looks like\n * `https://happy-animal-123.convex.cloud` or localhost. This can be useful if running a self-hosted\n * Convex backend that uses a different URL.\n * - `logger` - A logger or a boolean. If not provided, logs to the console.\n * You can construct your own logger to customize logging to log elsewhere\n * or not log at all, or use `false` as a shorthand for a no-op logger.\n * A logger is an object with 4 methods: log(), warn(), error(), and logVerbose().\n * These methods can receive multiple arguments of any types, like console.log().\n * - `auth` - A JWT containing identity claims accessible in Convex functions.\n * This identity may expire so it may be necessary to call `setAuth()` later,\n * but for short-lived clients it's convenient to specify this value here.\n * - `fetch` - A custom fetch implementation to use for all HTTP requests made by this client.\n */\n constructor(\n address: string,\n options?: {\n skipConvexDeploymentUrlCheck?: boolean;\n logger?: Logger | boolean;\n auth?: string;\n fetch?: typeof globalThis.fetch;\n },\n ) {\n if (typeof options === \"boolean\") {\n throw new Error(\n \"skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.\",\n );\n }\n const opts = options ?? {};\n if (opts.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n this.logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: false });\n this.address = address;\n this.debug = true;\n this.auth = undefined;\n this.adminAuth = undefined;\n this.fetch = options?.fetch;\n if (options?.auth) {\n this.setAuth(options.auth);\n }\n }\n\n /**\n * Obtain the {@link ConvexHttpClient}'s URL to its backend.\n * @deprecated Use url, which returns the url without /api at the end.\n *\n * @returns The URL to the Convex backend, including the client's API version.\n */\n backendUrl(): string {\n return `${this.address}/api`;\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n *\n * Should be called whenever the token changes (i.e. due to expiration and refresh).\n *\n * @param value - JWT-encoded OpenID Connect identity token.\n */\n setAuth(value: string) {\n this.clearAuth();\n this.auth = value;\n }\n\n /**\n * Set admin auth token to allow calling internal queries, mutations, and actions\n * and acting as an identity.\n *\n * @internal\n */\n setAdminAuth(token: string, actingAsIdentity?: UserIdentityAttributes) {\n this.clearAuth();\n if (actingAsIdentity !== undefined) {\n // Encode the identity to a base64 string\n const bytes = new TextEncoder().encode(JSON.stringify(actingAsIdentity));\n const actingAsIdentityEncoded = btoa(String.fromCodePoint(...bytes));\n this.adminAuth = `${token}:${actingAsIdentityEncoded}`;\n } else {\n this.adminAuth = token;\n }\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.auth = undefined;\n this.adminAuth = undefined;\n }\n\n /**\n * Sets whether the result log lines should be printed on the console or not.\n *\n * @internal\n */\n setDebug(debug: boolean) {\n this.debug = debug;\n }\n\n /**\n * Used to customize the fetch behavior in some runtimes.\n *\n * @internal\n */\n setFetchOptions(fetchOptions: FetchOptions) {\n this.fetchOptions = fetchOptions;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Execute a Convex query function at the same timestamp as every other\n * consistent query execution run by this HTTP client.\n *\n * This doesn't make sense for long-lived ConvexHttpClients as Convex\n * backends can read a limited amount into the past: beyond 30 seconds\n * in the past may not be available.\n *\n * Create a new client to use a consistent time.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n *\n * @deprecated This API is experimental: it may change or disappear.\n */\n async consistentQuery<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n\n const timestampPromise = this.getTimestamp();\n return await this.queryInner(query, queryArgs, { timestampPromise });\n }\n\n private async getTimestamp() {\n if (this.encodedTsPromise) {\n return this.encodedTsPromise;\n }\n return (this.encodedTsPromise = this.getTimestampInner());\n }\n\n private async getTimestampInner() {\n const localFetch = this.fetch || specifiedFetch || fetch;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n const response = await localFetch(`${this.address}/api/query_ts`, {\n ...this.fetchOptions,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok) {\n throw new Error(await response.text());\n }\n const { ts } = (await response.json()) as { ts: string };\n return ts;\n }\n\n /**\n * Execute a Convex query function.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n async query<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n return await this.queryInner(query, queryArgs, {});\n }\n\n private async queryInner<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n queryArgs: FunctionArgs<Query>,\n options: { timestampPromise?: Promise<string> },\n ): Promise<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n const args = [convexToJson(queryArgs)];\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n\n const timestamp = options.timestampPromise\n ? await options.timestampPromise\n : undefined;\n\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args,\n ...(timestamp ? { ts: timestamp } : {}),\n });\n const endpoint = timestamp\n ? `${this.address}/api/query_at_ts`\n : `${this.address}/api/query`;\n\n const response = await localFetch(endpoint, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"query\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async mutationInner<\n Mutation extends\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">,\n >(\n mutation: Mutation,\n mutationArgs: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n const name = getFunctionName(mutation);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(mutationArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/mutation`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"mutation\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async processMutationQueue() {\n if (this.isProcessingQueue) {\n return;\n }\n\n this.isProcessingQueue = true;\n while (this.mutationQueue.length > 0) {\n const { mutation, args, resolve, reject } = this.mutationQueue.shift()!;\n try {\n const result = await this.mutationInner(mutation, args);\n resolve(result);\n } catch (error) {\n reject(error);\n }\n }\n this.isProcessingQueue = false;\n }\n\n private enqueueMutation<\n Mutation extends\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">,\n >(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n return new Promise((resolve, reject) => {\n this.mutationQueue.push({ mutation, args, resolve, reject });\n void this.processMutationQueue();\n });\n }\n\n /**\n * Execute a Convex mutation function. Mutations are queued by default.\n *\n * @param name - The name of the mutation.\n * @param args - The arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - An optional object containing\n * @returns A promise of the mutation's result.\n */\n async mutation<\n Mutation extends\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">,\n >(\n mutation: Mutation,\n ...args: ArgsAndOptions<Mutation, HttpMutationOptions>\n ): Promise<FunctionReturnType<Mutation>> {\n const [fnArgs, options] = args;\n const mutationArgs = parseArgs(fnArgs);\n const queued = !options?.skipQueue;\n\n if (queued) {\n return await this.enqueueMutation(mutation, mutationArgs);\n } else {\n return await this.mutationInner(mutation, mutationArgs);\n }\n }\n\n /**\n * Execute a Convex action function. Actions are not queued.\n *\n * @param name - The name of the action.\n * @param args - The arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n async action<\n Action extends\n | FunctionReference<\"action\">\n | FunctionReference_future<\"action\">,\n >(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const actionArgs = parseArgs(args[0]);\n const name = getFunctionName(action);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(actionArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/action`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"action\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n /**\n * Execute a Convex function of an unknown type. These function calls are not queued.\n *\n * @param name - The name of the function.\n * @param args - The arguments object for the function. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the function's result.\n *\n * @internal\n */\n async function<\n AnyFunction extends\n | FunctionReference<\"query\" | \"mutation\" | \"action\">\n | FunctionReference_future<\"query\" | \"mutation\" | \"action\">,\n >(\n anyFunction: AnyFunction | string,\n componentPath?: string,\n ...args: OptionalRestArgs<AnyFunction>\n ): Promise<FunctionReturnType<AnyFunction>> {\n const functionArgs = parseArgs(args[0]);\n const name =\n typeof anyFunction === \"string\"\n ? anyFunction\n : getFunctionName(anyFunction);\n const body = JSON.stringify({\n componentPath: componentPath,\n path: name,\n format: \"convex_encoded_json\",\n args: convexToJson(functionArgs),\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/function`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"any\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n}\n\nfunction forwardErrorData(errorData: JSONValue, error: ConvexError<string>) {\n (error as ConvexError<any>).data = jsonToConvex(errorData);\n return error;\n}\n\n/**\n * @internal\n */\ntype FetchOptions = { cache: \"force-cache\" | \"no-store\" };\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAMO;AACP,oBAAiD;AACjD,eAAwB;AACxB,oBAKO;AACP,qBAKO;AAOA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAIhC,MAAM,yBAAyB;AAGtC,IAAI,iBAAsD;AACnD,SAAS,SAAS,GAA4B;AACnD,mBAAiB;AACnB;AAuBO,MAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsC5B,YACE,SACA,SAMA;AA7CF,wBAAiB;AACjB,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AACR,wBAAQ,iBAOH,CAAC;AACN,wBAAQ,qBAA6B;AA8BnC,QAAI,OAAO,YAAY,WAAW;AAChC,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,UAAM,OAAO,WAAW,CAAC;AACzB,QAAI,KAAK,iCAAiC,MAAM;AAC9C,+CAAsB,OAAO;AAAA,IAC/B;AACA,SAAK,SACH,SAAS,WAAW,YAChB,sCAAsB,EAAE,SAAS,MAAM,CAAC,IAC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 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/browser/query_options.ts"],
|
|
4
|
-
"sourcesContent": ["// Inspired by https://tanstack.com/query/v5/docs/framework/react/guides/query-options\nimport type {
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
4
|
+
"sourcesContent": ["// Inspired by https://tanstack.com/query/v5/docs/framework/react/guides/query-options\nimport type {\n FunctionArgs,\n FunctionReference,\n FunctionReference_future,\n} from \"../server/api.js\";\n\n/**\n * Options for a Convex query: the query function reference and its arguments.\n *\n * Used with the object-form overload of {@link useQuery}.\n *\n * @public\n */\nexport type QueryOptions<\n Query extends FunctionReference<\"query\"> | FunctionReference_future<\"query\">,\n> = {\n /**\n * The query function to run.\n */\n query: Query;\n /**\n * The arguments to the query function.\n */\n args: FunctionArgs<Query>;\n};\n\n/**\n * Creates a type-safe {@link QueryOptions} object for a Convex query.\n *\n * This is an identity function that exists to provide type inference \u2014 passing\n * your query and args through this helper ensures TypeScript infers the correct\n * `Query` type parameter, which enables precise return types on hooks like\n * {@link useQuery}.\n *\n * ```typescript\n * const opts = convexQueryOptions({\n * query: api.users.getById,\n * args: { id: userId },\n * });\n * // opts is typed as QueryOptions<typeof api.users.getById>\n * client.prewarmQuery(opts);\n * ```\n *\n * @param options - The query and its arguments.\n * @returns The same object, typed as `QueryOptions<Query>`.\n * @internal\n */\nexport function convexQueryOptions<\n Query extends FunctionReference<\"query\"> | FunctionReference_future<\"query\">,\n>(options: QueryOptions<Query>): QueryOptions<Query> {\n return options;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgDO,SAAS,mBAEd,SAAmD;AACnD,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/browser/simple_client.ts"],
|
|
4
|
-
"sourcesContent": ["import { validateDeploymentUrl } from \"../common/index.js\";\nimport {\n FunctionArgs,\n FunctionReference,\n FunctionReturnType,\n PaginationResult,\n} from \"../server/index.js\";\nimport { getFunctionName } from \"../server/api.js\";\nimport { AuthTokenFetcher } from \"./sync/authentication_manager.js\";\nimport {\n BaseConvexClient,\n BaseConvexClientOptions,\n ConnectionState,\n MutationOptions,\n} from \"./sync/client.js\";\nimport {\n ExtendedTransition,\n PaginatedQueryClient,\n} from \"./sync/paginated_query_client.js\";\nimport { PaginatedQueryResult } from \"./sync/pagination.js\";\nimport { UserIdentityAttributes } from \"./sync/protocol.js\";\nimport {\n PaginatedQueryToken,\n QueryToken,\n serializedQueryTokenIsPaginated,\n} from \"./sync/udf_path_utils.js\";\n\n// In Node.js builds this points to a bundled WebSocket implementation. If no\n// WebSocket implementation is manually specified or globally available,\n// this one is used.\nlet defaultWebSocketConstructor: typeof WebSocket | undefined;\n\n/** internal */\nexport function setDefaultWebSocketConstructor(ws: typeof WebSocket) {\n defaultWebSocketConstructor = ws;\n}\n\nexport type ConvexClientOptions = BaseConvexClientOptions & {\n /**\n * `disabled` makes onUpdate callback registration a no-op and actions,\n * mutations and one-shot queries throw. Setting disabled to true may be\n * useful for server-side rendering, where subscriptions don't make sense.\n */\n disabled?: boolean;\n /**\n * Whether to prompt users in browsers about queued or in-flight mutations.\n * This only works in environments where `window.onbeforeunload` is available.\n *\n * Defaults to true when `window` is defined, otherwise false.\n */\n unsavedChangesWarning?: boolean;\n};\n\n/**\n * Stops callbacks from running.\n *\n * @public\n */\nexport type Unsubscribe<T> = {\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n (): void;\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n unsubscribe(): void;\n /** Get the last known value, possibly with local optimistic updates applied. */\n getCurrentValue(): T | undefined;\n /** @internal */\n getQueryLogs(): string[] | undefined;\n};\n\n/**\n * Subscribes to Convex query functions and executes mutations and actions over a WebSocket.\n *\n * Optimistic updates for mutations are not provided for this client.\n * Third party clients may choose to wrap {@link browser.BaseConvexClient} for additional control.\n *\n * ```ts\n * const client = new ConvexClient(\"https://happy-otter-123.convex.cloud\");\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages[0].body);\n * });\n * ```\n *\n * @public\n */\nexport class ConvexClient {\n private listeners: Set<QueryInfo>;\n private _client: BaseConvexClient | undefined;\n private _paginatedClient: PaginatedQueryClient | undefined;\n // A synthetic server event to run callbacks the first time\n private callNewListenersWithCurrentValuesTimer:\n | ReturnType<typeof setTimeout>\n | undefined;\n private _closed: boolean;\n private _disabled: boolean;\n /**\n * Once closed no registered callbacks will fire again.\n */\n get closed(): boolean {\n return this._closed;\n }\n get client(): BaseConvexClient {\n if (this._client) return this._client;\n throw new Error(\"ConvexClient is disabled\");\n }\n /**\n * @internal\n */\n get paginatedClient(): PaginatedQueryClient {\n if (this._paginatedClient) return this._paginatedClient;\n throw new Error(\"ConvexClient is disabled\");\n }\n get disabled(): boolean {\n return this._disabled;\n }\n\n /**\n * Construct a client and immediately initiate a WebSocket connection to the passed address.\n *\n * @public\n */\n constructor(address: string, options: ConvexClientOptions = {}) {\n if (options.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n const { disabled, ...baseOptions } = options;\n this._closed = false;\n this._disabled = !!disabled;\n if (\n defaultWebSocketConstructor &&\n !(\"webSocketConstructor\" in baseOptions) &&\n typeof WebSocket === \"undefined\"\n ) {\n baseOptions.webSocketConstructor = defaultWebSocketConstructor;\n }\n if (\n typeof window === \"undefined\" &&\n !(\"unsavedChangesWarning\" in baseOptions)\n ) {\n baseOptions.unsavedChangesWarning = false;\n }\n if (!this.disabled) {\n this._client = new BaseConvexClient(\n address,\n () => {}, // NOP, let the paginated query client do it all\n baseOptions,\n );\n this._paginatedClient = new PaginatedQueryClient(\n this._client,\n (transition) => this._transition(transition),\n );\n }\n this.listeners = new Set();\n }\n\n /**\n * Call a callback whenever a new result for a query is received. The callback\n * will run soon after being registered if a result for the query is already\n * in memory.\n *\n * The return value is an {@link Unsubscribe} object which is both a function\n * an an object with properties. Both of the patterns below work with this object:\n *\n *```ts\n * // call the return value as a function\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n * unsubscribe();\n *\n * // unpack the return value into its properties\n * const {\n * getCurrentValue,\n * unsubscribe,\n * } = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n *```\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n * If not provided, errors will be thrown instead of calling the callback.\n *\n * @return an {@link Unsubscribe} function to stop calling the onUpdate function.\n */\n onUpdate<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: FunctionArgs<Query>,\n callback: (result: FunctionReturnType<Query>) => unknown,\n onError?: (e: Error) => unknown,\n ): Unsubscribe<Query[\"_returnType\"]> {\n if (this.disabled) {\n return this.createDisabledUnsubscribe<Query[\"_returnType\"]>();\n }\n\n // BaseConvexClient takes care of deduplicating queries subscriptions...\n const { queryToken, unsubscribe } = this.client.subscribe(\n getFunctionName(query),\n args,\n );\n\n // ...but we still need to bookkeep callbacks to actually call them.\n const queryInfo: QueryInfo = {\n queryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n paginationOptions: undefined,\n };\n this.listeners.add(queryInfo);\n\n // If the callback is registered for a query with a result immediately available\n // schedule a fake transition to call the callback soon instead of waiting for\n // a new server update (which could take seconds or days).\n if (\n this.queryResultReady(queryToken) &&\n this.callNewListenersWithCurrentValuesTimer === undefined\n ) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0,\n );\n }\n\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<Query[\"_returnType\"]>\n > = {\n unsubscribe: () => {\n if (this.closed) {\n // all unsubscribes already ran\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => this.client.localQueryResultByToken(queryToken),\n getQueryLogs: () => this.client.localQueryLogs(queryToken),\n };\n const ret = unsubscribeProps.unsubscribe as Unsubscribe<\n Query[\"_returnType\"]\n >;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n\n /**\n * Call a callback whenever a new result for a paginated query is received.\n *\n * This is an experimental preview: the final API may change.\n * In particular, caching behavior, page splitting, and required paginated query options\n * may change.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param options - Options for the paginated query including initialNumItems and id.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n *\n * @return an {@link Unsubscribe} function to stop calling the callback.\n */\n onPaginatedUpdate_experimental<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: FunctionArgs<Query>,\n options: { initialNumItems: number },\n callback: (result: PaginationResult<FunctionReturnType<Query>>) => unknown,\n onError?: (e: Error) => unknown,\n ): Unsubscribe<PaginatedQueryResult<FunctionReturnType<Query>[]>> {\n if (this.disabled) {\n return this.createDisabledUnsubscribe<\n PaginatedQueryResult<FunctionReturnType<Query>>\n >();\n }\n\n const paginationOptions = {\n initialNumItems: options.initialNumItems,\n id: -1,\n };\n\n const { paginatedQueryToken, unsubscribe } = this.paginatedClient.subscribe(\n getFunctionName(query),\n args,\n // Simple client doesn't use IDs, there's no expectation that these queries remain separate.\n paginationOptions,\n );\n\n const queryInfo: QueryInfo = {\n queryToken: paginatedQueryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n paginationOptions,\n };\n this.listeners.add(queryInfo);\n\n // If the callback is registered for a query with a result immediately available\n // schedule a fake transition to call the callback soon instead of waiting for\n // a new server update (which could take seconds or days).\n if (\n !!this.paginatedClient.localQueryResultByToken(paginatedQueryToken) &&\n this.callNewListenersWithCurrentValuesTimer === undefined\n ) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0,\n );\n }\n\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<PaginatedQueryResult<FunctionReturnType<Query>[]>>\n > = {\n unsubscribe: () => {\n if (this.closed) {\n // all unsubscribes already ran\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => {\n const result = this.paginatedClient.localQueryResult(\n getFunctionName(query),\n args,\n paginationOptions,\n );\n // cast to apply the specific function type\n return result as\n | PaginatedQueryResult<FunctionReturnType<Query>>\n | undefined;\n },\n getQueryLogs: () => [], // Paginated queries don't aggregate their logs\n };\n const ret = unsubscribeProps.unsubscribe as Unsubscribe<\n PaginatedQueryResult<FunctionReturnType<Query>>\n >;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n\n // Run all callbacks that have never been run before if they have a query\n // result available now.\n private callNewListenersWithCurrentValues() {\n this.callNewListenersWithCurrentValuesTimer = undefined;\n this._transition({ queries: [], paginatedQueries: [] }, true);\n }\n\n private queryResultReady(queryToken: QueryToken): boolean {\n return this.client.hasLocalQueryResultByToken(queryToken);\n }\n\n private createDisabledUnsubscribe<T>(): Unsubscribe<T> {\n const disabledUnsubscribe = (() => {}) as Unsubscribe<T>;\n const unsubscribeProps: RemoveCallSignature<Unsubscribe<T>> = {\n unsubscribe: disabledUnsubscribe,\n getCurrentValue: () => undefined,\n getQueryLogs: () => undefined,\n };\n Object.assign(disabledUnsubscribe, unsubscribeProps);\n return disabledUnsubscribe;\n }\n\n async close() {\n if (this.disabled) return;\n // prevent pending updates\n this.listeners.clear();\n this._closed = true;\n if (this._paginatedClient) {\n this._paginatedClient = undefined;\n }\n return this.client.close();\n }\n\n /**\n * Get the current JWT auth token and decoded claims.\n */\n getAuth(): { token: string; decoded: Record<string, any> } | undefined {\n if (this.disabled) return;\n return this.client.getCurrentAuthClaims();\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT (typically an OpenID Connect Identity Token)\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n ) {\n if (this.disabled) return;\n this.client.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n );\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n if (this.closed) {\n throw new Error(\"ConvexClient has already been closed.\");\n }\n if (this.disabled) return;\n this.client.setAdminAuth(token, identity);\n }\n\n /**\n * @internal\n */\n _transition(\n {\n queries,\n paginatedQueries,\n }: Pick<ExtendedTransition, \"queries\" | \"paginatedQueries\">,\n callNewListeners = false,\n ) {\n const updatedQueries = [\n ...queries.map((q) => q.token),\n ...paginatedQueries.map((q) => q.token),\n ];\n\n // Deduping subscriptions happens in the BaseConvexClient, so not much to do here.\n\n // Call all callbacks in the order they were registered\n for (const queryInfo of this.listeners) {\n const { callback, queryToken, onError, hasEverRun } = queryInfo;\n const isPaginatedQuery = serializedQueryTokenIsPaginated(queryToken);\n\n // What does it mean to have a paginated query result ready? I think it's\n // always going to fire immediately.\n const hasResultReady = isPaginatedQuery\n ? !!this.paginatedClient.localQueryResultByToken(queryToken)\n : this.client.hasLocalQueryResultByToken(queryToken);\n\n if (\n updatedQueries.includes(queryToken) ||\n (callNewListeners && !hasEverRun && hasResultReady)\n ) {\n queryInfo.hasEverRun = true;\n let newValue;\n try {\n if (isPaginatedQuery) {\n newValue = this.paginatedClient.localQueryResultByToken(queryToken);\n } else {\n newValue = this.client.localQueryResultByToken(queryToken);\n }\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n if (onError) {\n onError(\n error,\n \"Second argument to onUpdate onError is reserved for later use\",\n );\n } else {\n // Make some noise without unsubscribing or failing to call other callbacks.\n void Promise.reject(error);\n }\n continue;\n }\n callback(\n newValue,\n \"Second argument to onUpdate callback is reserved for later use\",\n );\n }\n }\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n async mutation<Mutation extends FunctionReference<\"mutation\">>(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n options?: MutationOptions,\n ): Promise<Awaited<FunctionReturnType<Mutation>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.mutation(getFunctionName(mutation), args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action.\n * @returns A promise of the action's result.\n */\n async action<Action extends FunctionReference<\"action\">>(\n action: Action,\n args: FunctionArgs<Action>,\n ): Promise<Awaited<FunctionReturnType<Action>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.action(getFunctionName(action), args);\n }\n\n /**\n * Fetch a query result once.\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query.\n * @returns A promise of the query's result.\n */\n async query<Query extends FunctionReference<\"query\">>(\n query: Query,\n args: Query[\"_args\"],\n ): Promise<Awaited<Query[\"_returnType\"]>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n const value = this.client.localQueryResult(getFunctionName(query), args) as\n | Awaited<Query[\"_returnType\"]>\n | undefined;\n if (value !== undefined) return Promise.resolve(value);\n\n return new Promise((resolve, reject) => {\n const { unsubscribe } = this.onUpdate(\n query,\n args,\n (value) => {\n unsubscribe();\n resolve(value);\n },\n (e: Error) => {\n unsubscribe();\n reject(e);\n },\n );\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return this.client.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n if (this.disabled) return () => {};\n return this.client.subscribeToConnectionState(cb);\n }\n}\n\n// internal information tracked about each registered callback\ntype QueryInfo = {\n callback: (result: any, meta: unknown) => unknown;\n onError: ((e: Error, meta: unknown) => unknown) | undefined;\n unsubscribe: () => void;\n queryToken: QueryToken | PaginatedQueryToken;\n hasEverRun: boolean;\n // query, args and paginationOptions are just here for debugging, the queryToken is authoritative\n query: FunctionReference<\"query\">;\n args: any;\n paginationOptions: { initialNumItems: number; id: number } | undefined;\n};\n\n// helps to construct objects with a call signature\ntype RemoveCallSignature<T> = Omit<T, never>;\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAsC;
|
|
4
|
+
"sourcesContent": ["import { validateDeploymentUrl } from \"../common/index.js\";\nimport {\n FunctionArgs,\n FunctionReturnType,\n PaginationResult,\n FunctionReference,\n FunctionReference_future,\n} from \"../server/index.js\";\nimport { getFunctionName } from \"../server/api.js\";\nimport { AuthTokenFetcher } from \"./sync/authentication_manager.js\";\nimport {\n BaseConvexClient,\n BaseConvexClientOptions,\n ConnectionState,\n MutationOptions,\n} from \"./sync/client.js\";\nimport {\n ExtendedTransition,\n PaginatedQueryClient,\n} from \"./sync/paginated_query_client.js\";\nimport { PaginatedQueryResult } from \"./sync/pagination.js\";\nimport { UserIdentityAttributes } from \"./sync/protocol.js\";\nimport {\n PaginatedQueryToken,\n QueryToken,\n serializedQueryTokenIsPaginated,\n} from \"./sync/udf_path_utils.js\";\n\n// In Node.js builds this points to a bundled WebSocket implementation. If no\n// WebSocket implementation is manually specified or globally available,\n// this one is used.\nlet defaultWebSocketConstructor: typeof WebSocket | undefined;\n\n/** internal */\nexport function setDefaultWebSocketConstructor(ws: typeof WebSocket) {\n defaultWebSocketConstructor = ws;\n}\n\nexport type ConvexClientOptions = BaseConvexClientOptions & {\n /**\n * `disabled` makes onUpdate callback registration a no-op and actions,\n * mutations and one-shot queries throw. Setting disabled to true may be\n * useful for server-side rendering, where subscriptions don't make sense.\n */\n disabled?: boolean;\n /**\n * Whether to prompt users in browsers about queued or in-flight mutations.\n * This only works in environments where `window.onbeforeunload` is available.\n *\n * Defaults to true when `window` is defined, otherwise false.\n */\n unsavedChangesWarning?: boolean;\n};\n\n/**\n * Stops callbacks from running.\n *\n * @public\n */\nexport type Unsubscribe<T> = {\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n (): void;\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n unsubscribe(): void;\n /** Get the last known value, possibly with local optimistic updates applied. */\n getCurrentValue(): T | undefined;\n /** @internal */\n getQueryLogs(): string[] | undefined;\n};\n\n/**\n * Subscribes to Convex query functions and executes mutations and actions over a WebSocket.\n *\n * Optimistic updates for mutations are not provided for this client.\n * Third party clients may choose to wrap {@link browser.BaseConvexClient} for additional control.\n *\n * ```ts\n * const client = new ConvexClient(\"https://happy-otter-123.convex.cloud\");\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages[0].body);\n * });\n * ```\n *\n * @public\n */\nexport class ConvexClient {\n private listeners: Set<QueryInfo>;\n private _client: BaseConvexClient | undefined;\n private _paginatedClient: PaginatedQueryClient | undefined;\n // A synthetic server event to run callbacks the first time\n private callNewListenersWithCurrentValuesTimer:\n | ReturnType<typeof setTimeout>\n | undefined;\n private _closed: boolean;\n private _disabled: boolean;\n /**\n * Once closed no registered callbacks will fire again.\n */\n get closed(): boolean {\n return this._closed;\n }\n get client(): BaseConvexClient {\n if (this._client) return this._client;\n throw new Error(\"ConvexClient is disabled\");\n }\n /**\n * @internal\n */\n get paginatedClient(): PaginatedQueryClient {\n if (this._paginatedClient) return this._paginatedClient;\n throw new Error(\"ConvexClient is disabled\");\n }\n get disabled(): boolean {\n return this._disabled;\n }\n\n /**\n * Construct a client and immediately initiate a WebSocket connection to the passed address.\n *\n * @public\n */\n constructor(address: string, options: ConvexClientOptions = {}) {\n if (options.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n const { disabled, ...baseOptions } = options;\n this._closed = false;\n this._disabled = !!disabled;\n if (\n defaultWebSocketConstructor &&\n !(\"webSocketConstructor\" in baseOptions) &&\n typeof WebSocket === \"undefined\"\n ) {\n baseOptions.webSocketConstructor = defaultWebSocketConstructor;\n }\n if (\n typeof window === \"undefined\" &&\n !(\"unsavedChangesWarning\" in baseOptions)\n ) {\n baseOptions.unsavedChangesWarning = false;\n }\n if (!this.disabled) {\n this._client = new BaseConvexClient(\n address,\n () => {}, // NOP, let the paginated query client do it all\n baseOptions,\n );\n this._paginatedClient = new PaginatedQueryClient(\n this._client,\n (transition) => this._transition(transition),\n );\n }\n this.listeners = new Set();\n }\n\n /**\n * Call a callback whenever a new result for a query is received. The callback\n * will run soon after being registered if a result for the query is already\n * in memory.\n *\n * The return value is an {@link Unsubscribe} object which is both a function\n * an an object with properties. Both of the patterns below work with this object:\n *\n *```ts\n * // call the return value as a function\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n * unsubscribe();\n *\n * // unpack the return value into its properties\n * const {\n * getCurrentValue,\n * unsubscribe,\n * } = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n *```\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n * If not provided, errors will be thrown instead of calling the callback.\n *\n * @return an {@link Unsubscribe} function to stop calling the onUpdate function.\n */\n onUpdate<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n args: FunctionArgs<Query>,\n callback: (result: FunctionReturnType<Query>) => unknown,\n onError?: (e: Error) => unknown,\n ): Unsubscribe<FunctionReturnType<Query>> {\n if (this.disabled) {\n return this.createDisabledUnsubscribe<FunctionReturnType<Query>>();\n }\n\n // BaseConvexClient takes care of deduplicating queries subscriptions...\n const { queryToken, unsubscribe } = this.client.subscribe(\n getFunctionName(query),\n args,\n );\n\n // ...but we still need to bookkeep callbacks to actually call them.\n const queryInfo: QueryInfo = {\n queryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n paginationOptions: undefined,\n };\n this.listeners.add(queryInfo);\n\n // If the callback is registered for a query with a result immediately available\n // schedule a fake transition to call the callback soon instead of waiting for\n // a new server update (which could take seconds or days).\n if (\n this.queryResultReady(queryToken) &&\n this.callNewListenersWithCurrentValuesTimer === undefined\n ) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0,\n );\n }\n\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<FunctionReturnType<Query>>\n > = {\n unsubscribe: () => {\n if (this.closed) {\n // all unsubscribes already ran\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => this.client.localQueryResultByToken(queryToken),\n getQueryLogs: () => this.client.localQueryLogs(queryToken),\n };\n const ret = unsubscribeProps.unsubscribe as Unsubscribe<\n FunctionReturnType<Query>\n >;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n\n /**\n * Call a callback whenever a new result for a paginated query is received.\n *\n * This is an experimental preview: the final API may change.\n * In particular, caching behavior, page splitting, and required paginated query options\n * may change.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param options - Options for the paginated query including initialNumItems and id.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n *\n * @return an {@link Unsubscribe} function to stop calling the callback.\n */\n onPaginatedUpdate_experimental<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n args: FunctionArgs<Query>,\n options: { initialNumItems: number },\n callback: (result: PaginationResult<FunctionReturnType<Query>>) => unknown,\n onError?: (e: Error) => unknown,\n ): Unsubscribe<PaginatedQueryResult<FunctionReturnType<Query>[]>> {\n if (this.disabled) {\n return this.createDisabledUnsubscribe<\n PaginatedQueryResult<FunctionReturnType<Query>>\n >();\n }\n\n const paginationOptions = {\n initialNumItems: options.initialNumItems,\n id: -1,\n };\n\n const { paginatedQueryToken, unsubscribe } = this.paginatedClient.subscribe(\n getFunctionName(query),\n args,\n // Simple client doesn't use IDs, there's no expectation that these queries remain separate.\n paginationOptions,\n );\n\n const queryInfo: QueryInfo = {\n queryToken: paginatedQueryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n paginationOptions,\n };\n this.listeners.add(queryInfo);\n\n // If the callback is registered for a query with a result immediately available\n // schedule a fake transition to call the callback soon instead of waiting for\n // a new server update (which could take seconds or days).\n if (\n !!this.paginatedClient.localQueryResultByToken(paginatedQueryToken) &&\n this.callNewListenersWithCurrentValuesTimer === undefined\n ) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0,\n );\n }\n\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<PaginatedQueryResult<FunctionReturnType<Query>[]>>\n > = {\n unsubscribe: () => {\n if (this.closed) {\n // all unsubscribes already ran\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => {\n const result = this.paginatedClient.localQueryResult(\n getFunctionName(query),\n args,\n paginationOptions,\n );\n // cast to apply the specific function type\n return result as\n | PaginatedQueryResult<FunctionReturnType<Query>>\n | undefined;\n },\n getQueryLogs: () => [], // Paginated queries don't aggregate their logs\n };\n const ret = unsubscribeProps.unsubscribe as Unsubscribe<\n PaginatedQueryResult<FunctionReturnType<Query>>\n >;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n\n // Run all callbacks that have never been run before if they have a query\n // result available now.\n private callNewListenersWithCurrentValues() {\n this.callNewListenersWithCurrentValuesTimer = undefined;\n this._transition({ queries: [], paginatedQueries: [] }, true);\n }\n\n private queryResultReady(queryToken: QueryToken): boolean {\n return this.client.hasLocalQueryResultByToken(queryToken);\n }\n\n private createDisabledUnsubscribe<T>(): Unsubscribe<T> {\n const disabledUnsubscribe = (() => {}) as Unsubscribe<T>;\n const unsubscribeProps: RemoveCallSignature<Unsubscribe<T>> = {\n unsubscribe: disabledUnsubscribe,\n getCurrentValue: () => undefined,\n getQueryLogs: () => undefined,\n };\n Object.assign(disabledUnsubscribe, unsubscribeProps);\n return disabledUnsubscribe;\n }\n\n async close() {\n if (this.disabled) return;\n // prevent pending updates\n this.listeners.clear();\n this._closed = true;\n if (this._paginatedClient) {\n this._paginatedClient = undefined;\n }\n return this.client.close();\n }\n\n /**\n * Get the current JWT auth token and decoded claims.\n */\n getAuth(): { token: string; decoded: Record<string, any> } | undefined {\n if (this.disabled) return;\n return this.client.getCurrentAuthClaims();\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT (typically an OpenID Connect Identity Token)\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n ) {\n if (this.disabled) return;\n this.client.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n );\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n if (this.closed) {\n throw new Error(\"ConvexClient has already been closed.\");\n }\n if (this.disabled) return;\n this.client.setAdminAuth(token, identity);\n }\n\n /**\n * @internal\n */\n _transition(\n {\n queries,\n paginatedQueries,\n }: Pick<ExtendedTransition, \"queries\" | \"paginatedQueries\">,\n callNewListeners = false,\n ) {\n const updatedQueries = [\n ...queries.map((q) => q.token),\n ...paginatedQueries.map((q) => q.token),\n ];\n\n // Deduping subscriptions happens in the BaseConvexClient, so not much to do here.\n\n // Call all callbacks in the order they were registered\n for (const queryInfo of this.listeners) {\n const { callback, queryToken, onError, hasEverRun } = queryInfo;\n const isPaginatedQuery = serializedQueryTokenIsPaginated(queryToken);\n\n // What does it mean to have a paginated query result ready? I think it's\n // always going to fire immediately.\n const hasResultReady = isPaginatedQuery\n ? !!this.paginatedClient.localQueryResultByToken(queryToken)\n : this.client.hasLocalQueryResultByToken(queryToken);\n\n if (\n updatedQueries.includes(queryToken) ||\n (callNewListeners && !hasEverRun && hasResultReady)\n ) {\n queryInfo.hasEverRun = true;\n let newValue;\n try {\n if (isPaginatedQuery) {\n newValue = this.paginatedClient.localQueryResultByToken(queryToken);\n } else {\n newValue = this.client.localQueryResultByToken(queryToken);\n }\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n if (onError) {\n onError(\n error,\n \"Second argument to onUpdate onError is reserved for later use\",\n );\n } else {\n // Make some noise without unsubscribing or failing to call other callbacks.\n void Promise.reject(error);\n }\n continue;\n }\n callback(\n newValue,\n \"Second argument to onUpdate callback is reserved for later use\",\n );\n }\n }\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n async mutation<\n Mutation extends\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">,\n >(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n options?: MutationOptions,\n ): Promise<Awaited<FunctionReturnType<Mutation>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.mutation(getFunctionName(mutation), args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action.\n * @returns A promise of the action's result.\n */\n async action<\n Action extends\n | FunctionReference<\"action\">\n | FunctionReference_future<\"action\">,\n >(\n action: Action,\n args: FunctionArgs<Action>,\n ): Promise<Awaited<FunctionReturnType<Action>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.action(getFunctionName(action), args);\n }\n\n /**\n * Fetch a query result once.\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query.\n * @returns A promise of the query's result.\n */\n async query<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n args: FunctionArgs<Query>,\n ): Promise<Awaited<FunctionReturnType<Query>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n const value = this.client.localQueryResult(getFunctionName(query), args) as\n | Awaited<FunctionReturnType<Query>>\n | undefined;\n if (value !== undefined) return Promise.resolve(value);\n\n return new Promise((resolve, reject) => {\n const { unsubscribe } = this.onUpdate(\n query,\n args,\n (value) => {\n unsubscribe();\n resolve(value);\n },\n (e: Error) => {\n unsubscribe();\n reject(e);\n },\n );\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return this.client.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n if (this.disabled) return () => {};\n return this.client.subscribeToConnectionState(cb);\n }\n}\n\n// internal information tracked about each registered callback\ntype QueryInfo = {\n callback: (result: any, meta: unknown) => unknown;\n onError: ((e: Error, meta: unknown) => unknown) | undefined;\n unsubscribe: () => void;\n queryToken: QueryToken | PaginatedQueryToken;\n hasEverRun: boolean;\n // query, args and paginationOptions are just here for debugging, the queryToken is authoritative\n query: FunctionReference<\"query\"> | FunctionReference_future<\"query\">;\n args: any;\n paginationOptions: { initialNumItems: number; id: number } | undefined;\n};\n\n// helps to construct objects with a call signature\ntype RemoveCallSignature<T> = Omit<T, never>;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAsC;AAQtC,iBAAgC;AAEhC,oBAKO;AACP,oCAGO;AAGP,4BAIO;AAKP,IAAI;AAGG,SAAS,+BAA+B,IAAsB;AACnE,gCAA8B;AAChC;AAiDO,MAAM,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAoCxB,YAAY,SAAiB,UAA+B,CAAC,GAAG;AAnChE,wBAAQ;AACR,wBAAQ;AACR,wBAAQ;AAER;AAAA,wBAAQ;AAGR,wBAAQ;AACR,wBAAQ;AA4BN,QAAI,QAAQ,iCAAiC,MAAM;AACjD,+CAAsB,OAAO;AAAA,IAC/B;AACA,UAAM,EAAE,UAAU,GAAG,YAAY,IAAI;AACrC,SAAK,UAAU;AACf,SAAK,YAAY,CAAC,CAAC;AACnB,QACE,+BACA,EAAE,0BAA0B,gBAC5B,OAAO,cAAc,aACrB;AACA,kBAAY,uBAAuB;AAAA,IACrC;AACA,QACE,OAAO,WAAW,eAClB,EAAE,2BAA2B,cAC7B;AACA,kBAAY,wBAAwB;AAAA,IACtC;AACA,QAAI,CAAC,KAAK,UAAU;AAClB,WAAK,UAAU,IAAI;AAAA,QACjB;AAAA,QACA,MAAM;AAAA,QAAC;AAAA;AAAA,QACP;AAAA,MACF;AACA,WAAK,mBAAmB,IAAI;AAAA,QAC1B,K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/sync/optimistic_updates.ts"],
|
|
4
|
-
"sourcesContent": ["import { Value } from \"../../values/index.js\";\nimport {\n FunctionArgs,\n
|
|
4
|
+
"sourcesContent": ["import { Value } from \"../../values/index.js\";\nimport {\n FunctionArgs,\n FunctionReturnType,\n OptionalRestArgs,\n FunctionReference,\n FunctionReference_future,\n} from \"../../server/api.js\";\n\n/**\n * A view of the query results currently in the Convex client for use within\n * optimistic updates.\n *\n * @public\n */\nexport interface OptimisticLocalStore {\n /**\n * Retrieve the result of a query from the client.\n *\n * Important: Query results should be treated as immutable!\n * Always make new copies of structures within query results to avoid\n * corrupting data within the client.\n *\n * @param query - A {@link FunctionReference} for the query to get.\n * @param args - The arguments object for this query.\n * @returns The query result or `undefined` if the query is not currently\n * in the client.\n */\n getQuery<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): undefined | FunctionReturnType<Query>;\n\n /**\n * Retrieve the results and arguments of all queries with a given name.\n *\n * This is useful for complex optimistic updates that need to inspect and\n * update many query results (for example updating a paginated list).\n *\n * Important: Query results should be treated as immutable!\n * Always make new copies of structures within query results to avoid\n * corrupting data within the client.\n *\n * @param query - A {@link FunctionReference} for the query to get.\n * @returns An array of objects, one for each query of the given name.\n * Each object includes:\n * - `args` - The arguments object for the query.\n * - `value` The query result or `undefined` if the query is loading.\n */\n getAllQueries<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n ): {\n args: FunctionArgs<Query>;\n value: undefined | FunctionReturnType<Query>;\n }[];\n\n /**\n * Optimistically update the result of a query.\n *\n * This can either be a new value (perhaps derived from the old value from\n * {@link OptimisticLocalStore.getQuery}) or `undefined` to remove the query.\n * Removing a query is useful to create loading states while Convex recomputes\n * the query results.\n *\n * @param query - A {@link FunctionReference} for the query to set.\n * @param args - The arguments object for this query.\n * @param value - The new value to set the query to or `undefined` to remove\n * it from the client.\n */\n setQuery<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n args: FunctionArgs<Query>,\n value: undefined | FunctionReturnType<Query>,\n ): void;\n}\n/**\n * A temporary, local update to query results within this client.\n *\n * This update will always be executed when a mutation is synced to the Convex\n * server and rolled back when the mutation completes.\n *\n * Note that optimistic updates can be called multiple times! If the client\n * loads new data while the mutation is in progress, the update will be replayed\n * again.\n *\n * @param localQueryStore - An interface to read and edit local query results.\n * @param args - The arguments to the mutation.\n *\n * @public\n */\nexport type OptimisticUpdate<Args extends Record<string, Value>> = (\n localQueryStore: OptimisticLocalStore,\n args: Args,\n) => void;\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;AAAA;AAAA;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/browser/sync/optimistic_updates_impl.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n FunctionArgs,\n
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["import {\n FunctionArgs,\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n FunctionReference,\n FunctionReference_future,\n} from \"../../server/api.js\";\nimport { parseArgs } from \"../../common/index.js\";\nimport { Value } from \"../../values/index.js\";\nimport { createHybridErrorStacktrace, forwardData } from \"../logging.js\";\nimport { FunctionResult } from \"./function_result.js\";\nimport { OptimisticLocalStore } from \"./optimistic_updates.js\";\nimport { RequestId } from \"./protocol.js\";\nimport {\n canonicalizeUdfPath,\n QueryToken,\n serializePathAndArgs,\n} from \"./udf_path_utils.js\";\nimport { ConvexError } from \"../../values/errors.js\";\n\n/**\n * An optimistic update function that has been curried over its arguments.\n */\ntype WrappedOptimisticUpdate = (locaQueryStore: OptimisticLocalStore) => void;\n\n/**\n * The implementation of `OptimisticLocalStore`.\n *\n * This class provides the interface for optimistic updates to modify query results.\n */\nclass OptimisticLocalStoreImpl implements OptimisticLocalStore {\n // A references of the query results in OptimisticQueryResults\n private readonly queryResults: QueryResultsMap;\n\n // All of the queries modified by this class\n readonly modifiedQueries: QueryToken[];\n\n constructor(queryResults: QueryResultsMap) {\n this.queryResults = queryResults;\n this.modifiedQueries = [];\n }\n\n getQuery<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): undefined | FunctionReturnType<Query> {\n const queryArgs = parseArgs(args[0]);\n const name = getFunctionName(query);\n const queryResult = this.queryResults.get(\n serializePathAndArgs(name, queryArgs),\n );\n if (queryResult === undefined) {\n return undefined;\n }\n return OptimisticLocalStoreImpl.queryValue(queryResult.result);\n }\n\n getAllQueries<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n ): {\n args: FunctionArgs<Query>;\n value: undefined | FunctionReturnType<Query>;\n }[] {\n const queriesWithName: {\n args: FunctionArgs<Query>;\n value: undefined | FunctionReturnType<Query>;\n }[] = [];\n const name = getFunctionName(query);\n for (const queryResult of this.queryResults.values()) {\n if (queryResult.udfPath === canonicalizeUdfPath(name)) {\n queriesWithName.push({\n args: queryResult.args as FunctionArgs<Query>,\n value: OptimisticLocalStoreImpl.queryValue(queryResult.result),\n });\n }\n }\n return queriesWithName;\n }\n\n setQuery<\n QueryReference extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n queryReference: QueryReference,\n args: FunctionArgs<QueryReference>,\n value: undefined | FunctionReturnType<QueryReference>,\n ): void {\n const queryArgs = parseArgs(args);\n const name = getFunctionName(queryReference);\n const queryToken = serializePathAndArgs(name, queryArgs);\n\n let result: FunctionResult | undefined;\n if (value === undefined) {\n result = undefined;\n } else {\n result = {\n success: true,\n value,\n // It's an optimistic update, so there are no function logs to show.\n logLines: [],\n };\n }\n const query: Query = {\n udfPath: name,\n args: queryArgs,\n result,\n };\n this.queryResults.set(queryToken, query);\n this.modifiedQueries.push(queryToken);\n }\n\n private static queryValue(\n result: FunctionResult | undefined,\n ): Value | undefined {\n if (result === undefined) {\n return undefined;\n } else if (result.success) {\n return result.value;\n } else {\n // If the query is an error state, just return `undefined` as though\n // it's loading. Optimistic updates should already handle `undefined` well\n // and there isn't a need to break the whole update because it tried\n // to load a single query that errored.\n return undefined;\n }\n }\n}\n\ntype OptimisticUpdateAndId = {\n update: WrappedOptimisticUpdate;\n mutationId: RequestId;\n};\n\ntype Query = {\n // undefined means the query was set to be loading (undefined) in an optimistic update.\n // Note that we can also have queries not present in the QueryResultMap\n // at all because they are still loading from the server and have no optimistic update\n // setting an optimistic value in advance.\n result: FunctionResult | undefined;\n udfPath: string;\n args: Record<string, Value>;\n};\nexport type QueryResultsMap = Map<QueryToken, Query>;\n\ntype ChangedQueries = QueryToken[];\n\n/**\n * A view of all of our query results with optimistic updates applied on top.\n */\nexport class OptimisticQueryResults {\n private queryResults: QueryResultsMap;\n private optimisticUpdates: OptimisticUpdateAndId[];\n\n constructor() {\n this.queryResults = new Map();\n this.optimisticUpdates = [];\n }\n\n /**\n * Apply all optimistic updates on top of server query results\n */\n ingestQueryResultsFromServer(\n serverQueryResults: QueryResultsMap,\n optimisticUpdatesToDrop: Set<RequestId>,\n ): ChangedQueries {\n this.optimisticUpdates = this.optimisticUpdates.filter((updateAndId) => {\n return !optimisticUpdatesToDrop.has(updateAndId.mutationId);\n });\n\n const oldQueryResults = this.queryResults;\n this.queryResults = new Map(serverQueryResults);\n const localStore = new OptimisticLocalStoreImpl(this.queryResults);\n for (const updateAndId of this.optimisticUpdates) {\n updateAndId.update(localStore);\n }\n\n // To find the changed queries, just do a shallow comparison\n // TODO(CX-733): Change this so we avoid unnecessary rerenders\n const changedQueries: ChangedQueries = [];\n for (const [queryToken, query] of this.queryResults) {\n const oldQuery = oldQueryResults.get(queryToken);\n if (oldQuery === undefined || oldQuery.result !== query.result) {\n changedQueries.push(queryToken);\n }\n }\n\n return changedQueries;\n }\n\n applyOptimisticUpdate(\n update: WrappedOptimisticUpdate,\n mutationId: RequestId,\n ): ChangedQueries {\n // Apply the update to our store\n this.optimisticUpdates.push({\n update,\n mutationId,\n });\n const localStore = new OptimisticLocalStoreImpl(this.queryResults);\n update(localStore);\n\n // Notify about any query results that changed\n // TODO(CX-733): Change this so we avoid unnecessary rerenders\n return localStore.modifiedQueries;\n }\n\n /**\n * \"Raw\" with respect to errors vs values, but query results still have\n * optimistic updates applied.\n *\n * @internal\n */\n rawQueryResult(queryToken: QueryToken): FunctionResult | undefined {\n const query = this.queryResults.get(queryToken);\n if (query === undefined) {\n return undefined;\n }\n return query.result;\n }\n\n queryResult(queryToken: QueryToken): Value | undefined {\n const query = this.queryResults.get(queryToken);\n if (query === undefined) {\n return undefined;\n }\n const result = query.result;\n if (result === undefined) {\n return undefined;\n } else if (result.success) {\n return result.value;\n } else {\n if (result.errorData !== undefined) {\n throw forwardData(\n result,\n new ConvexError(\n createHybridErrorStacktrace(\"query\", query.udfPath, result),\n ),\n );\n }\n throw new Error(\n createHybridErrorStacktrace(\"query\", query.udfPath, result),\n );\n }\n }\n\n hasQueryResult(queryToken: QueryToken): boolean {\n return this.queryResults.get(queryToken) !== undefined;\n }\n\n /**\n * @internal\n */\n queryLogs(queryToken: QueryToken): string[] | undefined {\n const query = this.queryResults.get(queryToken);\n return query?.result?.logLines;\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAOO;AACP,oBAA0B;AAE1B,qBAAyD;AAIzD,4BAIO;AACP,oBAA4B;AAY5B,MAAM,yBAAyD;AAAA,EAO7D,YAAY,cAA+B;AAL3C;AAAA,wBAAiB;AAGjB;AAAA,wBAAS;AAGP,SAAK,eAAe;AACpB,SAAK,kBAAkB,CAAC;AAAA,EAC1B;AAAA,EAEA,SAKE,UACG,MACoC;AACvC,UAA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W,OAAO,SAAS;AACzB,aAAO,OAAO;AAAA,IAChB,OAAO;AACL,UAAI,OAAO,cAAc,QAAW;AAClC,kBAAM;AAAA,UACJ;AAAA,UACA,IAAI;AAAA,gBACF,4CAA4B,SAAS,MAAM,SAAS,MAAM;AAAA,UAC5D;AAAA,QACF;AAAA,MACF;AACA,YAAM,IAAI;AAAA,YACR,4CAA4B,SAAS,MAAM,SAAS,MAAM;AAAA,MAC5D;AAAA,IACF;AAAA,EACF;AAAA,EAEA,eAAe,YAAiC;AAC9C,WAAO,KAAK,aAAa,IAAI,UAAU,MAAM;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU,YAA8C;AACtD,UAAM,QAAQ,KAAK,aAAa,IAAI,UAAU;AAC9C,WAAO,OAAO,QAAQ;AAAA,EACxB;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cjs/cli/codegen.js
CHANGED
|
@@ -70,6 +70,8 @@ const codegen = new import_extra_typings.Command("codegen").summary("Generate ba
|
|
|
70
70
|
systemUdfs: !!options.systemUdfs,
|
|
71
71
|
largeIndexDeletionCheck: "no verification",
|
|
72
72
|
// `codegen` is a read-only operation
|
|
73
|
+
warnOnSlowSchemaValidation: false,
|
|
74
|
+
// ditto: a codegen dry run never deploys
|
|
73
75
|
codegenOnlyThisComponent: options.componentDir
|
|
74
76
|
};
|
|
75
77
|
if (options.systemUdfs) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/cli/codegen.ts"],
|
|
4
|
-
"sourcesContent": ["import { Command, Option } from \"@commander-js/extra-typings\";\nimport { oneoffContext } from \"../bundler/context.js\";\nimport { runCodegen } from \"./lib/components.js\";\nimport { getDeploymentSelection } from \"./lib/deploymentSelection.js\";\nimport {\n DetailedDeploymentCredentials,\n loadSelectedDeploymentCredentials,\n} from \"./lib/api.js\";\nimport { withRunningBackend } from \"./lib/localDeployment/run.js\";\nexport const codegen = new Command(\"codegen\")\n .summary(\"Generate backend type definitions\")\n .description(\n [\n \"Generate code in `convex/_generated/` based on the current contents of `convex/`.\",\n \"\",\n \"This code is generated automatically while running `npx convex dev` and should be committed to the repo (your code won't typecheck without it!). Regenerating it explicitly is rarely needed (e.g. in CI to ensure the correct code was checked in).\",\n \"\",\n \"This doesn't modify the code running on the deployment.\",\n ].join(\"\\n\"),\n )\n .allowExcessArguments(false)\n .option(\n \"--dry-run\",\n \"Print out the generated configuration to stdout instead of writing to convex directory\",\n )\n .addOption(new Option(\"--debug\").hideHelp())\n .addOption(\n new Option(\n \"--typecheck <mode>\",\n `Whether to check TypeScript files with \\`tsc --noEmit\\`.`,\n )\n .choices([\"enable\", \"try\", \"disable\"] as const)\n .default(\"try\" as const),\n )\n .option(\n \"--init\",\n \"Also (over-)write the default convex/README.md and convex/tsconfig.json files, otherwise only written when creating a new Convex project.\",\n )\n .addOption(new Option(\"--admin-key <adminKey>\").hideHelp())\n .addOption(new Option(\"--url <url>\").hideHelp())\n .addOption(new Option(\"--live-component-sources\").hideHelp())\n // Experimental option\n .addOption(\n new Option(\n \"--commonjs\",\n \"Generate CommonJS modules (CJS) instead of ECMAScript modules, the default. Bundlers typically take care of this conversion while bundling, so this setting is generally only useful for projects which do not use a bundler, typically Node.js projects. Convex functions can be written with either syntax.\",\n ).hideHelp(),\n )\n // Only for doing codegen on system UDFs\n .addOption(new Option(\"--system-udfs\").hideHelp())\n .option(\n \"--component-dir <path>\",\n \"Generate code for a specific component directory instead of the current application.\",\n )\n .action(async (options) => {\n const ctx = await oneoffContext(options);\n const deploymentSelection = await getDeploymentSelection(ctx, options);\n\n const codegenOptions = {\n dryRun: !!options.dryRun,\n debug: !!options.debug,\n typecheck: options.typecheck,\n init: !!options.init,\n commonjs: !!options.commonjs,\n url: options.url,\n adminKey: options.adminKey,\n liveComponentSources: !!options.liveComponentSources,\n debugNodeApis: false,\n systemUdfs: !!options.systemUdfs,\n largeIndexDeletionCheck: \"no verification\" as const, // `codegen` is a read-only operation\n codegenOnlyThisComponent: options.componentDir,\n };\n\n if (options.systemUdfs) {\n await runCodegen(ctx, null, codegenOptions);\n return;\n }\n\n // Early exit for a better error message trying to use a preview key.\n if (deploymentSelection.kind === \"preview\") {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `Codegen requires an existing deployment so doesn't support CONVEX_DEPLOY_KEY.\\nGenerate code in dev and commit it to the repo instead.\\nhttps://docs.convex.dev/understanding/best-practices/other-recommendations#check-generated-code-into-version-control`,\n });\n }\n\n const credentials: DetailedDeploymentCredentials =\n await loadSelectedDeploymentCredentials(ctx, deploymentSelection, {\n ensureLocalRunning: false,\n });\n\n await withRunningBackend({\n ctx,\n deployment: {\n deploymentUrl: credentials.url,\n deploymentFields: credentials.deploymentFields,\n },\n action: async () => {\n await runCodegen(ctx, credentials, codegenOptions);\n },\n });\n });\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAgC;AAChC,qBAA8B;AAC9B,wBAA2B;AAC3B,iCAAuC;AACvC,iBAGO;AACP,iBAAmC;AAC5B,MAAM,UAAU,IAAI,6BAAQ,SAAS,EACzC,QAAQ,mCAAmC,EAC3C;AAAA,EACC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb,EACC,qBAAqB,KAAK,EAC1B;AAAA,EACC;AAAA,EACA;AACF,EACC,UAAU,IAAI,4BAAO,SAAS,EAAE,SAAS,CAAC,EAC1C;AAAA,EACC,IAAI;AAAA,IACF;AAAA,IACA;AAAA,EACF,EACG,QAAQ,CAAC,UAAU,OAAO,SAAS,CAAU,EAC7C,QAAQ,KAAc;AAC3B,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC,UAAU,IAAI,4BAAO,wBAAwB,EAAE,SAAS,CAAC,EACzD,UAAU,IAAI,4BAAO,a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AAa,cAAc;AAAA,IACnD;AAAA,EACF,CAAC;AACH,CAAC;",
|
|
4
|
+
"sourcesContent": ["import { Command, Option } from \"@commander-js/extra-typings\";\nimport { oneoffContext } from \"../bundler/context.js\";\nimport { runCodegen } from \"./lib/components.js\";\nimport { getDeploymentSelection } from \"./lib/deploymentSelection.js\";\nimport {\n DetailedDeploymentCredentials,\n loadSelectedDeploymentCredentials,\n} from \"./lib/api.js\";\nimport { withRunningBackend } from \"./lib/localDeployment/run.js\";\nexport const codegen = new Command(\"codegen\")\n .summary(\"Generate backend type definitions\")\n .description(\n [\n \"Generate code in `convex/_generated/` based on the current contents of `convex/`.\",\n \"\",\n \"This code is generated automatically while running `npx convex dev` and should be committed to the repo (your code won't typecheck without it!). Regenerating it explicitly is rarely needed (e.g. in CI to ensure the correct code was checked in).\",\n \"\",\n \"This doesn't modify the code running on the deployment.\",\n ].join(\"\\n\"),\n )\n .allowExcessArguments(false)\n .option(\n \"--dry-run\",\n \"Print out the generated configuration to stdout instead of writing to convex directory\",\n )\n .addOption(new Option(\"--debug\").hideHelp())\n .addOption(\n new Option(\n \"--typecheck <mode>\",\n `Whether to check TypeScript files with \\`tsc --noEmit\\`.`,\n )\n .choices([\"enable\", \"try\", \"disable\"] as const)\n .default(\"try\" as const),\n )\n .option(\n \"--init\",\n \"Also (over-)write the default convex/README.md and convex/tsconfig.json files, otherwise only written when creating a new Convex project.\",\n )\n .addOption(new Option(\"--admin-key <adminKey>\").hideHelp())\n .addOption(new Option(\"--url <url>\").hideHelp())\n .addOption(new Option(\"--live-component-sources\").hideHelp())\n // Experimental option\n .addOption(\n new Option(\n \"--commonjs\",\n \"Generate CommonJS modules (CJS) instead of ECMAScript modules, the default. Bundlers typically take care of this conversion while bundling, so this setting is generally only useful for projects which do not use a bundler, typically Node.js projects. Convex functions can be written with either syntax.\",\n ).hideHelp(),\n )\n // Only for doing codegen on system UDFs\n .addOption(new Option(\"--system-udfs\").hideHelp())\n .option(\n \"--component-dir <path>\",\n \"Generate code for a specific component directory instead of the current application.\",\n )\n .action(async (options) => {\n const ctx = await oneoffContext(options);\n const deploymentSelection = await getDeploymentSelection(ctx, options);\n\n const codegenOptions = {\n dryRun: !!options.dryRun,\n debug: !!options.debug,\n typecheck: options.typecheck,\n init: !!options.init,\n commonjs: !!options.commonjs,\n url: options.url,\n adminKey: options.adminKey,\n liveComponentSources: !!options.liveComponentSources,\n debugNodeApis: false,\n systemUdfs: !!options.systemUdfs,\n largeIndexDeletionCheck: \"no verification\" as const, // `codegen` is a read-only operation\n warnOnSlowSchemaValidation: false, // ditto: a codegen dry run never deploys\n codegenOnlyThisComponent: options.componentDir,\n };\n\n if (options.systemUdfs) {\n await runCodegen(ctx, null, codegenOptions);\n return;\n }\n\n // Early exit for a better error message trying to use a preview key.\n if (deploymentSelection.kind === \"preview\") {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `Codegen requires an existing deployment so doesn't support CONVEX_DEPLOY_KEY.\\nGenerate code in dev and commit it to the repo instead.\\nhttps://docs.convex.dev/understanding/best-practices/other-recommendations#check-generated-code-into-version-control`,\n });\n }\n\n const credentials: DetailedDeploymentCredentials =\n await loadSelectedDeploymentCredentials(ctx, deploymentSelection, {\n ensureLocalRunning: false,\n });\n\n await withRunningBackend({\n ctx,\n deployment: {\n deploymentUrl: credentials.url,\n deploymentFields: credentials.deploymentFields,\n },\n action: async () => {\n await runCodegen(ctx, credentials, codegenOptions);\n },\n });\n });\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAgC;AAChC,qBAA8B;AAC9B,wBAA2B;AAC3B,iCAAuC;AACvC,iBAGO;AACP,iBAAmC;AAC5B,MAAM,UAAU,IAAI,6BAAQ,SAAS,EACzC,QAAQ,mCAAmC,EAC3C;AAAA,EACC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAA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;AAC1C,WAAO,MAAM,IAAI,MAAM;AAAA,MACrB,UAAU;AAAA,MACV,WAAW;AAAA,MACX,gBAAgB;AAAA;AAAA;AAAA,IAClB,CAAC;AAAA,EACH;AAEA,QAAM,cACJ,UAAM,8CAAkC,KAAK,qBAAqB;AAAA,IAChE,oBAAoB;AAAA,EACtB,CAAC;AAEH,YAAM,+BAAmB;AAAA,IACvB;AAAA,IACA,YAAY;AAAA,MACV,eAAe,YAAY;AAAA,MAC3B,kBAAkB,YAAY;AAAA,IAChC;AAAA,IACA,QAAQ,YAAY;AAClB,gBAAM,8BAAW,KAAK,aAAa,cAAc;AAAA,IACnD;AAAA,EACF,CAAC;AACH,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cjs/cli/deploy.js
CHANGED
|
@@ -251,6 +251,7 @@ async function deployToNewPreviewDeployment(ctx, deploymentSelection, options) {
|
|
|
251
251
|
pushAllModules: !!options.pushAllModules,
|
|
252
252
|
largeIndexDeletionCheck: "no verification",
|
|
253
253
|
// fine for preview deployments
|
|
254
|
+
warnOnSlowSchemaValidation: true,
|
|
254
255
|
message: options.message
|
|
255
256
|
};
|
|
256
257
|
(0, import_log.showSpinner)(`Deploying to ${previewUrl}...`);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/cli/deploy.ts"],
|
|
4
|
-
"sourcesContent": ["import { chalkStderr } from \"chalk\";\nimport { Command, Option } from \"@commander-js/extra-typings\";\nimport { Context, oneoffContext } from \"../bundler/context.js\";\nimport { logFinishedStep, logMessage, showSpinner } from \"../bundler/log.js\";\nimport { loadSelectedDeploymentCredentials } from \"./lib/api.js\";\nimport { announceDeploymentTarget } from \"./lib/announceDeploymentTarget.js\";\nimport {\n getDefaultDeployMessage,\n gitBranchFromEnvironment,\n isNonProdBuildEnvironment,\n suggestedEnvVarNames,\n} from \"./lib/envvars.js\";\nimport { PushOptions } from \"./lib/components.js\";\nimport {\n CONVEX_DEPLOY_KEY_ENV_VAR_NAME,\n CONVEX_SELF_HOSTED_URL_VAR_NAME,\n CONVEX_DEPLOYMENT_ENV_VAR_NAME,\n bigBrainAPI,\n} from \"./lib/utils/utils.js\";\nimport { runFunctionAndLog } from \"./lib/run.js\";\nimport { usageStateWarning } from \"./lib/usage.js\";\nimport { getTeamAndProjectFromPreviewAdminKey } from \"./lib/deployment.js\";\nimport { runPush } from \"./lib/components.js\";\nimport { promptYesNo } from \"./lib/utils/prompts.js\";\nimport { deployToDeployment, runCommand } from \"./lib/deploy2.js\";\nimport {\n DeploymentSelection,\n getDeploymentSelection,\n} from \"./lib/deploymentSelection.js\";\nimport { deploymentNameAndTypeFromSelection } from \"./lib/deploymentSelection.js\";\nimport { checkVersionAndAiFilesStaleness } from \"./lib/updates.js\";\nimport { readProjectConfig, getAuthKitConfig } from \"./lib/config.js\";\nimport { ensureAuthKitProvisionedBeforeBuild } from \"./lib/workos/workos.js\";\nimport { DASHBOARD_HOST } from \"./lib/dashboard.js\";\nimport { extractDeploymentNameForWorkOS } from \"./lib/extractDeploymentNameForWorkOS.js\";\n\nexport const deploy = new Command(\"deploy\")\n .summary(\"Deploy to a production or preview deployment\")\n .description(\n [\n \"Deploys code to a deployment.\",\n \"This is typically used for deploying to a prod or preview deployment manually or from CI; to deploy to your dev deployment when developing, use `npx convex dev`.\",\n \"\",\n \"The target deployment is chosen like this:\",\n `\u2022 If the \\`${CONVEX_DEPLOYMENT_ENV_VAR_NAME}\\` environment variable is set (typical during local development), the target is the project\u2019s default production deployment.`,\n `\u2022 If the \\`${CONVEX_DEPLOY_KEY_ENV_VAR_NAME}\\` environment variable is set (typical in CI), it is the deployment associated with that key.`,\n ` \u2022 When it\u2019s set to a preview deploy key, it will deploy to a preview deployment:`,\n ` \u2022 with the name of the current Git branch when running in CI (Vercel, Netlify, Cloudflare Pages, GitHub)`,\n ` \u2022 or with the name specified by the \\`--preview-name\\` or \\`--preview-create\\` flags`,\n \"\",\n \"`npx convex deploy` will:\",\n \" 1. Run a command if specified with `--cmd`, with the deployment URL available as an environment variable.\",\n \" 2. Typecheck your Convex functions.\",\n \" 3. Regenerate the generated code in the `convex/_generated` directory.\",\n \" 4. Bundle your Convex functions and their dependencies.\",\n \" 5. Push your functions, indexes, and schema to the deployment.\",\n \" 6. When deploying to a preview deployment, it runs the function specified by `--preview-run`.\",\n \"If any step fails, the next steps do not run.\",\n ].join(\"\\n\"),\n )\n .allowExcessArguments(false)\n .addDeployOptions()\n .addOption(\n new Option(\n \"--preview-run <functionName>\",\n \"Function to run if deploying to a preview deployment. This is ignored if deploying to a production deployment.\",\n ),\n )\n .addOption(\n new Option(\n \"--preview-name <name>\",\n \"The name to associate with this preview deployment. Defaults to the current Git branch name in Vercel, Netlify, Cloudflare Pages and GitHub CI. Reuses the existing deployment if one exists.\",\n ).conflicts(\"preview-create\"),\n )\n .addOption(\n new Option(\n \"--preview-create <name>\",\n \"Like --preview-name, but deletes and recreates an existing preview deployment with the same name. This parameter can only be used with a preview deploy key (when used with another type of key, the command will return an error).\",\n ).conflicts(\"preview-name\"),\n )\n .addOption(\n new Option(\n \"--check-build-environment <mode>\",\n \"Whether to check for a non-production build environment before deploying to a production Convex deployment.\",\n )\n .choices([\"enable\", \"disable\"] as const)\n .default(\"enable\" as const)\n .hideHelp(),\n )\n // Hidden options to pass in admin key and url for tests and local development\n .addOption(new Option(\"--admin-key <adminKey>\").hideHelp())\n .addOption(new Option(\"--url <url>\").hideHelp())\n .addOption(\n new Option(\n \"--env-file <envFile>\",\n `Path to a custom file of environment variables, for choosing the \\\ndeployment, e.g. ${CONVEX_DEPLOYMENT_ENV_VAR_NAME} or ${CONVEX_SELF_HOSTED_URL_VAR_NAME}. \\\nSame format as .env.local or .env files, and overrides them.`,\n ),\n )\n .addOption(\n new Option(\n \"--message <message>\",\n \"Optional message to attach to this deployment in the audit log.\",\n ),\n )\n .addOption(\n new Option(\n \"--skip-workos-check\",\n \"Skip WorkOS AuthKit provisioning and credential checks during deploy.\",\n ).hideHelp(),\n )\n .addOption(\n new Option(\"--allow-deleting-large-indexes\")\n .hideHelp()\n .conflicts(\"preview-create\")\n .conflicts(\"preview-name\"),\n )\n .showHelpAfterError()\n .action(async (cmdOptions) => {\n const ctx = await oneoffContext(cmdOptions);\n\n const deploymentSelection = await getDeploymentSelection(ctx, {\n ...cmdOptions,\n implicitProd: true,\n });\n if (\n cmdOptions.checkBuildEnvironment === \"enable\" &&\n isNonProdBuildEnvironment() &&\n deploymentSelection.kind === \"existingDeployment\" &&\n deploymentSelection.deploymentToActOn.source === \"deployKey\" &&\n deploymentSelection.deploymentToActOn.deploymentFields?.deploymentType ===\n \"prod\"\n ) {\n await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `Detected a non-production build environment and \"${CONVEX_DEPLOY_KEY_ENV_VAR_NAME}\" for a production Convex deployment.\\n\n This is probably unintentional.\n `,\n });\n }\n\n if (deploymentSelection.kind === \"anonymous\") {\n logMessage(\n \"You are currently developing anonymously with a locally running project.\\n\" +\n \"To deploy your Convex app to the cloud, log in by running `npx convex login`.\\n\" +\n \"See https://docs.convex.dev/production for more information on how Convex cloud works and instructions on how to set up hosting.\",\n );\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: null,\n });\n }\n\n if (deploymentSelection.kind === \"preview\") {\n // TODO -- add usage state warnings here too once we can do it without a deployment name\n // await usageStateWarning(ctx);\n const previewName =\n cmdOptions.previewCreate ??\n cmdOptions.previewName ??\n gitBranchFromEnvironment();\n const reuse = cmdOptions.previewCreate === undefined;\n\n const teamAndProjectSlugs = await getTeamAndProjectFromPreviewAdminKey(\n ctx,\n deploymentSelection.previewDeployKey,\n );\n await deployToNewPreviewDeployment(\n ctx,\n {\n previewDeployKey: deploymentSelection.previewDeployKey,\n projectSelection: {\n kind: \"teamAndProjectSlugs\",\n teamSlug: teamAndProjectSlugs.teamSlug,\n projectSlug: teamAndProjectSlugs.projectSlug,\n },\n },\n {\n ...cmdOptions,\n previewName: previewName ?? undefined,\n reuse,\n message: cmdOptions.message ?? getDefaultDeployMessage(),\n },\n );\n } else {\n if (cmdOptions.previewCreate !== undefined) {\n const source =\n deploymentSelection.kind === \"deploymentWithinProject\" &&\n deploymentSelection.targetProject.kind === \"deploymentName\"\n ? `at ${chalkStderr.blue.underline(`${DASHBOARD_HOST}/dp/${deploymentSelection.targetProject.deploymentName}/settings#preview-deploy-keys`)}`\n : deploymentSelection.kind === \"existingDeployment\" &&\n deploymentSelection.deploymentToActOn.deploymentFields !== null\n ? `at ${chalkStderr.blue.underline(`${DASHBOARD_HOST}/dp/${deploymentSelection.deploymentToActOn.deploymentFields.deploymentName}/settings#preview-deploy-keys`)}`\n : \"on the dashboard\";\n await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `Preview deployments can only be created with preview deploy keys. Generate a preview deploy key ${source} and set the ${chalkStderr.bold(`CONVEX_DEPLOY_KEY`)} environment variable with it.`,\n });\n }\n\n await deployToExistingDeployment(ctx, deploymentSelection, {\n ...cmdOptions,\n skipWorkosCheck: cmdOptions.skipWorkosCheck ?? false,\n allowDeletingLargeIndexes:\n cmdOptions.allowDeletingLargeIndexes ?? false,\n message: cmdOptions.message ?? getDefaultDeployMessage(),\n });\n }\n });\n\nasync function deployToNewPreviewDeployment(\n ctx: Context,\n deploymentSelection: {\n previewDeployKey: string;\n projectSelection: {\n kind: \"teamAndProjectSlugs\";\n teamSlug: string;\n projectSlug: string;\n };\n },\n options: {\n dryRun?: boolean | undefined;\n previewName?: string | undefined;\n reuse: boolean;\n previewRun?: string | undefined;\n cmdUrlEnvVarName?: string | undefined;\n cmd?: string | undefined;\n verbose?: boolean | undefined;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: \"enable\" | \"disable\";\n pushAllModules?: boolean;\n\n debug?: boolean | undefined;\n debugBundlePath?: string | undefined;\n skipWorkosCheck?: boolean | undefined;\n message: string | null;\n },\n) {\n const previewName = options.previewName ?? null;\n if (previewName === null) {\n await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage:\n \"`npx convex deploy` to a preview deployment could not determine the preview name. Provide one using `--preview-name`\",\n });\n }\n\n if (options.dryRun) {\n logFinishedStep(\n `Would have claimed preview deployment for \"${previewName}\"`,\n );\n await runCommand(ctx, {\n cmdUrlEnvVarName: options.cmdUrlEnvVarName,\n cmd: options.cmd,\n dryRun: !!options.dryRun,\n url: \"https://<PREVIEW DEPLOYMENT>.convex.cloud\",\n adminKey: \"preview-deployment-admin-key\",\n });\n logFinishedStep(\n `Would have deployed Convex functions to preview deployment for \"${previewName}\"`,\n );\n if (options.previewRun !== undefined) {\n logMessage(`Would have run function \"${options.previewRun}\"`);\n }\n return;\n }\n const data = await bigBrainAPI({\n ctx,\n method: \"POST\",\n path: \"claim_preview_deployment\",\n data: {\n projectSelection: deploymentSelection.projectSelection,\n identifier: previewName,\n reuse: options.reuse,\n },\n });\n\n const previewAdminKey = data.adminKey;\n const previewUrl = data.instanceUrl;\n\n // Extract deployment name from URL for WorkOS provisioning\n const deploymentNameForWorkOS = extractDeploymentNameForWorkOS(previewUrl);\n\n announceDeploymentTarget(\"Deploying code to deployment:\", {\n url: previewUrl,\n deploymentFields: {\n deploymentName: data.deploymentName,\n deploymentType: \"preview\",\n teamSlug: deploymentSelection.projectSelection.teamSlug,\n projectSlug: deploymentSelection.projectSelection.projectSlug,\n reference: data.reference,\n // Preview deployments are never default\n isDefault: false,\n },\n });\n\n // Provision WorkOS before building the client bundle (if configured)\n const { projectConfig } = await readProjectConfig(ctx);\n const authKitConfig = await getAuthKitConfig(ctx, projectConfig);\n\n if (authKitConfig && deploymentNameForWorkOS && !options.skipWorkosCheck) {\n await ensureAuthKitProvisionedBeforeBuild(\n ctx,\n deploymentNameForWorkOS,\n { deploymentUrl: previewUrl, adminKey: previewAdminKey },\n \"preview\",\n );\n }\n\n await runCommand(ctx, {\n ...options,\n url: previewUrl,\n adminKey: previewAdminKey,\n });\n\n const pushOptions: PushOptions = {\n deploymentName: null,\n adminKey: previewAdminKey,\n verbose: !!options.verbose,\n dryRun: false,\n typecheck: options.typecheck,\n typecheckComponents: options.typecheckComponents,\n debug: !!options.debug,\n debugBundlePath: options.debugBundlePath,\n debugNodeApis: false,\n codegen: options.codegen === \"enable\",\n url: previewUrl,\n liveComponentSources: false,\n pushAllModules: !!options.pushAllModules,\n largeIndexDeletionCheck: \"no verification\", // fine for preview deployments\n message: options.message,\n };\n showSpinner(`Deploying to ${previewUrl}...`);\n await runPush(ctx, pushOptions);\n logFinishedStep(`Deployed Convex functions to ${previewUrl}`);\n\n if (options.previewRun !== undefined && data.isNewDeployment) {\n await runFunctionAndLog(ctx, {\n deploymentUrl: previewUrl,\n adminKey: previewAdminKey,\n functionName: options.previewRun,\n argsString: \"{}\",\n componentPath: undefined,\n callbacks: {\n onSuccess: () => {\n logFinishedStep(`Finished running function \"${options.previewRun}\"`);\n },\n },\n });\n }\n}\n\nasync function deployToExistingDeployment(\n ctx: Context,\n deploymentSelection: DeploymentSelection,\n options: {\n verbose?: boolean | undefined;\n dryRun?: boolean | undefined;\n yes?: boolean | undefined;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: \"enable\" | \"disable\";\n cmd?: string | undefined;\n cmdUrlEnvVarName?: string | undefined;\n pushAllModules?: boolean;\n\n debugBundlePath?: string | undefined;\n debug?: boolean | undefined;\n adminKey?: string | undefined;\n url?: string | undefined;\n writePushRequest?: string | undefined;\n liveComponentSources?: boolean | undefined;\n envFile?: string | undefined;\n skipWorkosCheck?: boolean | undefined;\n allowDeletingLargeIndexes: boolean;\n message: string | null;\n },\n) {\n const deploymentToActOn = await loadSelectedDeploymentCredentials(\n ctx,\n deploymentSelection,\n );\n announceDeploymentTarget(\"Deploying code to deployment:\", deploymentToActOn);\n const { deploymentFields } = deploymentToActOn;\n\n const configuredDeployment =\n deploymentNameAndTypeFromSelection(deploymentSelection);\n if (configuredDeployment !== null && configuredDeployment.name !== null) {\n const shouldPushToProd =\n configuredDeployment.name === deploymentFields?.deploymentName ||\n (options.yes ??\n (await askToConfirmPush(\n ctx,\n {\n configuredName: configuredDeployment.name,\n configuredType: configuredDeployment.type,\n requestedName: deploymentFields?.deploymentName!,\n requestedType: deploymentFields?.deploymentType!,\n },\n deploymentToActOn.url,\n )));\n if (!shouldPushToProd) {\n await ctx.crash({\n exitCode: 1,\n printedMessage: null,\n errorType: \"fatal\",\n });\n }\n }\n\n const isCloudDeployment = deploymentFields !== null;\n await Promise.all([\n deployToDeployment(\n ctx,\n {\n url: deploymentToActOn.url,\n adminKey: deploymentToActOn.adminKey,\n deploymentName: deploymentFields?.deploymentName ?? null,\n ...(deploymentFields?.deploymentType !== undefined\n ? { deploymentType: deploymentFields.deploymentType }\n : {}),\n },\n { ...options, skipWorkosCheck: options.skipWorkosCheck },\n ),\n ...(isCloudDeployment\n ? [\n usageStateWarning(ctx, deploymentFields.deploymentName),\n checkVersionAndAiFilesStaleness(ctx),\n ]\n : []),\n ]);\n}\n\nasync function askToConfirmPush(\n ctx: Context,\n deployment: {\n configuredName: string;\n configuredType: string | null;\n requestedName: string;\n requestedType: string;\n },\n prodUrl: string,\n) {\n logMessage(\n `\\\nYou're currently developing against your ${chalkStderr.bold(\n deployment.configuredType ?? \"dev\",\n )} deployment\n\n ${deployment.configuredName} (set in CONVEX_DEPLOYMENT)\n\nYour ${chalkStderr.bold(deployment.requestedType)} deployment ${chalkStderr.bold(\n deployment.requestedName,\n )} serves traffic at:\n\n ${(await suggestedEnvVarNames(ctx)).convexUrlEnvVar}=${chalkStderr.bold(prodUrl)}\n\nMake sure that your published client is configured with this URL (for instructions see https://docs.convex.dev/hosting)\\n`,\n );\n return promptYesNo(ctx, {\n message: `Do you want to push your code to your ${deployment.requestedType} deployment ${deployment.requestedName} now?`,\n default: true,\n });\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AA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AU;AAAA,QACV,gBAAgB;AAAA,QAChB,WAAW;AAAA,MACb,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,oBAAoB,qBAAqB;AAC/C,QAAM,QAAQ,IAAI;AAAA,QAChB;AAAA,MACE;AAAA,MACA;AAAA,QACE,KAAK,kBAAkB;AAAA,QACvB,UAAU,kBAAkB;AAAA,QAC5B,gBAAgB,kBAAkB,kBAAkB;AAAA,QACpD,GAAI,kBAAkB,mBAAmB,SACrC,EAAE,gBAAgB,iBAAiB,eAAe,IAClD,CAAC;AAAA,MACP;AAAA,MACA,EAAE,GAAG,SAAS,iBAAiB,QAAQ,gBAAgB;AAAA,IACzD;AAAA,IACA,GAAI,oBACA;AAAA,UACE,gCAAkB,KAAK,iBAAiB,cAAc;AAAA,UACtD,gDAAgC,GAAG;AAAA,IACrC,IACA,CAAC;AAAA,EACP,CAAC;AACH;AAEA,eAAe,iBACb,KACA,YAMA,SACA;AACA;AAAA,IACE,4CACuC,yBAAY;AAAA,MACjD,WAAW,kBAAkB;AAAA,IAC/B,CAAC;AAAA;AAAA,IAED,WAAW,cAAc;AAAA;AAAA,OAEtB,yBAAY,KAAK,WAAW,aAAa,CAAC,eAAe,yBAAY;AAAA,MACtE,WAAW;AAAA,IACb,CAAC;AAAA;AAAA,KAEA,UAAM,qCAAqB,GAAG,GAAG,eAAe,IAAI,yBAAY,KAAK,OAAO,CAAC;AAAA;AAAA;AAAA;AAAA,EAGhF;AACA,aAAO,4BAAY,KAAK;AAAA,IACtB,SAAS,yCAAyC,WAAW,aAAa,eAAe,WAAW,aAAa;AAAA,IACjH,SAAS;AAAA,EACX,CAAC;AACH;",
|
|
4
|
+
"sourcesContent": ["import { chalkStderr } from \"chalk\";\nimport { Command, Option } from \"@commander-js/extra-typings\";\nimport { Context, oneoffContext } from \"../bundler/context.js\";\nimport { logFinishedStep, logMessage, showSpinner } from \"../bundler/log.js\";\nimport { loadSelectedDeploymentCredentials } from \"./lib/api.js\";\nimport { announceDeploymentTarget } from \"./lib/announceDeploymentTarget.js\";\nimport {\n getDefaultDeployMessage,\n gitBranchFromEnvironment,\n isNonProdBuildEnvironment,\n suggestedEnvVarNames,\n} from \"./lib/envvars.js\";\nimport { PushOptions } from \"./lib/components.js\";\nimport {\n CONVEX_DEPLOY_KEY_ENV_VAR_NAME,\n CONVEX_SELF_HOSTED_URL_VAR_NAME,\n CONVEX_DEPLOYMENT_ENV_VAR_NAME,\n bigBrainAPI,\n} from \"./lib/utils/utils.js\";\nimport { runFunctionAndLog } from \"./lib/run.js\";\nimport { usageStateWarning } from \"./lib/usage.js\";\nimport { getTeamAndProjectFromPreviewAdminKey } from \"./lib/deployment.js\";\nimport { runPush } from \"./lib/components.js\";\nimport { promptYesNo } from \"./lib/utils/prompts.js\";\nimport { deployToDeployment, runCommand } from \"./lib/deploy2.js\";\nimport {\n DeploymentSelection,\n getDeploymentSelection,\n} from \"./lib/deploymentSelection.js\";\nimport { deploymentNameAndTypeFromSelection } from \"./lib/deploymentSelection.js\";\nimport { checkVersionAndAiFilesStaleness } from \"./lib/updates.js\";\nimport { readProjectConfig, getAuthKitConfig } from \"./lib/config.js\";\nimport { ensureAuthKitProvisionedBeforeBuild } from \"./lib/workos/workos.js\";\nimport { DASHBOARD_HOST } from \"./lib/dashboard.js\";\nimport { extractDeploymentNameForWorkOS } from \"./lib/extractDeploymentNameForWorkOS.js\";\n\nexport const deploy = new Command(\"deploy\")\n .summary(\"Deploy to a production or preview deployment\")\n .description(\n [\n \"Deploys code to a deployment.\",\n \"This is typically used for deploying to a prod or preview deployment manually or from CI; to deploy to your dev deployment when developing, use `npx convex dev`.\",\n \"\",\n \"The target deployment is chosen like this:\",\n `\u2022 If the \\`${CONVEX_DEPLOYMENT_ENV_VAR_NAME}\\` environment variable is set (typical during local development), the target is the project\u2019s default production deployment.`,\n `\u2022 If the \\`${CONVEX_DEPLOY_KEY_ENV_VAR_NAME}\\` environment variable is set (typical in CI), it is the deployment associated with that key.`,\n ` \u2022 When it\u2019s set to a preview deploy key, it will deploy to a preview deployment:`,\n ` \u2022 with the name of the current Git branch when running in CI (Vercel, Netlify, Cloudflare Pages, GitHub)`,\n ` \u2022 or with the name specified by the \\`--preview-name\\` or \\`--preview-create\\` flags`,\n \"\",\n \"`npx convex deploy` will:\",\n \" 1. Run a command if specified with `--cmd`, with the deployment URL available as an environment variable.\",\n \" 2. Typecheck your Convex functions.\",\n \" 3. Regenerate the generated code in the `convex/_generated` directory.\",\n \" 4. Bundle your Convex functions and their dependencies.\",\n \" 5. Push your functions, indexes, and schema to the deployment.\",\n \" 6. When deploying to a preview deployment, it runs the function specified by `--preview-run`.\",\n \"If any step fails, the next steps do not run.\",\n ].join(\"\\n\"),\n )\n .allowExcessArguments(false)\n .addDeployOptions()\n .addOption(\n new Option(\n \"--preview-run <functionName>\",\n \"Function to run if deploying to a preview deployment. This is ignored if deploying to a production deployment.\",\n ),\n )\n .addOption(\n new Option(\n \"--preview-name <name>\",\n \"The name to associate with this preview deployment. Defaults to the current Git branch name in Vercel, Netlify, Cloudflare Pages and GitHub CI. Reuses the existing deployment if one exists.\",\n ).conflicts(\"preview-create\"),\n )\n .addOption(\n new Option(\n \"--preview-create <name>\",\n \"Like --preview-name, but deletes and recreates an existing preview deployment with the same name. This parameter can only be used with a preview deploy key (when used with another type of key, the command will return an error).\",\n ).conflicts(\"preview-name\"),\n )\n .addOption(\n new Option(\n \"--check-build-environment <mode>\",\n \"Whether to check for a non-production build environment before deploying to a production Convex deployment.\",\n )\n .choices([\"enable\", \"disable\"] as const)\n .default(\"enable\" as const)\n .hideHelp(),\n )\n // Hidden options to pass in admin key and url for tests and local development\n .addOption(new Option(\"--admin-key <adminKey>\").hideHelp())\n .addOption(new Option(\"--url <url>\").hideHelp())\n .addOption(\n new Option(\n \"--env-file <envFile>\",\n `Path to a custom file of environment variables, for choosing the \\\ndeployment, e.g. ${CONVEX_DEPLOYMENT_ENV_VAR_NAME} or ${CONVEX_SELF_HOSTED_URL_VAR_NAME}. \\\nSame format as .env.local or .env files, and overrides them.`,\n ),\n )\n .addOption(\n new Option(\n \"--message <message>\",\n \"Optional message to attach to this deployment in the audit log.\",\n ),\n )\n .addOption(\n new Option(\n \"--skip-workos-check\",\n \"Skip WorkOS AuthKit provisioning and credential checks during deploy.\",\n ).hideHelp(),\n )\n .addOption(\n new Option(\"--allow-deleting-large-indexes\")\n .hideHelp()\n .conflicts(\"preview-create\")\n .conflicts(\"preview-name\"),\n )\n .showHelpAfterError()\n .action(async (cmdOptions) => {\n const ctx = await oneoffContext(cmdOptions);\n\n const deploymentSelection = await getDeploymentSelection(ctx, {\n ...cmdOptions,\n implicitProd: true,\n });\n if (\n cmdOptions.checkBuildEnvironment === \"enable\" &&\n isNonProdBuildEnvironment() &&\n deploymentSelection.kind === \"existingDeployment\" &&\n deploymentSelection.deploymentToActOn.source === \"deployKey\" &&\n deploymentSelection.deploymentToActOn.deploymentFields?.deploymentType ===\n \"prod\"\n ) {\n await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n printedMessage: `Detected a non-production build environment and \"${CONVEX_DEPLOY_KEY_ENV_VAR_NAME}\" for a production Convex deployment.\\n\n This is probably unintentional.\n `,\n });\n }\n\n if (deploymentSelection.kind === \"anonymous\") {\n logMessage(\n \"You are currently developing anonymously with a locally running project.\\n\" +\n \"To deploy your Convex app to the cloud, log in by running `npx convex login`.\\n\" +\n \"See https://docs.convex.dev/production for more information on how Convex cloud works and instructions on how to set up hosting.\",\n );\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: null,\n });\n }\n\n if (deploymentSelection.kind === \"preview\") {\n // TODO -- add usage state warnings here too once we can do it without a deployment name\n // await usageStateWarning(ctx);\n const previewName =\n cmdOptions.previewCreate ??\n cmdOptions.previewName ??\n gitBranchFromEnvironment();\n const reuse = cmdOptions.previewCreate === undefined;\n\n const teamAndProjectSlugs = await getTeamAndProjectFromPreviewAdminKey(\n ctx,\n deploymentSelection.previewDeployKey,\n );\n await deployToNewPreviewDeployment(\n ctx,\n {\n previewDeployKey: deploymentSelection.previewDeployKey,\n projectSelection: {\n kind: \"teamAndProjectSlugs\",\n teamSlug: teamAndProjectSlugs.teamSlug,\n projectSlug: teamAndProjectSlugs.projectSlug,\n },\n },\n {\n ...cmdOptions,\n previewName: previewName ?? undefined,\n reuse,\n message: cmdOptions.message ?? getDefaultDeployMessage(),\n },\n );\n } else {\n if (cmdOptions.previewCreate !== undefined) {\n const source =\n deploymentSelection.kind === \"deploymentWithinProject\" &&\n deploymentSelection.targetProject.kind === \"deploymentName\"\n ? `at ${chalkStderr.blue.underline(`${DASHBOARD_HOST}/dp/${deploymentSelection.targetProject.deploymentName}/settings#preview-deploy-keys`)}`\n : deploymentSelection.kind === \"existingDeployment\" &&\n deploymentSelection.deploymentToActOn.deploymentFields !== null\n ? `at ${chalkStderr.blue.underline(`${DASHBOARD_HOST}/dp/${deploymentSelection.deploymentToActOn.deploymentFields.deploymentName}/settings#preview-deploy-keys`)}`\n : \"on the dashboard\";\n await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: `Preview deployments can only be created with preview deploy keys. Generate a preview deploy key ${source} and set the ${chalkStderr.bold(`CONVEX_DEPLOY_KEY`)} environment variable with it.`,\n });\n }\n\n await deployToExistingDeployment(ctx, deploymentSelection, {\n ...cmdOptions,\n skipWorkosCheck: cmdOptions.skipWorkosCheck ?? false,\n allowDeletingLargeIndexes:\n cmdOptions.allowDeletingLargeIndexes ?? false,\n message: cmdOptions.message ?? getDefaultDeployMessage(),\n });\n }\n });\n\nasync function deployToNewPreviewDeployment(\n ctx: Context,\n deploymentSelection: {\n previewDeployKey: string;\n projectSelection: {\n kind: \"teamAndProjectSlugs\";\n teamSlug: string;\n projectSlug: string;\n };\n },\n options: {\n dryRun?: boolean | undefined;\n previewName?: string | undefined;\n reuse: boolean;\n previewRun?: string | undefined;\n cmdUrlEnvVarName?: string | undefined;\n cmd?: string | undefined;\n verbose?: boolean | undefined;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: \"enable\" | \"disable\";\n pushAllModules?: boolean;\n\n debug?: boolean | undefined;\n debugBundlePath?: string | undefined;\n skipWorkosCheck?: boolean | undefined;\n message: string | null;\n },\n) {\n const previewName = options.previewName ?? null;\n if (previewName === null) {\n await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage:\n \"`npx convex deploy` to a preview deployment could not determine the preview name. Provide one using `--preview-name`\",\n });\n }\n\n if (options.dryRun) {\n logFinishedStep(\n `Would have claimed preview deployment for \"${previewName}\"`,\n );\n await runCommand(ctx, {\n cmdUrlEnvVarName: options.cmdUrlEnvVarName,\n cmd: options.cmd,\n dryRun: !!options.dryRun,\n url: \"https://<PREVIEW DEPLOYMENT>.convex.cloud\",\n adminKey: \"preview-deployment-admin-key\",\n });\n logFinishedStep(\n `Would have deployed Convex functions to preview deployment for \"${previewName}\"`,\n );\n if (options.previewRun !== undefined) {\n logMessage(`Would have run function \"${options.previewRun}\"`);\n }\n return;\n }\n const data = await bigBrainAPI({\n ctx,\n method: \"POST\",\n path: \"claim_preview_deployment\",\n data: {\n projectSelection: deploymentSelection.projectSelection,\n identifier: previewName,\n reuse: options.reuse,\n },\n });\n\n const previewAdminKey = data.adminKey;\n const previewUrl = data.instanceUrl;\n\n // Extract deployment name from URL for WorkOS provisioning\n const deploymentNameForWorkOS = extractDeploymentNameForWorkOS(previewUrl);\n\n announceDeploymentTarget(\"Deploying code to deployment:\", {\n url: previewUrl,\n deploymentFields: {\n deploymentName: data.deploymentName,\n deploymentType: \"preview\",\n teamSlug: deploymentSelection.projectSelection.teamSlug,\n projectSlug: deploymentSelection.projectSelection.projectSlug,\n reference: data.reference,\n // Preview deployments are never default\n isDefault: false,\n },\n });\n\n // Provision WorkOS before building the client bundle (if configured)\n const { projectConfig } = await readProjectConfig(ctx);\n const authKitConfig = await getAuthKitConfig(ctx, projectConfig);\n\n if (authKitConfig && deploymentNameForWorkOS && !options.skipWorkosCheck) {\n await ensureAuthKitProvisionedBeforeBuild(\n ctx,\n deploymentNameForWorkOS,\n { deploymentUrl: previewUrl, adminKey: previewAdminKey },\n \"preview\",\n );\n }\n\n await runCommand(ctx, {\n ...options,\n url: previewUrl,\n adminKey: previewAdminKey,\n });\n\n const pushOptions: PushOptions = {\n deploymentName: null,\n adminKey: previewAdminKey,\n verbose: !!options.verbose,\n dryRun: false,\n typecheck: options.typecheck,\n typecheckComponents: options.typecheckComponents,\n debug: !!options.debug,\n debugBundlePath: options.debugBundlePath,\n debugNodeApis: false,\n codegen: options.codegen === \"enable\",\n url: previewUrl,\n liveComponentSources: false,\n pushAllModules: !!options.pushAllModules,\n largeIndexDeletionCheck: \"no verification\", // fine for preview deployments\n warnOnSlowSchemaValidation: true,\n message: options.message,\n };\n showSpinner(`Deploying to ${previewUrl}...`);\n await runPush(ctx, pushOptions);\n logFinishedStep(`Deployed Convex functions to ${previewUrl}`);\n\n if (options.previewRun !== undefined && data.isNewDeployment) {\n await runFunctionAndLog(ctx, {\n deploymentUrl: previewUrl,\n adminKey: previewAdminKey,\n functionName: options.previewRun,\n argsString: \"{}\",\n componentPath: undefined,\n callbacks: {\n onSuccess: () => {\n logFinishedStep(`Finished running function \"${options.previewRun}\"`);\n },\n },\n });\n }\n}\n\nasync function deployToExistingDeployment(\n ctx: Context,\n deploymentSelection: DeploymentSelection,\n options: {\n verbose?: boolean | undefined;\n dryRun?: boolean | undefined;\n yes?: boolean | undefined;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: \"enable\" | \"disable\";\n cmd?: string | undefined;\n cmdUrlEnvVarName?: string | undefined;\n pushAllModules?: boolean;\n\n debugBundlePath?: string | undefined;\n debug?: boolean | undefined;\n adminKey?: string | undefined;\n url?: string | undefined;\n writePushRequest?: string | undefined;\n liveComponentSources?: boolean | undefined;\n envFile?: string | undefined;\n skipWorkosCheck?: boolean | undefined;\n allowDeletingLargeIndexes: boolean;\n message: string | null;\n },\n) {\n const deploymentToActOn = await loadSelectedDeploymentCredentials(\n ctx,\n deploymentSelection,\n );\n announceDeploymentTarget(\"Deploying code to deployment:\", deploymentToActOn);\n const { deploymentFields } = deploymentToActOn;\n\n const configuredDeployment =\n deploymentNameAndTypeFromSelection(deploymentSelection);\n if (configuredDeployment !== null && configuredDeployment.name !== null) {\n const shouldPushToProd =\n configuredDeployment.name === deploymentFields?.deploymentName ||\n (options.yes ??\n (await askToConfirmPush(\n ctx,\n {\n configuredName: configuredDeployment.name,\n configuredType: configuredDeployment.type,\n requestedName: deploymentFields?.deploymentName!,\n requestedType: deploymentFields?.deploymentType!,\n },\n deploymentToActOn.url,\n )));\n if (!shouldPushToProd) {\n await ctx.crash({\n exitCode: 1,\n printedMessage: null,\n errorType: \"fatal\",\n });\n }\n }\n\n const isCloudDeployment = deploymentFields !== null;\n await Promise.all([\n deployToDeployment(\n ctx,\n {\n url: deploymentToActOn.url,\n adminKey: deploymentToActOn.adminKey,\n deploymentName: deploymentFields?.deploymentName ?? null,\n ...(deploymentFields?.deploymentType !== undefined\n ? { deploymentType: deploymentFields.deploymentType }\n : {}),\n },\n { ...options, skipWorkosCheck: options.skipWorkosCheck },\n ),\n ...(isCloudDeployment\n ? [\n usageStateWarning(ctx, deploymentFields.deploymentName),\n checkVersionAndAiFilesStaleness(ctx),\n ]\n : []),\n ]);\n}\n\nasync function askToConfirmPush(\n ctx: Context,\n deployment: {\n configuredName: string;\n configuredType: string | null;\n requestedName: string;\n requestedType: string;\n },\n prodUrl: string,\n) {\n logMessage(\n `\\\nYou're currently developing against your ${chalkStderr.bold(\n deployment.configuredType ?? \"dev\",\n )} deployment\n\n ${deployment.configuredName} (set in CONVEX_DEPLOYMENT)\n\nYour ${chalkStderr.bold(deployment.requestedType)} deployment ${chalkStderr.bold(\n deployment.requestedName,\n )} serves traffic at:\n\n ${(await suggestedEnvVarNames(ctx)).convexUrlEnvVar}=${chalkStderr.bold(prodUrl)}\n\nMake sure that your published client is configured with this URL (for instructions see https://docs.convex.dev/hosting)\\n`,\n );\n return promptYesNo(ctx, {\n message: `Do you want to push your code to your ${deployment.requestedType} deployment ${deployment.requestedName} now?`,\n default: true,\n });\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA4B;AAC5B,2BAAgC;AAChC,qBAAuC;AACvC,iBAAyD;AACzD,iBAAkD;AAClD,sCAAyC;AACzC,qBAKO;AAEP,mBAKO;AACP,iBAAkC;AAClC,mBAAkC;AAClC,wBAAqD;AACrD,IAAAA,qBAAwB;AACxB,qBAA4B;AAC5B,qBAA+C;AAC/C,iCAGO;AACP,IAAAC,8BAAmD;AACnD,qBAAgD;AAChD,oBAAoD;AACpD,oBAAoD;AACpD,uBAA+B;AAC/B,4CAA+C;AAExC,MAAM,SAAS,IAAI,6BAAQ,QAAQ,EACvC,QAAQ,8CAA8C,EACtD;AAAA,EACC;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,mBAAc,2CAA8B;AAAA,IAC5C,mBAAc,2CAA8B;AAAA,IAC5C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb,EACC,qBAAqB,KAAK,EAC1B,iBAAiB,EACjB;AAAA,EACC,IAAI;AAAA,IACF;AAAA,IACA;AAAA,EACF;AACF,EACC;AAAA,EACC,IAAI;AAAA,IACF;AAAA,IACA;AAAA,EACF,EAAE,UAAU,gBAAgB;AAC9B,EACC;AAAA,EACC,IAAI;AAAA,IACF;AAAA,IACA;AAAA,EACF,EAAE,UAAU,cAAc;AAC5B,EACC;AAAA,EACC,IAAI;AAAA,IACF;AAAA,IACA;AAAA,EACF,EACG,QAAQ,CAAC,UAAU,SAAS,CAAU,EACtC,QAAQ,QAAiB,EACzB,SAAS;A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