convex 1.36.0 → 1.36.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +5 -4
  2. package/dist/browser.bundle.js +1 -1
  3. package/dist/browser.bundle.js.map +1 -1
  4. package/dist/cjs/cli/envDefault.js +130 -41
  5. package/dist/cjs/cli/envDefault.js.map +3 -3
  6. package/dist/cjs/cli/lib/command.js +1 -1
  7. package/dist/cjs/cli/lib/command.js.map +1 -1
  8. package/dist/cjs/cli/lib/login.js +51 -0
  9. package/dist/cjs/cli/lib/login.js.map +3 -3
  10. package/dist/cjs/index.js +1 -1
  11. package/dist/cjs/index.js.map +1 -1
  12. package/dist/cjs-types/cli/envDefault.d.ts +2 -2
  13. package/dist/cjs-types/cli/envDefault.d.ts.map +1 -1
  14. package/dist/cjs-types/cli/envDefault.test.d.ts +2 -0
  15. package/dist/cjs-types/cli/envDefault.test.d.ts.map +1 -0
  16. package/dist/cjs-types/cli/lib/login.d.ts.map +1 -1
  17. package/dist/cjs-types/index.d.ts +1 -1
  18. package/dist/cli.bundle.cjs +186 -48
  19. package/dist/cli.bundle.cjs.map +4 -4
  20. package/dist/esm/cli/envDefault.js +131 -42
  21. package/dist/esm/cli/envDefault.js.map +3 -3
  22. package/dist/esm/cli/lib/command.js +1 -1
  23. package/dist/esm/cli/lib/command.js.map +1 -1
  24. package/dist/esm/cli/lib/login.js +52 -0
  25. package/dist/esm/cli/lib/login.js.map +3 -3
  26. package/dist/esm/index.js +1 -1
  27. package/dist/esm/index.js.map +1 -1
  28. package/dist/esm-types/cli/envDefault.d.ts +2 -2
  29. package/dist/esm-types/cli/envDefault.d.ts.map +1 -1
  30. package/dist/esm-types/cli/envDefault.test.d.ts +2 -0
  31. package/dist/esm-types/cli/envDefault.test.d.ts.map +1 -0
  32. package/dist/esm-types/cli/lib/login.d.ts.map +1 -1
  33. package/dist/esm-types/index.d.ts +1 -1
  34. package/dist/react.bundle.js +1 -1
  35. package/dist/react.bundle.js.map +1 -1
  36. package/package.json +4 -4
  37. package/src/cli/envDefault.test.ts +495 -0
  38. package/src/cli/envDefault.ts +222 -107
  39. package/src/cli/lib/command.ts +1 -1
  40. package/src/cli/lib/login.ts +67 -0
  41. package/src/index.ts +1 -1
@@ -27,23 +27,36 @@ var import_env = require("./lib/env.js");
27
27
  var import_utils = require("./lib/utils/utils.js");
28
28
  var import_defaultEnv = require("./lib/defaultEnv.js");
29
29
  var import_api = require("./lib/api.js");
30
+ var import_context = require("../bundler/context.js");
30
31
  var import_env2 = require("./env.js");
31
- const envDefaultSet = new import_extra_typings.Command("set").usage("[options] <name> <value>").arguments("[name] [value]").summary("Set a default variable").description(
32
- "Set default environment variables for your project's deployment type.\n\n npx convex env default set NAME 'value'\n npx convex env default set NAME # omit a value to set one interactively\n npx convex env default set NAME --from-file value.txt\n npx convex env default set --from-file .env.defaults\nWhen setting multiple values, it will refuse all changes if any variables are already set to different values by default. Pass --force to overwrite the provided values.\nThe deployment type is determined by the current deployment (local maps to dev).\n"
33
- ).option(
34
- "--from-file <file>",
35
- "Read environment variables from a .env file. Without --force, fails if any existing variable has a different value."
36
- ).option(
37
- "--force",
38
- "When setting multiple variables, overwrite existing environment variable values instead of failing on mismatch."
39
- ).configureHelp({ showGlobalOptions: true }).allowExcessArguments(false).action(async (name, value, cmdOptions, cmd) => {
32
+ var import_deploymentSelection = require("./lib/deploymentSelection.js");
33
+ function addEnvDefaultOptions(cmd) {
34
+ return cmd.addOption(
35
+ new import_extra_typings.Option(
36
+ "--type <type>",
37
+ "Manage default env vars for the given deployment type instead of inferring from the current deployment."
38
+ )
39
+ ).addOption(
40
+ new import_extra_typings.Option(
41
+ "--project <project>",
42
+ "Select a project manually. Accepts `team-slug:project-slug` or just `project-slug` (team inferred from your current project). Requires --type."
43
+ )
44
+ );
45
+ }
46
+ const envDefaultSet = addEnvDefaultOptions(
47
+ new import_extra_typings.Command("set").usage("[options] <name> <value>").arguments("[name] [value]").summary("Set a default variable").description(
48
+ "Set default environment variables for your project's deployment type.\n\n npx convex env default set NAME 'value'\n npx convex env default set NAME # omit a value to set one interactively\n npx convex env default set NAME --from-file value.txt\n npx convex env default set --from-file .env.defaults\nWhen setting multiple values, it will refuse all changes if any variables are already set to different values by default. Pass --force to overwrite the provided values.\nThe deployment type is determined by the current deployment (local maps to dev), or by --type if provided.\n"
49
+ ).option(
50
+ "--from-file <file>",
51
+ "Read environment variables from a .env file. Without --force, fails if any existing variable has a different value."
52
+ ).option(
53
+ "--force",
54
+ "When setting multiple variables, overwrite existing environment variable values instead of failing on mismatch."
55
+ ).configureHelp({ showGlobalOptions: true }).allowExcessArguments(false)
56
+ ).action(async (name, value, cmdOptions, cmd) => {
40
57
  const options = cmd.optsWithGlobals();
41
- const { ctx, deployment } = await (0, import_env2.selectEnvDeployment)(options);
58
+ const { ctx, backend } = await resolveEnvDefaultBackend(options);
42
59
  await (0, import_utils.ensureHasConvexDependency)(ctx, "env default set");
43
- const backend = await resolveDefaultEnvBackend(
44
- ctx,
45
- deployment.deploymentFields
46
- );
47
60
  const didAnything = await (0, import_env.envSet)(ctx, backend, name, value, cmdOptions);
48
61
  if (didAnything === false) {
49
62
  cmd.outputHelp({ error: true });
@@ -54,46 +67,122 @@ const envDefaultSet = new import_extra_typings.Command("set").usage("[options] <
54
67
  });
55
68
  }
56
69
  });
57
- const envDefaultGet = new import_extra_typings.Command("get").arguments("<name>").summary("Print a default variable's value").description(
58
- "Print a default variable's value: `npx convex env default get NAME`\nThe deployment type is determined by the current deployment (local maps to dev)."
59
- ).configureHelp({ showGlobalOptions: true }).allowExcessArguments(false).action(async (envVarName, _options, cmd) => {
70
+ const envDefaultGet = addEnvDefaultOptions(
71
+ new import_extra_typings.Command("get").arguments("<name>").summary("Print a default variable's value").description(
72
+ "Print a default variable's value: `npx convex env default get NAME`\nThe deployment type is determined by the current deployment (local maps to dev), or by --type if provided."
73
+ ).configureHelp({ showGlobalOptions: true }).allowExcessArguments(false)
74
+ ).action(async (envVarName, _options, cmd) => {
60
75
  const options = cmd.optsWithGlobals();
61
- const { ctx, deployment } = await (0, import_env2.selectEnvDeployment)(options);
76
+ const { ctx, backend } = await resolveEnvDefaultBackend(options);
62
77
  await (0, import_utils.ensureHasConvexDependency)(ctx, "env default get");
63
- const backend = await resolveDefaultEnvBackend(
64
- ctx,
65
- deployment.deploymentFields
66
- );
67
78
  await (0, import_env.envGet)(ctx, backend, envVarName);
68
79
  });
69
- const envDefaultRemove = new import_extra_typings.Command("remove").alias("rm").alias("unset").arguments("<name>").summary("Unset a default variable").description(
70
- "Unset a default variable: `npx convex env default remove NAME`\nIf the variable doesn't exist, the command doesn't do anything and succeeds.\nThe deployment type is determined by the current deployment (local maps to dev)."
71
- ).configureHelp({ showGlobalOptions: true }).allowExcessArguments(false).action(async (name, _options, cmd) => {
80
+ const envDefaultRemove = addEnvDefaultOptions(
81
+ new import_extra_typings.Command("remove").alias("rm").alias("unset").arguments("<name>").summary("Unset a default variable").description(
82
+ "Unset a default variable: `npx convex env default remove NAME`\nIf the variable doesn't exist, the command doesn't do anything and succeeds.\nThe deployment type is determined by the current deployment (local maps to dev), or by --type if provided."
83
+ ).configureHelp({ showGlobalOptions: true }).allowExcessArguments(false)
84
+ ).action(async (name, _options, cmd) => {
72
85
  const options = cmd.optsWithGlobals();
73
- const { ctx, deployment } = await (0, import_env2.selectEnvDeployment)(options);
86
+ const { ctx, backend } = await resolveEnvDefaultBackend(options);
74
87
  await (0, import_utils.ensureHasConvexDependency)(ctx, "env default remove");
75
- const backend = await resolveDefaultEnvBackend(
76
- ctx,
77
- deployment.deploymentFields
78
- );
79
88
  await (0, import_env.envRemove)(ctx, backend, name);
80
89
  });
81
- const envDefaultList = new import_extra_typings.Command("list").summary("List all default variables").description(
82
- "List all default variables: `npx convex env default list`\nThe deployment type is determined by the current deployment (local maps to dev)."
83
- ).configureHelp({ showGlobalOptions: true }).allowExcessArguments(false).action(async (_options, cmd) => {
90
+ const envDefaultList = addEnvDefaultOptions(
91
+ new import_extra_typings.Command("list").summary("List all default variables").description(
92
+ "List all default variables: `npx convex env default list`\nThe deployment type is determined by the current deployment (local maps to dev), or by --type if provided."
93
+ ).configureHelp({ showGlobalOptions: true }).allowExcessArguments(false)
94
+ ).action(async (_options, cmd) => {
84
95
  const options = cmd.optsWithGlobals();
85
- const { ctx, deployment } = await (0, import_env2.selectEnvDeployment)(options);
96
+ const { ctx, backend } = await resolveEnvDefaultBackend(options);
86
97
  await (0, import_utils.ensureHasConvexDependency)(ctx, "env default list");
87
- const backend = await resolveDefaultEnvBackend(
88
- ctx,
89
- deployment.deploymentFields
90
- );
91
98
  await (0, import_env.envList)(ctx, backend);
92
99
  });
93
100
  const envDefault = new import_extra_typings.Command("default").summary("Manage project-level default environment variables").description(
94
- "Manage default environment variables for your project.\n\nThe default environment variables read and written to by this command are the ones for the deployment type of the current deployment (i.e. dev in most cases).\n\n Set a default variable: `npx convex env default set NAME 'value'`\n Unset a default variable: `npx convex env default remove NAME`\n List all default variables: `npx convex env default list`\n Print a default variable's value: `npx convex env default get NAME`\n\n"
101
+ "Manage default environment variables for your project.\n\nThe default environment variables read and written to by this command are the ones for the deployment type of the current deployment (i.e. dev in most cases), unless --type is provided.\n\n Set a default variable: `npx convex env default set NAME 'value'`\n Unset a default variable: `npx convex env default remove NAME`\n List all default variables: `npx convex env default list`\n Print a default variable's value: `npx convex env default get NAME`\n\n"
95
102
  ).addCommand(envDefaultSet).addCommand(envDefaultGet).addCommand(envDefaultRemove).addCommand(envDefaultList).helpCommand(false);
96
- async function resolveDefaultEnvBackend(ctx, deploymentFields) {
103
+ async function resolveEnvDefaultBackend(options) {
104
+ const dtypeOverride = normalizeTypeOption(options.type);
105
+ if (options.project !== void 0) {
106
+ const parsedProject = parseProjectOption(options.project);
107
+ if (parsedProject === null) {
108
+ const ctx3 = await (0, import_context.oneoffContext)(options);
109
+ return await ctx3.crash({
110
+ exitCode: 1,
111
+ errorType: "fatal",
112
+ printedMessage: "error: --project must be `team-slug:project-slug` or `project-slug`."
113
+ });
114
+ }
115
+ if (dtypeOverride === void 0) {
116
+ const ctx3 = await (0, import_context.oneoffContext)(options);
117
+ return await ctx3.crash({
118
+ exitCode: 1,
119
+ errorType: "fatal",
120
+ printedMessage: "error: --project requires --type to also be set."
121
+ });
122
+ }
123
+ let ctx2;
124
+ let resolved;
125
+ if (parsedProject.kind === "teamAndProject") {
126
+ ctx2 = await (0, import_context.oneoffContext)(options);
127
+ resolved = {
128
+ teamSlug: parsedProject.teamSlug,
129
+ projectSlug: parsedProject.projectSlug
130
+ };
131
+ } else {
132
+ const selected = await (0, import_env2.selectEnvDeployment)(options);
133
+ ctx2 = selected.ctx;
134
+ if (selected.deployment.deploymentFields === null) {
135
+ return await ctx2.crash({
136
+ exitCode: 1,
137
+ errorType: "fatal",
138
+ printedMessage: "error: --project <project-slug> requires a current cloud deployment to infer the team from. Use `team-slug:project-slug` to specify the team explicitly."
139
+ });
140
+ }
141
+ const { team } = await (0, import_api.fetchTeamAndProject)(
142
+ ctx2,
143
+ selected.deployment.deploymentFields.deploymentName
144
+ );
145
+ resolved = { teamSlug: team, projectSlug: parsedProject.projectSlug };
146
+ }
147
+ const details = await (0, import_deploymentSelection.getProjectDetails)(ctx2, {
148
+ kind: "teamAndProjectSlugs",
149
+ teamSlug: resolved.teamSlug,
150
+ projectSlug: resolved.projectSlug
151
+ });
152
+ return {
153
+ ctx: ctx2,
154
+ backend: (0, import_defaultEnv.defaultEnvBackend)(ctx2, details.id, dtypeOverride)
155
+ };
156
+ }
157
+ const { ctx, deployment } = await (0, import_env2.selectEnvDeployment)(options);
158
+ const backend = await resolveDefaultEnvBackend(
159
+ ctx,
160
+ deployment.deploymentFields,
161
+ dtypeOverride
162
+ );
163
+ return { ctx, backend };
164
+ }
165
+ function normalizeTypeOption(type) {
166
+ if (type === void 0) return void 0;
167
+ if (type === "development") return "dev";
168
+ if (type === "production") return "prod";
169
+ return type;
170
+ }
171
+ function parseProjectOption(value) {
172
+ const parts = value.split(":");
173
+ if (parts.length === 1 && parts[0].length > 0) {
174
+ return { kind: "projectOnly", projectSlug: parts[0] };
175
+ }
176
+ if (parts.length === 2 && parts[0].length > 0 && parts[1].length > 0) {
177
+ return {
178
+ kind: "teamAndProject",
179
+ teamSlug: parts[0],
180
+ projectSlug: parts[1]
181
+ };
182
+ }
183
+ return null;
184
+ }
185
+ async function resolveDefaultEnvBackend(ctx, deploymentFields, dtypeOverride) {
97
186
  if (deploymentFields === null) {
98
187
  return await ctx.crash({
99
188
  exitCode: 1,
@@ -108,7 +197,7 @@ async function resolveDefaultEnvBackend(ctx, deploymentFields) {
108
197
  printedMessage: "Default environment variables are not available for anonymous deployments."
109
198
  });
110
199
  }
111
- const dtype = resolveDefaultEnvDtype(deploymentFields.deploymentType);
200
+ const dtype = dtypeOverride ?? resolveDefaultEnvDtype(deploymentFields.deploymentType);
112
201
  const { projectId } = await (0, import_api.fetchTeamAndProject)(
113
202
  ctx,
114
203
  deploymentFields.deploymentName
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/cli/envDefault.ts"],
4
- "sourcesContent": ["import { Command } from \"@commander-js/extra-typings\";\nimport {\n envGet,\n envList,\n envRemove,\n envSet,\n EnvVarBackend,\n} from \"./lib/env.js\";\nimport { ensureHasConvexDependency } from \"./lib/utils/utils.js\";\nimport { defaultEnvBackend } from \"./lib/defaultEnv.js\";\nimport {\n CloudDeploymentType,\n DeploymentSelectionOptions,\n DeploymentType,\n fetchTeamAndProject,\n} from \"./lib/api.js\";\nimport { Context } from \"../bundler/context.js\";\nimport { selectEnvDeployment } from \"./env.js\";\n\nconst envDefaultSet = new Command(\"set\")\n .usage(\"[options] <name> <value>\")\n .arguments(\"[name] [value]\")\n .summary(\"Set a default variable\")\n .description(\n \"Set default environment variables for your project's deployment type.\\n\\n\" +\n \" npx convex env default set NAME 'value'\\n\" +\n \" npx convex env default set NAME # omit a value to set one interactively\\n\" +\n \" npx convex env default set NAME --from-file value.txt\\n\" +\n \" npx convex env default set --from-file .env.defaults\\n\" +\n \"When setting multiple values, it will refuse all changes if any \" +\n \"variables are already set to different values by default. \" +\n \"Pass --force to overwrite the provided values.\\n\" +\n \"The deployment type is determined by the current deployment (local maps to dev).\\n\",\n )\n .option(\n \"--from-file <file>\",\n \"Read environment variables from a .env file. Without --force, fails if any existing variable has a different value.\",\n )\n .option(\n \"--force\",\n \"When setting multiple variables, overwrite existing environment variable values instead of failing on mismatch.\",\n )\n .configureHelp({ showGlobalOptions: true })\n .allowExcessArguments(false)\n .action(async (name, value, cmdOptions, cmd) => {\n const options = cmd.optsWithGlobals() as DeploymentSelectionOptions;\n const { ctx, deployment } = await selectEnvDeployment(options);\n await ensureHasConvexDependency(ctx, \"env default set\");\n const backend = await resolveDefaultEnvBackend(\n ctx,\n deployment.deploymentFields,\n );\n const didAnything = await envSet(ctx, backend, name, value, cmdOptions);\n if (didAnything === false) {\n cmd.outputHelp({ error: true });\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"error: No environment variables specified to be set.\",\n });\n }\n });\n\nconst envDefaultGet = new Command(\"get\")\n .arguments(\"<name>\")\n .summary(\"Print a default variable's value\")\n .description(\n \"Print a default variable's value: `npx convex env default get NAME`\\n\" +\n \"The deployment type is determined by the current deployment (local maps to dev).\",\n )\n .configureHelp({ showGlobalOptions: true })\n .allowExcessArguments(false)\n .action(async (envVarName, _options, cmd) => {\n const options = cmd.optsWithGlobals() as DeploymentSelectionOptions;\n const { ctx, deployment } = await selectEnvDeployment(options);\n await ensureHasConvexDependency(ctx, \"env default get\");\n const backend = await resolveDefaultEnvBackend(\n ctx,\n deployment.deploymentFields,\n );\n await envGet(ctx, backend, envVarName);\n });\n\nconst envDefaultRemove = new Command(\"remove\")\n .alias(\"rm\")\n .alias(\"unset\")\n .arguments(\"<name>\")\n .summary(\"Unset a default variable\")\n .description(\n \"Unset a default variable: `npx convex env default remove NAME`\\n\" +\n \"If the variable doesn't exist, the command doesn't do anything and succeeds.\\n\" +\n \"The deployment type is determined by the current deployment (local maps to dev).\",\n )\n .configureHelp({ showGlobalOptions: true })\n .allowExcessArguments(false)\n .action(async (name, _options, cmd) => {\n const options = cmd.optsWithGlobals() as DeploymentSelectionOptions;\n const { ctx, deployment } = await selectEnvDeployment(options);\n await ensureHasConvexDependency(ctx, \"env default remove\");\n const backend = await resolveDefaultEnvBackend(\n ctx,\n deployment.deploymentFields,\n );\n await envRemove(ctx, backend, name);\n });\n\nconst envDefaultList = new Command(\"list\")\n .summary(\"List all default variables\")\n .description(\n \"List all default variables: `npx convex env default list`\\n\" +\n \"The deployment type is determined by the current deployment (local maps to dev).\",\n )\n .configureHelp({ showGlobalOptions: true })\n .allowExcessArguments(false)\n .action(async (_options, cmd) => {\n const options = cmd.optsWithGlobals() as DeploymentSelectionOptions;\n const { ctx, deployment } = await selectEnvDeployment(options);\n await ensureHasConvexDependency(ctx, \"env default list\");\n const backend = await resolveDefaultEnvBackend(\n ctx,\n deployment.deploymentFields,\n );\n await envList(ctx, backend);\n });\n\nexport const envDefault = new Command(\"default\")\n .summary(\"Manage project-level default environment variables\")\n .description(\n \"Manage default environment variables for your project.\\n\\n\" +\n \"The default environment variables read and written to by this command are the ones for the deployment type of the current deployment (i.e. dev in most cases).\\n\\n\" +\n \" Set a default variable: `npx convex env default set NAME 'value'`\\n\" +\n \" Unset a default variable: `npx convex env default remove NAME`\\n\" +\n \" List all default variables: `npx convex env default list`\\n\" +\n \" Print a default variable's value: `npx convex env default get NAME`\\n\\n\",\n )\n .addCommand(envDefaultSet)\n .addCommand(envDefaultGet)\n .addCommand(envDefaultRemove)\n .addCommand(envDefaultList)\n .helpCommand(false);\n\nexport async function resolveDefaultEnvBackend(\n ctx: Context,\n deploymentFields: {\n deploymentName: string;\n deploymentType: DeploymentType;\n } | null,\n): Promise<EnvVarBackend> {\n if (deploymentFields === null) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage:\n \"Default environment variables are only available for cloud projects.\",\n });\n }\n if (deploymentFields.deploymentType === \"anonymous\") {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage:\n \"Default environment variables are not available for anonymous deployments.\",\n });\n }\n const dtype = resolveDefaultEnvDtype(deploymentFields.deploymentType);\n const { projectId } = await fetchTeamAndProject(\n ctx,\n deploymentFields.deploymentName,\n );\n return defaultEnvBackend(ctx, projectId, dtype);\n}\n\nfunction resolveDefaultEnvDtype(\n deploymentType: Exclude<DeploymentType, \"anonymous\">,\n): CloudDeploymentType {\n if (deploymentType === \"local\") return \"dev\";\n return deploymentType;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAwB;AACxB,iBAMO;AACP,mBAA0C;AAC1C,wBAAkC;AAClC,iBAKO;AAEP,IAAAA,cAAoC;AAEpC,MAAM,gBAAgB,IAAI,6BAAQ,KAAK,EACpC,MAAM,0BAA0B,EAChC,UAAU,gBAAgB,EAC1B,QAAQ,wBAAwB,EAChC;AAAA,EACC;AASF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC;AAAA,EACC;AAAA,EACA;AACF,EACC,cAAc,EAAE,mBAAmB,KAAK,CAAC,EACzC,qBAAqB,KAAK,EAC1B,OAAO,OAAO,MAAM,OAAO,YAAY,QAAQ;AAC9C,QAAM,UAAU,IAAI,gBAAgB;AACpC,QAAM,EAAE,KAAK,WAAW,IAAI,UAAM,iCAAoB,OAAO;AAC7D,YAAM,wCAA0B,KAAK,iBAAiB;AACtD,QAAM,UAAU,MAAM;AAAA,IACpB;AAAA,IACA,WAAW;AAAA,EACb;AACA,QAAM,cAAc,UAAM,mBAAO,KAAK,SAAS,MAAM,OAAO,UAAU;AACtE,MAAI,gBAAgB,OAAO;AACzB,QAAI,WAAW,EAAE,OAAO,KAAK,CAAC;AAC9B,WAAO,MAAM,IAAI,MAAM;AAAA,MACrB,UAAU;AAAA,M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M,iCAAoB,OAAO;AAC7D,YAAM,wCAA0B,KAAK,kBAAkB;AACvD,QAAM,UAAU,MAAM;AAAA,IACpB;AAAA,IACA,WAAW;AAAA,EACb;AACA,YAAM,oBAAQ,KAAK,OAAO;AAC5B,CAAC;AAEI,MAAM,aAAa,IAAI,6BAAQ,SAAS,EAC5C,QAAQ,oDAAoD,EAC5D;AAAA,EACC;AAMF,EACC,WAAW,aAAa,EACxB,WAAW,aAAa,EACxB,WAAW,gBAAgB,EAC3B,WAAW,cAAc,EACzB,YAAY,KAAK;AAEpB,eAAsB,yBACpB,KACA,kBAIwB;AACxB,MAAI,qBAAqB,MAAM;AAC7B,WAAO,MAAM,IAAI,MAAM;AAAA,MACrB,UAAU;AAAA,MACV,WAAW;AAAA,MACX,gBACE;AAAA,IACJ,CAAC;AAAA,EACH;AACA,MAAI,iBAAiB,mBAAmB,aAAa;AACnD,WAAO,MAAM,IAAI,MAAM;AAAA,MACrB,UAAU;AAAA,MACV,WAAW;AAAA,MACX,gBACE;AAAA,IACJ,CAAC;AAAA,EACH;AACA,QAAM,QAAQ,uBAAuB,iBAAiB,cAAc;AACpE,QAAM,EAAE,UAAU,IAAI,UAAM;AAAA,IAC1B;AAAA,IACA,iBAAiB;AAAA,EACnB;AACA,aAAO,qCAAkB,KAAK,WAAW,KAAK;AAChD;AAEA,SAAS,uBACP,gBACqB;AACrB,MAAI,mBAAmB,QAAS,QAAO;AACvC,SAAO;AACT;",
6
- "names": ["import_env"]
4
+ "sourcesContent": ["import { Command, Option } from \"@commander-js/extra-typings\";\nimport {\n envGet,\n envList,\n envRemove,\n envSet,\n EnvVarBackend,\n} from \"./lib/env.js\";\nimport { ensureHasConvexDependency } from \"./lib/utils/utils.js\";\nimport { defaultEnvBackend } from \"./lib/defaultEnv.js\";\nimport {\n CloudDeploymentType,\n DeploymentSelectionOptions,\n DeploymentType,\n fetchTeamAndProject,\n} from \"./lib/api.js\";\nimport { Context, oneoffContext } from \"../bundler/context.js\";\nimport { selectEnvDeployment } from \"./env.js\";\nimport { getProjectDetails } from \"./lib/deploymentSelection.js\";\n\ntype EnvDefaultExtraOptions = {\n type?: string;\n project?: string;\n};\n\nfunction addEnvDefaultOptions<T extends Command<any, any>>(cmd: T): T {\n return cmd\n .addOption(\n new Option(\n \"--type <type>\",\n \"Manage default env vars for the given deployment type instead of inferring from the current deployment.\",\n ),\n )\n .addOption(\n new Option(\n \"--project <project>\",\n \"Select a project manually. Accepts `team-slug:project-slug` or just `project-slug` (team inferred from your current project). Requires --type.\",\n ),\n ) as T;\n}\n\nconst envDefaultSet = addEnvDefaultOptions(\n new Command(\"set\")\n .usage(\"[options] <name> <value>\")\n .arguments(\"[name] [value]\")\n .summary(\"Set a default variable\")\n .description(\n \"Set default environment variables for your project's deployment type.\\n\\n\" +\n \" npx convex env default set NAME 'value'\\n\" +\n \" npx convex env default set NAME # omit a value to set one interactively\\n\" +\n \" npx convex env default set NAME --from-file value.txt\\n\" +\n \" npx convex env default set --from-file .env.defaults\\n\" +\n \"When setting multiple values, it will refuse all changes if any \" +\n \"variables are already set to different values by default. \" +\n \"Pass --force to overwrite the provided values.\\n\" +\n \"The deployment type is determined by the current deployment (local maps to dev), or by --type if provided.\\n\",\n )\n .option(\n \"--from-file <file>\",\n \"Read environment variables from a .env file. Without --force, fails if any existing variable has a different value.\",\n )\n .option(\n \"--force\",\n \"When setting multiple variables, overwrite existing environment variable values instead of failing on mismatch.\",\n )\n .configureHelp({ showGlobalOptions: true })\n .allowExcessArguments(false),\n).action(async (name, value, cmdOptions, cmd) => {\n const options = cmd.optsWithGlobals() as DeploymentSelectionOptions &\n EnvDefaultExtraOptions;\n const { ctx, backend } = await resolveEnvDefaultBackend(options);\n await ensureHasConvexDependency(ctx, \"env default set\");\n const didAnything = await envSet(ctx, backend, name, value, cmdOptions);\n if (didAnything === false) {\n cmd.outputHelp({ error: true });\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"error: No environment variables specified to be set.\",\n });\n }\n});\n\nconst envDefaultGet = addEnvDefaultOptions(\n new Command(\"get\")\n .arguments(\"<name>\")\n .summary(\"Print a default variable's value\")\n .description(\n \"Print a default variable's value: `npx convex env default get NAME`\\n\" +\n \"The deployment type is determined by the current deployment (local maps to dev), or by --type if provided.\",\n )\n .configureHelp({ showGlobalOptions: true })\n .allowExcessArguments(false),\n).action(async (envVarName, _options, cmd) => {\n const options = cmd.optsWithGlobals() as DeploymentSelectionOptions &\n EnvDefaultExtraOptions;\n const { ctx, backend } = await resolveEnvDefaultBackend(options);\n await ensureHasConvexDependency(ctx, \"env default get\");\n await envGet(ctx, backend, envVarName);\n});\n\nconst envDefaultRemove = addEnvDefaultOptions(\n new Command(\"remove\")\n .alias(\"rm\")\n .alias(\"unset\")\n .arguments(\"<name>\")\n .summary(\"Unset a default variable\")\n .description(\n \"Unset a default variable: `npx convex env default remove NAME`\\n\" +\n \"If the variable doesn't exist, the command doesn't do anything and succeeds.\\n\" +\n \"The deployment type is determined by the current deployment (local maps to dev), or by --type if provided.\",\n )\n .configureHelp({ showGlobalOptions: true })\n .allowExcessArguments(false),\n).action(async (name, _options, cmd) => {\n const options = cmd.optsWithGlobals() as DeploymentSelectionOptions &\n EnvDefaultExtraOptions;\n const { ctx, backend } = await resolveEnvDefaultBackend(options);\n await ensureHasConvexDependency(ctx, \"env default remove\");\n await envRemove(ctx, backend, name);\n});\n\nconst envDefaultList = addEnvDefaultOptions(\n new Command(\"list\")\n .summary(\"List all default variables\")\n .description(\n \"List all default variables: `npx convex env default list`\\n\" +\n \"The deployment type is determined by the current deployment (local maps to dev), or by --type if provided.\",\n )\n .configureHelp({ showGlobalOptions: true })\n .allowExcessArguments(false),\n).action(async (_options, cmd) => {\n const options = cmd.optsWithGlobals() as DeploymentSelectionOptions &\n EnvDefaultExtraOptions;\n const { ctx, backend } = await resolveEnvDefaultBackend(options);\n await ensureHasConvexDependency(ctx, \"env default list\");\n await envList(ctx, backend);\n});\n\nexport const envDefault = new Command(\"default\")\n .summary(\"Manage project-level default environment variables\")\n .description(\n \"Manage default environment variables for your project.\\n\\n\" +\n \"The default environment variables read and written to by this command are the ones for the deployment type of the current deployment (i.e. dev in most cases), unless --type is provided.\\n\\n\" +\n \" Set a default variable: `npx convex env default set NAME 'value'`\\n\" +\n \" Unset a default variable: `npx convex env default remove NAME`\\n\" +\n \" List all default variables: `npx convex env default list`\\n\" +\n \" Print a default variable's value: `npx convex env default get NAME`\\n\\n\",\n )\n .addCommand(envDefaultSet)\n .addCommand(envDefaultGet)\n .addCommand(envDefaultRemove)\n .addCommand(envDefaultList)\n .helpCommand(false);\n\ntype ParsedProjectOption =\n | { kind: \"teamAndProject\"; teamSlug: string; projectSlug: string }\n | { kind: \"projectOnly\"; projectSlug: string };\n\nasync function resolveEnvDefaultBackend(\n options: DeploymentSelectionOptions & EnvDefaultExtraOptions,\n): Promise<{ ctx: Context; backend: EnvVarBackend }> {\n const dtypeOverride = normalizeTypeOption(options.type);\n\n if (options.project !== undefined) {\n const parsedProject = parseProjectOption(options.project);\n if (parsedProject === null) {\n const ctx = await oneoffContext(options);\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage:\n \"error: --project must be `team-slug:project-slug` or `project-slug`.\",\n });\n }\n if (dtypeOverride === undefined) {\n const ctx = await oneoffContext(options);\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"error: --project requires --type to also be set.\",\n });\n }\n\n let ctx: Context;\n let resolved: { teamSlug: string; projectSlug: string };\n if (parsedProject.kind === \"teamAndProject\") {\n ctx = await oneoffContext(options);\n resolved = {\n teamSlug: parsedProject.teamSlug,\n projectSlug: parsedProject.projectSlug,\n };\n } else {\n const selected = await selectEnvDeployment(options);\n ctx = selected.ctx;\n if (selected.deployment.deploymentFields === null) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage:\n \"error: --project <project-slug> requires a current cloud deployment to infer the team from. Use `team-slug:project-slug` to specify the team explicitly.\",\n });\n }\n const { team } = await fetchTeamAndProject(\n ctx,\n selected.deployment.deploymentFields.deploymentName,\n );\n resolved = { teamSlug: team, projectSlug: parsedProject.projectSlug };\n }\n\n const details = await getProjectDetails(ctx, {\n kind: \"teamAndProjectSlugs\",\n teamSlug: resolved.teamSlug,\n projectSlug: resolved.projectSlug,\n });\n return {\n ctx,\n backend: defaultEnvBackend(ctx, details.id, dtypeOverride),\n };\n }\n\n const { ctx, deployment } = await selectEnvDeployment(options);\n const backend = await resolveDefaultEnvBackend(\n ctx,\n deployment.deploymentFields,\n dtypeOverride,\n );\n return { ctx, backend };\n}\n\nfunction normalizeTypeOption(\n type: string | undefined,\n): CloudDeploymentType | undefined {\n if (type === undefined) return undefined;\n if (type === \"development\") return \"dev\";\n if (type === \"production\") return \"prod\";\n return type as CloudDeploymentType;\n}\n\nfunction parseProjectOption(value: string): ParsedProjectOption | null {\n const parts = value.split(\":\");\n if (parts.length === 1 && parts[0].length > 0) {\n return { kind: \"projectOnly\", projectSlug: parts[0] };\n }\n if (parts.length === 2 && parts[0].length > 0 && parts[1].length > 0) {\n return {\n kind: \"teamAndProject\",\n teamSlug: parts[0],\n projectSlug: parts[1],\n };\n }\n return null;\n}\n\nexport async function resolveDefaultEnvBackend(\n ctx: Context,\n deploymentFields: {\n deploymentName: string;\n deploymentType: DeploymentType;\n } | null,\n dtypeOverride?: CloudDeploymentType,\n): Promise<EnvVarBackend> {\n if (deploymentFields === null) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage:\n \"Default environment variables are only available for cloud projects.\",\n });\n }\n if (deploymentFields.deploymentType === \"anonymous\") {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage:\n \"Default environment variables are not available for anonymous deployments.\",\n });\n }\n const dtype =\n dtypeOverride ?? resolveDefaultEnvDtype(deploymentFields.deploymentType);\n const { projectId } = await fetchTeamAndProject(\n ctx,\n deploymentFields.deploymentName,\n );\n return defaultEnvBackend(ctx, projectId, dtype);\n}\n\nfunction resolveDefaultEnvDtype(\n deploymentType: Exclude<DeploymentType, \"anonymous\">,\n): CloudDeploymentType {\n if (deploymentType === \"local\") return \"dev\";\n return deploymentType;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAgC;AAChC,iBAMO;AACP,mBAA0C;AAC1C,wBAAkC;AAClC,iBAKO;AACP,qBAAuC;AACvC,IAAAA,cAAoC;AACpC,iCAAkC;AAOlC,SAAS,qBAAkD,KAAW;AACpE,SAAO,IACJ;AAAA,IACC,IAAI;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF,EACC;AAAA,IACC,IAAI;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACJ;AAEA,MAAM,gBAAgB;AAAA,EACpB,IAAI,6BAAQ,KAAK,EACd,MAAM,0BAA0B,EAChC,UAAU,gBAAgB,EAC1B,QAAQ,wBAAwB,EAChC;AAAA,IACC;AAAA,EASF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC;AAAA,IACC;AAAA,IACA;AAAA,EACF,EACC,cAAc,EAAE,mBAAmB,KAAK,CAAC,EACzC,qBAAqB,KAAK;AAC/B,EAAE,OAAO,OAAO,MAAM,OAAO,YAAY,QAAQ;AAC/C,QAAM,UAAU,IAAI,gBAAgB;AAEpC,QAAM,EAAE,KAAK,QAAQ,IAAI,MAAM,yBAAyB,OAAO;AAC/D,YAAM,wCAA0B,KAAK,iBAAiB;AACtD,QAAM,cAAc,UAAM,mBAAO,KAAK,SAAS,MAAM,OAAO,UAAU;AACtE,MAAI,gBAAgB,OAAO;AACzB,QAAI,WAAW,EAAE,OAAO,KAAK,CAAC;AAC9B,WAAO,MAAM,IAAI,MAAM;AAAA,MACrB,UAAU;AAAA,MACV,WAAW;AAAA,MACX,gBAAgB;AAAA,IAClB,CAAC;AAAA,EACH;AACF,CAAC;AAED,MAAM,gBAAgB;AAAA,EACpB,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B,iBAAiB,cAAc;AACzE,QAAM,EAAE,UAAU,IAAI,UAAM;AAAA,IAC1B;AAAA,IACA,iBAAiB;AAAA,EACnB;AACA,aAAO,qCAAkB,KAAK,WAAW,KAAK;AAChD;AAEA,SAAS,uBACP,gBACqB;AACrB,MAAI,mBAAmB,QAAS,QAAO;AACvC,SAAO;AACT;",
6
+ "names": ["import_env", "ctx"]
7
7
  }
@@ -61,7 +61,7 @@ import_extra_typings.Command.prototype.addDeploymentSelectionOptions = function(
61
61
  ).addOption(
62
62
  new import_extra_typings.Option(
63
63
  "--deployment <deployment>",
64
- action + " a specific deployment. Accepts:\n\u2022 a deployment name (e.g. joyful-capybara-123)\u2022 a deployment reference (e.g. dev/james, staging)\n\u2022 `dev` (for your personal dev deployment)\n\u2022 `prod` (for your project\u2019s default production deployment)\n\u2022 `local` (for your local dev deployment).\nYou can also select deployments in other projects with `project-slug:reference` or `team-slug:project-slug:reference`."
64
+ action + " a specific deployment. Accepts:\n\u2022 a deployment name (e.g. joyful-capybara-123)\n\u2022 a deployment reference (e.g. dev/james, staging)\n\u2022 `dev` (for your personal dev deployment)\n\u2022 `prod` (for your project\u2019s default production deployment)\n\u2022 `local` (for your local dev deployment).\nYou can also select deployments in other projects with `project-slug:reference` or `team-slug:project-slug:reference`."
65
65
  ).conflicts(["--prod", "--preview-name", "--deployment-name", "--url"])
66
66
  ).addOption(
67
67
  new import_extra_typings.Option(
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/cli/lib/command.ts"],
4
- "sourcesContent": ["import { Command, Option, OptionValues } from \"@commander-js/extra-typings\";\nimport { OneoffCtx } from \"../../bundler/context.js\";\nimport { LogMode } from \"./logs.js\";\nimport {\n CONVEX_DEPLOYMENT_ENV_VAR_NAME,\n CONVEX_SELF_HOSTED_ADMIN_KEY_VAR_NAME,\n CONVEX_SELF_HOSTED_URL_VAR_NAME,\n parseInteger,\n parsePositiveInteger,\n} from \"./utils/utils.js\";\nimport { INLINE_QUERY_DESCRIPTION } from \"./runTestFunction.js\";\n\ndeclare module \"@commander-js/extra-typings\" {\n interface Command<Args extends any[] = [], Opts extends OptionValues = {}> {\n /**\n * For a command that talks to the configured dev deployment by default,\n * add flags for talking to prod, preview, or other deployment in the same\n * project.\n *\n * These flags are added to the end of `command` (ordering matters for `--help`\n * output). `action` should look like \"Import data into\" because it is prefixed\n * onto help strings.\n *\n * The options can be passed to `deploymentSelectionFromOptions`.\n *\n * NOTE: This method only exists at runtime if this file is imported.\n * To help avoid this bug, this method takes in an `ActionDescription` which\n * can only be constructed via `actionDescription` from this file.\n *\n * @param action - The action description\n * @param options - Optional settings\n * @param options.showUrlHelp - If true, show the --url option in help output\n */\n addDeploymentSelectionOptions(\n action: ActionDescription,\n options?: { showUrlHelp?: boolean },\n ): Command<\n Args,\n Opts & {\n envFile?: string;\n url?: string;\n adminKey?: string;\n prod?: boolean;\n previewName?: string;\n deploymentName?: string;\n deployment?: string;\n }\n >;\n\n /**\n * Adds options for the `deploy` command.\n */\n addDeployOptions(): Command<\n Args,\n Opts & {\n verbose?: boolean;\n dryRun?: boolean;\n yes?: boolean;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: \"enable\" | \"disable\";\n cmd?: string;\n cmdUrlEnvVarName?: string;\n debugBundlePath?: string;\n debug?: boolean;\n writePushRequest?: string;\n liveComponentSources?: boolean;\n }\n >;\n\n /**\n * Adds options for `self-host` subcommands.\n */\n addSelfHostOptions(): Command<\n Args,\n Opts & {\n url?: string;\n adminKey?: string;\n env?: string;\n }\n >;\n\n /**\n * Adds options and arguments for the `run` command.\n */\n addRunOptions(): Command<\n [...Args, string | undefined, string | undefined],\n Opts & {\n watch?: boolean;\n push?: boolean;\n identity?: string;\n inlineQuery?: string;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: \"enable\" | \"disable\";\n component?: string;\n liveComponentSources?: boolean;\n }\n >;\n\n /**\n * Adds options for the `import` command.\n */\n addImportOptions(): Command<\n [...Args, string],\n Opts & {\n table?: string;\n format?: \"csv\" | \"jsonLines\" | \"jsonArray\" | \"zip\";\n replace?: boolean;\n append?: boolean;\n replaceAll?: boolean;\n yes?: boolean;\n component?: string;\n }\n >;\n\n /**\n * Adds options for the `export` command.\n */\n addExportOptions(): Command<\n Args,\n Opts & {\n path: string;\n includeFileStorage?: boolean;\n }\n >;\n\n /**\n * Adds options for the `data` command.\n */\n addDataOptions(): Command<\n [...Args, string | undefined],\n Opts & {\n limit: number;\n order: \"asc\" | \"desc\";\n component?: string;\n format?: \"json\" | \"jsonArray\" | \"jsonLines\" | \"jsonl\" | \"pretty\";\n }\n >;\n\n /**\n * Adds options for the `logs` command.\n */\n addLogsOptions(): Command<\n Args,\n Opts & {\n history: number;\n success: boolean;\n jsonl: boolean;\n }\n >;\n\n /**\n * Adds options for the `network-test` command.\n */\n addNetworkTestOptions(): Command<\n Args,\n Opts & {\n timeout?: string;\n ipFamily?: string;\n speedTest?: boolean;\n }\n >;\n }\n}\n\nCommand.prototype.addDeploymentSelectionOptions = function (\n action: ActionDescription,\n options?: { showUrlHelp?: boolean },\n) {\n const urlOption = new Option(\n \"--url <url>\",\n options?.showUrlHelp\n ? action + \" the deployment at the given URL.\"\n : undefined,\n ).conflicts([\n \"--prod\",\n \"--preview-name\",\n \"--deployment-name\",\n \"--deployment\",\n ]);\n if (!options?.showUrlHelp) {\n urlOption.hideHelp();\n }\n return this.addOption(urlOption)\n .addOption(new Option(\"--admin-key <adminKey>\").hideHelp())\n .addOption(\n new Option(\n \"--prod\",\n action + \" this project's default production deployment.\",\n ).conflicts([\n \"--preview-name\",\n \"--deployment-name\",\n \"--url\",\n \"--deployment\",\n ]),\n )\n .addOption(\n new Option(\n \"--preview-name <previewName>\",\n action + \" the preview deployment with the given name.\",\n )\n .conflicts([\"--prod\", \"--deployment-name\", \"--url\", \"--deployment\"])\n .hideHelp(),\n )\n .addOption(\n new Option(\n \"--deployment-name <deploymentName>\",\n action + \" the specified deployment.\",\n )\n .conflicts([\"--prod\", \"--preview-name\", \"--url\", \"--deployment\"])\n .hideHelp(),\n )\n .addOption(\n new Option(\n \"--deployment <deployment>\",\n action +\n \" a specific deployment. Accepts:\\n\" +\n \"\u2022 a deployment name (e.g. joyful-capybara-123)\" +\n \"\u2022 a deployment reference (e.g. dev/james, staging)\\n\" +\n \"\u2022 `dev` (for your personal dev deployment)\\n\" +\n \"\u2022 `prod` (for your project\u2019s default production deployment)\\n\" +\n \"\u2022 `local` (for your local dev deployment).\" +\n \"\\nYou can also select deployments in other projects with `project-slug:reference` or `team-slug:project-slug:reference`.\",\n ).conflicts([\"--prod\", \"--preview-name\", \"--deployment-name\", \"--url\"]),\n )\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 ).hideHelp(),\n ) as any;\n};\n\ndeclare const tag: unique symbol;\ntype ActionDescription = string & { readonly [tag]: \"noop\" };\nexport function actionDescription(action: string): ActionDescription {\n return action as any;\n}\n\nexport async function normalizeDevOptions(\n ctx: OneoffCtx,\n cmdOptions: {\n verbose?: boolean;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents?: boolean;\n codegen: \"enable\" | \"disable\";\n once?: boolean;\n untilSuccess: boolean;\n start?: string;\n runSh?: string;\n run?: string | undefined;\n runComponent?: string;\n tailLogs?: string | true;\n traceEvents: boolean;\n debugBundlePath?: string | undefined;\n debugNodeApis?: boolean;\n liveComponentSources?: boolean;\n pushAllModules?: boolean;\n while?: string;\n },\n): Promise<{\n verbose: boolean;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: boolean;\n once: boolean;\n untilSuccess: boolean;\n run?:\n | { kind: \"function\"; name: string; component?: string | undefined }\n | { kind: \"shell\"; command: string }\n | undefined;\n tailLogs: LogMode;\n traceEvents: boolean;\n debugBundlePath?: string | undefined;\n debugNodeApis: boolean;\n liveComponentSources: boolean;\n pushAllModules: boolean;\n}> {\n if (cmdOptions.runComponent && !cmdOptions.run) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"Can't specify `--run-component` option without `--run`\",\n });\n }\n\n if (cmdOptions.debugBundlePath !== undefined && !cmdOptions.once) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"`--debug-bundle-path` can only be used with `--once`.\",\n });\n }\n if (cmdOptions.debugNodeApis && !cmdOptions.once) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"`--debug-node-apis` can only be used with `--once`.\",\n });\n }\n\n return {\n verbose: !!cmdOptions.verbose,\n typecheck: cmdOptions.typecheck,\n typecheckComponents: !!cmdOptions.typecheckComponents,\n codegen: cmdOptions.codegen === \"enable\",\n once: !!cmdOptions.once,\n untilSuccess: cmdOptions.untilSuccess,\n run:\n cmdOptions.run !== undefined\n ? {\n kind: \"function\",\n name: cmdOptions.run,\n component: cmdOptions.runComponent,\n }\n : (cmdOptions.start ?? cmdOptions.runSh) !== undefined\n ? {\n kind: \"shell\",\n command: (cmdOptions.start ?? cmdOptions.runSh)!,\n }\n : undefined,\n tailLogs:\n typeof cmdOptions.tailLogs === \"string\"\n ? (cmdOptions.tailLogs as LogMode)\n : \"pause-on-deploy\",\n traceEvents: cmdOptions.traceEvents,\n debugBundlePath: cmdOptions.debugBundlePath,\n debugNodeApis: !!cmdOptions.debugNodeApis,\n liveComponentSources: !!cmdOptions.liveComponentSources,\n pushAllModules: !!cmdOptions.pushAllModules,\n };\n}\n\nCommand.prototype.addDeployOptions = function () {\n return this.option(\"-v, --verbose\", \"Show full listing of changes\")\n .option(\n \"--dry-run\",\n \"Print out the generated configuration without deploying to your Convex deployment\",\n )\n .addOption(\n new Option(\n \"-y, --yes\",\n \"Skip confirmation prompt when running interactively. Warning: this deploys to PRODUCTION. To deploy to your current dev environment, run npx convex dev --once\",\n ).hideHelp(),\n )\n .addOption(\n new Option(\n \"--typecheck <mode>\",\n `Whether to check TypeScript files with \\`tsc --noEmit\\` before deploying.`,\n )\n .choices([\"enable\", \"try\", \"disable\"] as const)\n .default(\"try\" as const),\n )\n .option(\n \"--typecheck-components\",\n \"Check TypeScript files within component implementations with `tsc --noEmit`.\",\n false,\n )\n .addOption(\n new Option(\n \"--codegen <mode>\",\n \"Whether to regenerate code in `convex/_generated/` before pushing.\",\n )\n .choices([\"enable\", \"disable\"] as const)\n .default(\"enable\" as const),\n )\n .addOption(\n new Option(\n \"--cmd <command>\",\n \"Command to run as part of deploying your app (e.g. `vite build`). This command can depend on the environment variables specified in `--cmd-url-env-var-name` being set.\",\n ),\n )\n .addOption(\n new Option(\n \"--cmd-url-env-var-name <name>\",\n \"Environment variable name to set Convex deployment URL (e.g. `VITE_CONVEX_URL`) when using `--cmd`\",\n ),\n )\n .addOption(new Option(\"--debug-bundle-path <path>\").hideHelp())\n .addOption(new Option(\"--debug\").hideHelp())\n .addOption(new Option(\"--write-push-request <writePushRequest>\").hideHelp())\n .addOption(new Option(\"--live-component-sources\").hideHelp())\n .addOption(\n new Option(\n \"--push-all-modules\",\n \"Push all modules without checking for unchanged module hashes from the server\",\n )\n .default(false)\n .hideHelp(),\n );\n};\n\nCommand.prototype.addSelfHostOptions = function () {\n return this.option(\n \"--admin-key <adminKey>\",\n `An admin key for the deployment. Can alternatively be set as \\`${CONVEX_SELF_HOSTED_ADMIN_KEY_VAR_NAME}\\` environment variable.`,\n )\n .option(\n \"--url <url>\",\n `The url of the deployment. Can alternatively be set as \\`${CONVEX_SELF_HOSTED_URL_VAR_NAME}\\` environment variable.`,\n )\n .option(\n \"--env <env>\",\n `Path to a custom file of environment variables, containing \\`${CONVEX_SELF_HOSTED_URL_VAR_NAME}\\` and \\`${CONVEX_SELF_HOSTED_ADMIN_KEY_VAR_NAME}\\`.`,\n );\n};\n\nCommand.prototype.addRunOptions = function () {\n return (\n this.argument(\n \"[functionName]\",\n \"identifier of the function to run, like `listMessages` or `dir/file:myFunction`\",\n )\n .argument(\n \"[args]\",\n \"JSON-formatted arguments object to pass to the function.\",\n )\n .option(\n \"-w, --watch\",\n \"Watch a query, printing its result if the underlying data changes. Given function must be a query.\",\n )\n .addOption(\n new Option(\n \"--inline-query <query>\",\n INLINE_QUERY_DESCRIPTION,\n ).conflicts(\"--watch\"),\n )\n .option(\"--push\", \"Push code to deployment before running the function.\")\n .addOption(\n new Option(\n \"--identity <identity>\",\n 'JSON-formatted UserIdentity object, e.g. \\'{ name: \"John\", address: \"0x123\" }\\'',\n ),\n )\n // For backwards compatibility we still support --no-push which is a noop\n .addOption(new Option(\"--no-push\").hideHelp())\n // Options for the deploy that --push does\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 \"--typecheck-components\",\n \"Check TypeScript files within component implementations with `tsc --noEmit`.\",\n false,\n )\n .addOption(\n new Option(\n \"--codegen <mode>\",\n \"Regenerate code in `convex/_generated/`\",\n )\n .choices([\"enable\", \"disable\"] as const)\n .default(\"enable\" as const),\n )\n .addOption(\n new Option(\n \"--component <path>\",\n \"Path to the component in the component tree defined in convex.config.ts.\",\n ),\n )\n .addOption(new Option(\"--live-component-sources\").hideHelp())\n );\n};\n\nCommand.prototype.addImportOptions = function () {\n return this.argument(\"<path>\", \"Path to the input file\")\n .addOption(\n new Option(\n \"--table <table>\",\n \"Destination table name. Required if format is csv, jsonLines, or jsonArray. Not supported if format is zip.\",\n ),\n )\n .addOption(\n new Option(\n \"--replace\",\n \"Replace all existing data in any of the imported tables\",\n )\n .conflicts(\"--append\")\n .conflicts(\"--replace-all\"),\n )\n .addOption(\n new Option(\"--append\", \"Append imported data to any existing tables\")\n .conflicts(\"--replace-all\")\n .conflicts(\"--replace\"),\n )\n .addOption(\n new Option(\n \"--replace-all\",\n \"Replace all existing data in the deployment with the imported tables,\\n\" +\n \" deleting tables that don't appear in the import file or the schema,\\n\" +\n \" and clearing tables that appear in the schema but not in the import file\",\n )\n .conflicts(\"--append\")\n .conflicts(\"--replace\"),\n )\n .option(\n \"-y, --yes\",\n \"Skip confirmation prompt when import leads to deleting existing documents\",\n )\n .addOption(\n new Option(\n \"--format <format>\",\n \"Input file format. This flag is only required if the filename is missing an extension.\\n\" +\n \"- CSV files must have a header, and each row's entries are interpreted either as a (floating point) number or a string.\\n\" +\n \"- JSON files must be an array of JSON objects.\\n\" +\n \"- JSONLines files must have a JSON object per line.\\n\" +\n \"- ZIP files must have one directory per table, containing <table>/documents.jsonl. Snapshot exports from the Convex dashboard have this format.\",\n ).choices([\"csv\", \"jsonLines\", \"jsonArray\", \"zip\"]),\n )\n .addOption(\n new Option(\n \"--component <path>\",\n \"Path to the component in the component tree defined in convex.config.ts.\",\n ),\n );\n};\n\nCommand.prototype.addExportOptions = function () {\n return this.requiredOption(\n \"--path <zipFilePath>\",\n \"Exports data into a ZIP file at this path, which may be a directory or unoccupied .zip path\",\n ).addOption(\n new Option(\n \"--include-file-storage\",\n \"Includes stored files (https://dashboard.convex.dev/deployment/files) in a _storage folder within the ZIP file\",\n ),\n );\n};\n\nCommand.prototype.addDataOptions = function () {\n return this.addOption(\n new Option(\n \"--limit <n>\",\n \"List only the `n` the most recently created documents.\",\n )\n .default(100)\n .argParser(parsePositiveInteger),\n )\n .addOption(\n new Option(\n \"--order <choice>\",\n \"Order the documents by their `_creationTime`.\",\n )\n .choices([\"asc\", \"desc\"])\n .default(\"desc\"),\n )\n .addOption(\n new Option(\n \"--component <path>\",\n \"Path to the component in the component tree defined in convex.config.ts.\",\n ),\n )\n .addOption(\n new Option(\n \"--format <format>\",\n \"Format to print the data in. This flag is only required if the filename is missing an extension.\\n\" +\n \"- jsonArray (aka json): print the data as a JSON array of objects.\\n\" +\n \"- jsonLines (aka jsonl): print the data as a JSON object per line.\\n\" +\n \"- pretty: print the data in a human-readable format.\",\n ).choices([\"jsonArray\", \"json\", \"jsonLines\", \"jsonl\", \"pretty\"]),\n )\n .argument(\"[table]\", \"If specified, list documents in this table.\");\n};\n\nCommand.prototype.addLogsOptions = function () {\n return this.option(\n \"--history [n]\",\n \"Show `n` most recent logs. Defaults to showing all available logs.\",\n parseInteger,\n )\n .option(\n \"--success\",\n \"Print a log line for every successful function execution\",\n false,\n )\n .option(\"--jsonl\", \"Output raw log events as JSONL\", false);\n};\n\nCommand.prototype.addNetworkTestOptions = function () {\n return this.addOption(\n new Option(\n \"--timeout <timeout>\",\n \"Timeout in seconds for the network test (default: 30).\",\n ),\n )\n .addOption(\n new Option(\n \"--ip-family <ipFamily>\",\n \"IP family to use (ipv4, ipv6, or auto)\",\n ),\n )\n .addOption(\n new Option(\n \"--speed-test\",\n \"Perform a large echo test to measure network speed.\",\n ),\n );\n};\n"],
4
+ "sourcesContent": ["import { Command, Option, OptionValues } from \"@commander-js/extra-typings\";\nimport { OneoffCtx } from \"../../bundler/context.js\";\nimport { LogMode } from \"./logs.js\";\nimport {\n CONVEX_DEPLOYMENT_ENV_VAR_NAME,\n CONVEX_SELF_HOSTED_ADMIN_KEY_VAR_NAME,\n CONVEX_SELF_HOSTED_URL_VAR_NAME,\n parseInteger,\n parsePositiveInteger,\n} from \"./utils/utils.js\";\nimport { INLINE_QUERY_DESCRIPTION } from \"./runTestFunction.js\";\n\ndeclare module \"@commander-js/extra-typings\" {\n interface Command<Args extends any[] = [], Opts extends OptionValues = {}> {\n /**\n * For a command that talks to the configured dev deployment by default,\n * add flags for talking to prod, preview, or other deployment in the same\n * project.\n *\n * These flags are added to the end of `command` (ordering matters for `--help`\n * output). `action` should look like \"Import data into\" because it is prefixed\n * onto help strings.\n *\n * The options can be passed to `deploymentSelectionFromOptions`.\n *\n * NOTE: This method only exists at runtime if this file is imported.\n * To help avoid this bug, this method takes in an `ActionDescription` which\n * can only be constructed via `actionDescription` from this file.\n *\n * @param action - The action description\n * @param options - Optional settings\n * @param options.showUrlHelp - If true, show the --url option in help output\n */\n addDeploymentSelectionOptions(\n action: ActionDescription,\n options?: { showUrlHelp?: boolean },\n ): Command<\n Args,\n Opts & {\n envFile?: string;\n url?: string;\n adminKey?: string;\n prod?: boolean;\n previewName?: string;\n deploymentName?: string;\n deployment?: string;\n }\n >;\n\n /**\n * Adds options for the `deploy` command.\n */\n addDeployOptions(): Command<\n Args,\n Opts & {\n verbose?: boolean;\n dryRun?: boolean;\n yes?: boolean;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: \"enable\" | \"disable\";\n cmd?: string;\n cmdUrlEnvVarName?: string;\n debugBundlePath?: string;\n debug?: boolean;\n writePushRequest?: string;\n liveComponentSources?: boolean;\n }\n >;\n\n /**\n * Adds options for `self-host` subcommands.\n */\n addSelfHostOptions(): Command<\n Args,\n Opts & {\n url?: string;\n adminKey?: string;\n env?: string;\n }\n >;\n\n /**\n * Adds options and arguments for the `run` command.\n */\n addRunOptions(): Command<\n [...Args, string | undefined, string | undefined],\n Opts & {\n watch?: boolean;\n push?: boolean;\n identity?: string;\n inlineQuery?: string;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: \"enable\" | \"disable\";\n component?: string;\n liveComponentSources?: boolean;\n }\n >;\n\n /**\n * Adds options for the `import` command.\n */\n addImportOptions(): Command<\n [...Args, string],\n Opts & {\n table?: string;\n format?: \"csv\" | \"jsonLines\" | \"jsonArray\" | \"zip\";\n replace?: boolean;\n append?: boolean;\n replaceAll?: boolean;\n yes?: boolean;\n component?: string;\n }\n >;\n\n /**\n * Adds options for the `export` command.\n */\n addExportOptions(): Command<\n Args,\n Opts & {\n path: string;\n includeFileStorage?: boolean;\n }\n >;\n\n /**\n * Adds options for the `data` command.\n */\n addDataOptions(): Command<\n [...Args, string | undefined],\n Opts & {\n limit: number;\n order: \"asc\" | \"desc\";\n component?: string;\n format?: \"json\" | \"jsonArray\" | \"jsonLines\" | \"jsonl\" | \"pretty\";\n }\n >;\n\n /**\n * Adds options for the `logs` command.\n */\n addLogsOptions(): Command<\n Args,\n Opts & {\n history: number;\n success: boolean;\n jsonl: boolean;\n }\n >;\n\n /**\n * Adds options for the `network-test` command.\n */\n addNetworkTestOptions(): Command<\n Args,\n Opts & {\n timeout?: string;\n ipFamily?: string;\n speedTest?: boolean;\n }\n >;\n }\n}\n\nCommand.prototype.addDeploymentSelectionOptions = function (\n action: ActionDescription,\n options?: { showUrlHelp?: boolean },\n) {\n const urlOption = new Option(\n \"--url <url>\",\n options?.showUrlHelp\n ? action + \" the deployment at the given URL.\"\n : undefined,\n ).conflicts([\n \"--prod\",\n \"--preview-name\",\n \"--deployment-name\",\n \"--deployment\",\n ]);\n if (!options?.showUrlHelp) {\n urlOption.hideHelp();\n }\n return this.addOption(urlOption)\n .addOption(new Option(\"--admin-key <adminKey>\").hideHelp())\n .addOption(\n new Option(\n \"--prod\",\n action + \" this project's default production deployment.\",\n ).conflicts([\n \"--preview-name\",\n \"--deployment-name\",\n \"--url\",\n \"--deployment\",\n ]),\n )\n .addOption(\n new Option(\n \"--preview-name <previewName>\",\n action + \" the preview deployment with the given name.\",\n )\n .conflicts([\"--prod\", \"--deployment-name\", \"--url\", \"--deployment\"])\n .hideHelp(),\n )\n .addOption(\n new Option(\n \"--deployment-name <deploymentName>\",\n action + \" the specified deployment.\",\n )\n .conflicts([\"--prod\", \"--preview-name\", \"--url\", \"--deployment\"])\n .hideHelp(),\n )\n .addOption(\n new Option(\n \"--deployment <deployment>\",\n action +\n \" a specific deployment. Accepts:\\n\" +\n \"\u2022 a deployment name (e.g. joyful-capybara-123)\\n\" +\n \"\u2022 a deployment reference (e.g. dev/james, staging)\\n\" +\n \"\u2022 `dev` (for your personal dev deployment)\\n\" +\n \"\u2022 `prod` (for your project\u2019s default production deployment)\\n\" +\n \"\u2022 `local` (for your local dev deployment).\" +\n \"\\nYou can also select deployments in other projects with `project-slug:reference` or `team-slug:project-slug:reference`.\",\n ).conflicts([\"--prod\", \"--preview-name\", \"--deployment-name\", \"--url\"]),\n )\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 ).hideHelp(),\n ) as any;\n};\n\ndeclare const tag: unique symbol;\ntype ActionDescription = string & { readonly [tag]: \"noop\" };\nexport function actionDescription(action: string): ActionDescription {\n return action as any;\n}\n\nexport async function normalizeDevOptions(\n ctx: OneoffCtx,\n cmdOptions: {\n verbose?: boolean;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents?: boolean;\n codegen: \"enable\" | \"disable\";\n once?: boolean;\n untilSuccess: boolean;\n start?: string;\n runSh?: string;\n run?: string | undefined;\n runComponent?: string;\n tailLogs?: string | true;\n traceEvents: boolean;\n debugBundlePath?: string | undefined;\n debugNodeApis?: boolean;\n liveComponentSources?: boolean;\n pushAllModules?: boolean;\n while?: string;\n },\n): Promise<{\n verbose: boolean;\n typecheck: \"enable\" | \"try\" | \"disable\";\n typecheckComponents: boolean;\n codegen: boolean;\n once: boolean;\n untilSuccess: boolean;\n run?:\n | { kind: \"function\"; name: string; component?: string | undefined }\n | { kind: \"shell\"; command: string }\n | undefined;\n tailLogs: LogMode;\n traceEvents: boolean;\n debugBundlePath?: string | undefined;\n debugNodeApis: boolean;\n liveComponentSources: boolean;\n pushAllModules: boolean;\n}> {\n if (cmdOptions.runComponent && !cmdOptions.run) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"Can't specify `--run-component` option without `--run`\",\n });\n }\n\n if (cmdOptions.debugBundlePath !== undefined && !cmdOptions.once) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"`--debug-bundle-path` can only be used with `--once`.\",\n });\n }\n if (cmdOptions.debugNodeApis && !cmdOptions.once) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"`--debug-node-apis` can only be used with `--once`.\",\n });\n }\n\n return {\n verbose: !!cmdOptions.verbose,\n typecheck: cmdOptions.typecheck,\n typecheckComponents: !!cmdOptions.typecheckComponents,\n codegen: cmdOptions.codegen === \"enable\",\n once: !!cmdOptions.once,\n untilSuccess: cmdOptions.untilSuccess,\n run:\n cmdOptions.run !== undefined\n ? {\n kind: \"function\",\n name: cmdOptions.run,\n component: cmdOptions.runComponent,\n }\n : (cmdOptions.start ?? cmdOptions.runSh) !== undefined\n ? {\n kind: \"shell\",\n command: (cmdOptions.start ?? cmdOptions.runSh)!,\n }\n : undefined,\n tailLogs:\n typeof cmdOptions.tailLogs === \"string\"\n ? (cmdOptions.tailLogs as LogMode)\n : \"pause-on-deploy\",\n traceEvents: cmdOptions.traceEvents,\n debugBundlePath: cmdOptions.debugBundlePath,\n debugNodeApis: !!cmdOptions.debugNodeApis,\n liveComponentSources: !!cmdOptions.liveComponentSources,\n pushAllModules: !!cmdOptions.pushAllModules,\n };\n}\n\nCommand.prototype.addDeployOptions = function () {\n return this.option(\"-v, --verbose\", \"Show full listing of changes\")\n .option(\n \"--dry-run\",\n \"Print out the generated configuration without deploying to your Convex deployment\",\n )\n .addOption(\n new Option(\n \"-y, --yes\",\n \"Skip confirmation prompt when running interactively. Warning: this deploys to PRODUCTION. To deploy to your current dev environment, run npx convex dev --once\",\n ).hideHelp(),\n )\n .addOption(\n new Option(\n \"--typecheck <mode>\",\n `Whether to check TypeScript files with \\`tsc --noEmit\\` before deploying.`,\n )\n .choices([\"enable\", \"try\", \"disable\"] as const)\n .default(\"try\" as const),\n )\n .option(\n \"--typecheck-components\",\n \"Check TypeScript files within component implementations with `tsc --noEmit`.\",\n false,\n )\n .addOption(\n new Option(\n \"--codegen <mode>\",\n \"Whether to regenerate code in `convex/_generated/` before pushing.\",\n )\n .choices([\"enable\", \"disable\"] as const)\n .default(\"enable\" as const),\n )\n .addOption(\n new Option(\n \"--cmd <command>\",\n \"Command to run as part of deploying your app (e.g. `vite build`). This command can depend on the environment variables specified in `--cmd-url-env-var-name` being set.\",\n ),\n )\n .addOption(\n new Option(\n \"--cmd-url-env-var-name <name>\",\n \"Environment variable name to set Convex deployment URL (e.g. `VITE_CONVEX_URL`) when using `--cmd`\",\n ),\n )\n .addOption(new Option(\"--debug-bundle-path <path>\").hideHelp())\n .addOption(new Option(\"--debug\").hideHelp())\n .addOption(new Option(\"--write-push-request <writePushRequest>\").hideHelp())\n .addOption(new Option(\"--live-component-sources\").hideHelp())\n .addOption(\n new Option(\n \"--push-all-modules\",\n \"Push all modules without checking for unchanged module hashes from the server\",\n )\n .default(false)\n .hideHelp(),\n );\n};\n\nCommand.prototype.addSelfHostOptions = function () {\n return this.option(\n \"--admin-key <adminKey>\",\n `An admin key for the deployment. Can alternatively be set as \\`${CONVEX_SELF_HOSTED_ADMIN_KEY_VAR_NAME}\\` environment variable.`,\n )\n .option(\n \"--url <url>\",\n `The url of the deployment. Can alternatively be set as \\`${CONVEX_SELF_HOSTED_URL_VAR_NAME}\\` environment variable.`,\n )\n .option(\n \"--env <env>\",\n `Path to a custom file of environment variables, containing \\`${CONVEX_SELF_HOSTED_URL_VAR_NAME}\\` and \\`${CONVEX_SELF_HOSTED_ADMIN_KEY_VAR_NAME}\\`.`,\n );\n};\n\nCommand.prototype.addRunOptions = function () {\n return (\n this.argument(\n \"[functionName]\",\n \"identifier of the function to run, like `listMessages` or `dir/file:myFunction`\",\n )\n .argument(\n \"[args]\",\n \"JSON-formatted arguments object to pass to the function.\",\n )\n .option(\n \"-w, --watch\",\n \"Watch a query, printing its result if the underlying data changes. Given function must be a query.\",\n )\n .addOption(\n new Option(\n \"--inline-query <query>\",\n INLINE_QUERY_DESCRIPTION,\n ).conflicts(\"--watch\"),\n )\n .option(\"--push\", \"Push code to deployment before running the function.\")\n .addOption(\n new Option(\n \"--identity <identity>\",\n 'JSON-formatted UserIdentity object, e.g. \\'{ name: \"John\", address: \"0x123\" }\\'',\n ),\n )\n // For backwards compatibility we still support --no-push which is a noop\n .addOption(new Option(\"--no-push\").hideHelp())\n // Options for the deploy that --push does\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 \"--typecheck-components\",\n \"Check TypeScript files within component implementations with `tsc --noEmit`.\",\n false,\n )\n .addOption(\n new Option(\n \"--codegen <mode>\",\n \"Regenerate code in `convex/_generated/`\",\n )\n .choices([\"enable\", \"disable\"] as const)\n .default(\"enable\" as const),\n )\n .addOption(\n new Option(\n \"--component <path>\",\n \"Path to the component in the component tree defined in convex.config.ts.\",\n ),\n )\n .addOption(new Option(\"--live-component-sources\").hideHelp())\n );\n};\n\nCommand.prototype.addImportOptions = function () {\n return this.argument(\"<path>\", \"Path to the input file\")\n .addOption(\n new Option(\n \"--table <table>\",\n \"Destination table name. Required if format is csv, jsonLines, or jsonArray. Not supported if format is zip.\",\n ),\n )\n .addOption(\n new Option(\n \"--replace\",\n \"Replace all existing data in any of the imported tables\",\n )\n .conflicts(\"--append\")\n .conflicts(\"--replace-all\"),\n )\n .addOption(\n new Option(\"--append\", \"Append imported data to any existing tables\")\n .conflicts(\"--replace-all\")\n .conflicts(\"--replace\"),\n )\n .addOption(\n new Option(\n \"--replace-all\",\n \"Replace all existing data in the deployment with the imported tables,\\n\" +\n \" deleting tables that don't appear in the import file or the schema,\\n\" +\n \" and clearing tables that appear in the schema but not in the import file\",\n )\n .conflicts(\"--append\")\n .conflicts(\"--replace\"),\n )\n .option(\n \"-y, --yes\",\n \"Skip confirmation prompt when import leads to deleting existing documents\",\n )\n .addOption(\n new Option(\n \"--format <format>\",\n \"Input file format. This flag is only required if the filename is missing an extension.\\n\" +\n \"- CSV files must have a header, and each row's entries are interpreted either as a (floating point) number or a string.\\n\" +\n \"- JSON files must be an array of JSON objects.\\n\" +\n \"- JSONLines files must have a JSON object per line.\\n\" +\n \"- ZIP files must have one directory per table, containing <table>/documents.jsonl. Snapshot exports from the Convex dashboard have this format.\",\n ).choices([\"csv\", \"jsonLines\", \"jsonArray\", \"zip\"]),\n )\n .addOption(\n new Option(\n \"--component <path>\",\n \"Path to the component in the component tree defined in convex.config.ts.\",\n ),\n );\n};\n\nCommand.prototype.addExportOptions = function () {\n return this.requiredOption(\n \"--path <zipFilePath>\",\n \"Exports data into a ZIP file at this path, which may be a directory or unoccupied .zip path\",\n ).addOption(\n new Option(\n \"--include-file-storage\",\n \"Includes stored files (https://dashboard.convex.dev/deployment/files) in a _storage folder within the ZIP file\",\n ),\n );\n};\n\nCommand.prototype.addDataOptions = function () {\n return this.addOption(\n new Option(\n \"--limit <n>\",\n \"List only the `n` the most recently created documents.\",\n )\n .default(100)\n .argParser(parsePositiveInteger),\n )\n .addOption(\n new Option(\n \"--order <choice>\",\n \"Order the documents by their `_creationTime`.\",\n )\n .choices([\"asc\", \"desc\"])\n .default(\"desc\"),\n )\n .addOption(\n new Option(\n \"--component <path>\",\n \"Path to the component in the component tree defined in convex.config.ts.\",\n ),\n )\n .addOption(\n new Option(\n \"--format <format>\",\n \"Format to print the data in. This flag is only required if the filename is missing an extension.\\n\" +\n \"- jsonArray (aka json): print the data as a JSON array of objects.\\n\" +\n \"- jsonLines (aka jsonl): print the data as a JSON object per line.\\n\" +\n \"- pretty: print the data in a human-readable format.\",\n ).choices([\"jsonArray\", \"json\", \"jsonLines\", \"jsonl\", \"pretty\"]),\n )\n .argument(\"[table]\", \"If specified, list documents in this table.\");\n};\n\nCommand.prototype.addLogsOptions = function () {\n return this.option(\n \"--history [n]\",\n \"Show `n` most recent logs. Defaults to showing all available logs.\",\n parseInteger,\n )\n .option(\n \"--success\",\n \"Print a log line for every successful function execution\",\n false,\n )\n .option(\"--jsonl\", \"Output raw log events as JSONL\", false);\n};\n\nCommand.prototype.addNetworkTestOptions = function () {\n return this.addOption(\n new Option(\n \"--timeout <timeout>\",\n \"Timeout in seconds for the network test (default: 30).\",\n ),\n )\n .addOption(\n new Option(\n \"--ip-family <ipFamily>\",\n \"IP family to use (ipv4, ipv6, or auto)\",\n ),\n )\n .addOption(\n new Option(\n \"--speed-test\",\n \"Perform a large echo test to measure network speed.\",\n ),\n );\n};\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAA8C;AAG9C,mBAMO;AACP,6BAAyC;AA4JzC,6BAAQ,UAAU,gCAAgC,SAChD,QACA,SACA;AACA,QAAM,YAAY,IAAI;AAAA,IACpB;AAAA,IACA,SAAS,cACL,SAAS,sCACT;AAAA,EACN,EAAE,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,MAAI,CAAC,SAAS,aAAa;AACzB,cAAU,SAAS;AAAA,EACrB;AACA,SAAO,KAAK,UAAU,SAAS,EAC5B,UAAU,IAAI,4BAAO,wBAAwB,EAAE,SAAS,CAAC,EACzD;AAAA,IACC,IAAI;AAAA,MACF;AAAA,MACA,SAAS;AAAA,IACX,EAAE,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH,EACC;AAAA,IACC,IAAI;AAAA,MACF;AAAA,MACA,SAAS;AAAA,IACX,EACG,UAAU,CAAC,UAAU,qBAAqB,SAAS,cAAc,CAAC,EAClE,SAAS;AAAA,EACd,EACC;AAAA,IACC,IAAI;AAAA,MACF;AAAA,MACA,SAAS;AAAA,IACX,EACG,UAAU,CAAC,UAAU,kBAAkB,SAAS,cAAc,CAAC,EAC/D,SAAS;AAAA,EACd,EACC;AAAA,IACC,IAAI;AAAA,MACF;AAAA,MACA,SACE;AAAA,IAOJ,EAAE,UAAU,CAAC,UAAU,kBAAkB,qBAAqB,OAAO,CA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EACF,EACG;AAAA,IACC,IAAI;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF,EACC;AAAA,IACC,IAAI;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACJ;",
6
6
  "names": []
7
7
  }
@@ -318,6 +318,57 @@ async function performLogin(ctx, {
318
318
  printedMessage: null
319
319
  });
320
320
  }
321
+ if (vercel) {
322
+ await promptJoinVercelTeams(ctx);
323
+ }
324
+ }
325
+ async function promptJoinVercelTeams(ctx) {
326
+ const fetch2 = (0, import_utils.bigBrainFetch)(ctx);
327
+ let teams;
328
+ try {
329
+ const res = await fetch2(
330
+ new URL("vercel/potential_teams", `${import_config.provisionHost}/`)
331
+ );
332
+ if (!res.ok) {
333
+ (0, import_log.logVerbose)(
334
+ `vercel/potential_teams returned ${res.status}; skipping team-join prompt`
335
+ );
336
+ return;
337
+ }
338
+ teams = await res.json();
339
+ } catch (err) {
340
+ (0, import_log.logVerbose)(`Failed to fetch potential Vercel teams: ${String(err)}`);
341
+ return;
342
+ }
343
+ if (teams.length === 0) return;
344
+ for (const [index, team] of teams.entries()) {
345
+ const displayName = team.teamName.replace(/ \(Vercel\)$/, "");
346
+ const counter = teams.length > 1 ? `[${index + 1}/${teams.length}] ` : "";
347
+ const lines = [
348
+ import_chalk.chalkStderr.bold(`${counter}You've been invited to join ${displayName}`) + ` (${team.planName}) through the Vercel marketplace.`
349
+ ];
350
+ if (team.pricingNotice) {
351
+ lines.push(import_chalk.chalkStderr.yellow(team.pricingNotice));
352
+ }
353
+ lines.push(`Join "${displayName}"?`);
354
+ const join = await (0, import_prompts.promptYesNo)(ctx, {
355
+ message: `${lines.join("\n")}`,
356
+ default: true
357
+ });
358
+ if (!join) continue;
359
+ try {
360
+ await fetch2(
361
+ new URL(
362
+ `vercel/potential_teams/${team.teamId}/join`,
363
+ `${import_config.provisionHost}/`
364
+ ),
365
+ { method: "POST" }
366
+ );
367
+ (0, import_log.logFinishedStep)(`Joined ${displayName}`);
368
+ } catch (err) {
369
+ (0, import_log.logFailure)(`Failed to join ${displayName}: ${String(err)}`);
370
+ }
371
+ }
321
372
  }
322
373
  async function optins(ctx, acceptOptIns) {
323
374
  const bbAuth = ctx.bigBrainAuth();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/cli/lib/login.ts"],
4
- "sourcesContent": ["import { errors, BaseClient, custom } from \"openid-client\";\nimport {\n bigBrainAPI,\n logAndHandleFetchError,\n throwingFetch,\n isWebContainer,\n} from \"./utils/utils.js\";\nimport open from \"open\";\nimport { chalkStderr } from \"chalk\";\nimport { provisionHost } from \"./config.js\";\nimport { version } from \"../version.js\";\nimport { Context } from \"../../bundler/context.js\";\nimport {\n changeSpinner,\n logError,\n logFailure,\n logFinishedStep,\n logMessage,\n logOutput,\n logVerbose,\n showSpinner,\n} from \"../../bundler/log.js\";\nimport { Issuer } from \"openid-client\";\nimport { hostname } from \"os\";\nimport { execSync } from \"child_process\";\nimport { promptString, promptYesNo } from \"./utils/prompts.js\";\nimport {\n formatPathForPrinting,\n globalConfigPath,\n modifyGlobalConfig,\n} from \"./utils/globalConfig.js\";\nimport { updateBigBrainAuthAfterLogin } from \"./deploymentSelection.js\";\n\n// Per https://github.com/panva/node-openid-client/tree/main/docs#customizing\ncustom.setHttpOptionsDefaults({\n timeout: parseInt(process.env.OPENID_CLIENT_TIMEOUT || \"10000\"),\n});\n\ninterface AuthorizeArgs {\n authnToken: string;\n deviceName: string;\n anonymousId?: string | undefined;\n}\n\nexport async function checkAuthorization(\n ctx: Context,\n acceptOptIns: boolean,\n): Promise<boolean> {\n const header = ctx.bigBrainAuth()?.header ?? null;\n if (header === null) {\n return false;\n }\n try {\n const resp = await fetch(`${provisionHost}/api/authorize`, {\n method: \"HEAD\",\n headers: {\n Authorization: header,\n \"Convex-Client\": `npm-cli-${version}`,\n },\n });\n // Don't throw an error if this request returns a non-200 status.\n // Big Brain responds with a variety of error codes -- 401 if the token is correctly-formed but not valid, and either 400 or 500 if the token is ill-formed.\n // We only care if this check returns a 200 code (so we can skip logging in again) -- any other errors should be silently skipped and we'll run the whole login flow again.\n if (resp.status !== 200) {\n return false;\n }\n } catch (e: any) {\n // This `catch` block should only be hit if a network error was encountered\n logError(\n `Unexpected error when authorizing - are you connected to the internet?`,\n );\n return await logAndHandleFetchError(ctx, e);\n }\n\n // Check that we have optin as well\n const shouldContinue = await optins(ctx, acceptOptIns);\n if (!shouldContinue) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: null,\n });\n }\n return true;\n}\n\nasync function performDeviceAuthorization(\n ctx: Context,\n authClient: BaseClient,\n shouldOpen: boolean,\n vercel?: boolean,\n vercelOverride?: string,\n): Promise<string> {\n // Device authorization flow follows this guide: https://github.com/auth0/auth0-device-flow-cli-sample/blob/9f0f3b76a6cd56ea8d99e76769187ea5102d519d/cli.js\n // License: MIT License\n // Copyright (c) 2019 Auth0 Samples\n /*\n The MIT License (MIT)\n\n Copyright (c) 2019 Auth0 Samples\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n\n // Device Authorization Request - https://tools.ietf.org/html/rfc8628#section-3.1\n // Get authentication URL\n let handle;\n try {\n handle = await authClient.deviceAuthorization();\n } catch {\n // We couldn't get verification URL from the auth provider, proceed with manual auth\n return promptString(ctx, {\n message:\n \"Open https://dashboard.convex.dev/auth, log in and paste the token here:\",\n });\n }\n\n // Device Authorization Response - https://tools.ietf.org/html/rfc8628#section-3.2\n // Open authentication URL\n const { verification_uri_complete, user_code, expires_in } = handle;\n\n // Construct Vercel URL if --vercel flag is used\n const urlToOpen = vercel\n ? `https://vercel.com/sso/integrations/${vercelOverride || \"convex\"}?url=${verification_uri_complete}`\n : verification_uri_complete;\n\n logMessage(\n `Visit ${urlToOpen} to finish logging in.\\n` +\n `You should see the following code which expires in ${\n expires_in % 60 === 0\n ? `${expires_in / 60} minutes`\n : `${expires_in} seconds`\n }: ${user_code}`,\n );\n if (shouldOpen) {\n shouldOpen = await promptYesNo(ctx, {\n message: `Open the browser?`,\n default: true,\n });\n }\n\n if (shouldOpen) {\n showSpinner(`Opening ${urlToOpen} in your browser to log in...\\n`);\n try {\n const p = await open(urlToOpen);\n p.once(\"error\", () => {\n changeSpinner(`Manually open ${urlToOpen} in your browser to log in.`);\n });\n changeSpinner(\"Waiting for the confirmation...\");\n } catch {\n logError(chalkStderr.red(`Unable to open browser.`));\n changeSpinner(`Manually open ${urlToOpen} in your browser to log in.`);\n }\n } else {\n showSpinner(`Open ${urlToOpen} in your browser to log in.`);\n }\n\n // Device Access Token Request - https://tools.ietf.org/html/rfc8628#section-3.4\n // Device Access Token Response - https://tools.ietf.org/html/rfc8628#section-3.5\n try {\n const tokens = await handle.poll();\n if (typeof tokens.access_token === \"string\") {\n return tokens.access_token;\n } else {\n // Unexpected error\n // eslint-disable-next-line no-restricted-syntax\n throw Error(\"Access token is missing\");\n }\n } catch (err: any) {\n switch (err.error) {\n case \"access_denied\": // end-user declined the device confirmation prompt, consent or rules failed\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"Access denied.\",\n errForSentry: err,\n });\n case \"expired_token\": // end-user did not complete the interaction in time\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"Device flow expired.\",\n errForSentry: err,\n });\n default: {\n const message =\n err instanceof errors.OPError\n ? `Error = ${err.error}; error_description = ${err.error_description}`\n : `Login failed with error: ${err}`;\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: message,\n errForSentry: err,\n });\n }\n }\n }\n}\n\nasync function performPasswordAuthentication(\n ctx: Context,\n clientId: string,\n username: string,\n password: string,\n): Promise<string> {\n if (!process.env.WORKOS_API_SECRET) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"WORKOS_API_SECRET environment variable is not set\",\n });\n }\n\n // Unfortunately, `openid-client` doesn't support the resource owner password credentials flow so we need to manually send the requests.\n const options: Parameters<typeof throwingFetch>[1] = {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n grant_type: \"password\",\n email: username,\n password: password,\n client_id: clientId,\n client_secret: process.env.WORKOS_API_SECRET,\n }),\n };\n\n try {\n const response = await throwingFetch(\n \"https://apiauth.convex.dev/user_management/authenticate\",\n options,\n );\n const data = await response.json();\n if (typeof data.access_token === \"string\") {\n return data.access_token;\n } else {\n // Unexpected error\n // eslint-disable-next-line no-restricted-syntax\n throw Error(\"Access token is missing\");\n }\n } catch (err: any) {\n logFailure(`Password flow failed: ${err}`);\n if (err.response) {\n logError(chalkStderr.red(`${JSON.stringify(err.response.data)}`));\n }\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n errForSentry: err,\n printedMessage: null,\n });\n }\n}\n\nexport async function performLogin(\n ctx: Context,\n {\n overrideAuthUrl,\n overrideAuthClient,\n overrideAuthUsername,\n overrideAuthPassword,\n overrideAccessToken,\n loginFlow,\n open,\n acceptOptIns,\n dumpAccessToken,\n deviceName: deviceNameOverride,\n anonymousId,\n vercel,\n vercelOverride,\n }: {\n overrideAuthUrl?: string | undefined;\n overrideAuthClient?: string | undefined;\n overrideAuthUsername?: string | undefined;\n overrideAuthPassword?: string | undefined;\n overrideAccessToken?: string | undefined;\n loginFlow?: \"auto\" | \"paste\" | \"poll\" | undefined;\n // default `true`\n open?: boolean | undefined;\n // default `false`\n acceptOptIns?: boolean | undefined;\n dumpAccessToken?: boolean | undefined;\n deviceName?: string | undefined;\n anonymousId?: string | undefined;\n vercel?: boolean | undefined;\n vercelOverride?: string | undefined;\n } = {},\n) {\n loginFlow = loginFlow || \"auto\";\n // Get access token from big-brain\n // Default the device name to the hostname, but allow the user to change this if the terminal is interactive.\n // On Macs, the `hostname()` may be a weirdly-truncated form of the computer name. Attempt to read the \"real\" name before falling back to hostname.\n let deviceName = deviceNameOverride ?? \"\";\n if (!deviceName && process.platform === \"darwin\") {\n try {\n deviceName = execSync(\"scutil --get ComputerName\").toString().trim();\n } catch {\n // Just fall back to the hostname default below.\n }\n }\n if (!deviceName) {\n deviceName = hostname();\n }\n if (!deviceNameOverride) {\n logMessage(\n chalkStderr.bold(\n `Welcome to developing with Convex, let's get you logged in.`,\n ),\n );\n deviceName = await promptString(ctx, {\n message: \"Device name:\",\n default: deviceName,\n });\n }\n\n const issuer = overrideAuthUrl ?? \"https://auth.convex.dev\";\n let authIssuer;\n let accessToken: string;\n\n if (loginFlow === \"paste\" || (loginFlow === \"auto\" && isWebContainer())) {\n accessToken = await promptString(ctx, {\n message:\n \"Open https://dashboard.convex.dev/auth, log in and paste the token here:\",\n });\n } else {\n try {\n authIssuer = await Issuer.discover(issuer);\n } catch {\n // Couldn't contact https://auth.convex.dev/.well-known/openid-configuration,\n // proceed with manual auth.\n accessToken = await promptString(ctx, {\n message:\n \"Open https://dashboard.convex.dev/auth, log in and paste the token here:\",\n });\n }\n }\n\n // typical path\n if (authIssuer) {\n const clientId = overrideAuthClient ?? \"HFtA247jp9iNs08NTLIB7JsNPMmRIyfi\";\n const authClient = new authIssuer.Client({\n client_id: clientId,\n token_endpoint_auth_method: \"none\",\n id_token_signed_response_alg: \"RS256\",\n });\n\n if (overrideAccessToken) {\n accessToken = overrideAccessToken;\n } else if (overrideAuthUsername && overrideAuthPassword) {\n accessToken = await performPasswordAuthentication(\n ctx,\n clientId,\n overrideAuthUsername,\n overrideAuthPassword,\n );\n } else {\n accessToken = await performDeviceAuthorization(\n ctx,\n authClient,\n open ?? true,\n vercel,\n vercelOverride,\n );\n }\n }\n\n if (dumpAccessToken) {\n logOutput(`${accessToken!}`);\n return await ctx.crash({\n exitCode: 0,\n errorType: \"fatal\",\n printedMessage: null,\n });\n }\n\n const authorizeArgs: AuthorizeArgs = {\n authnToken: accessToken!,\n deviceName: deviceName,\n anonymousId: anonymousId,\n };\n const data = await bigBrainAPI({\n ctx,\n method: \"POST\",\n path: \"authorize\",\n data: authorizeArgs,\n });\n const globalConfig = { accessToken: data.accessToken };\n try {\n await modifyGlobalConfig(ctx, globalConfig);\n const path = globalConfigPath();\n logFinishedStep(`Saved credentials to ${formatPathForPrinting(path)}`);\n } catch (err: unknown) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n errForSentry: err,\n printedMessage: null,\n });\n }\n\n logVerbose(`performLogin: updating big brain auth after login`);\n await updateBigBrainAuthAfterLogin(ctx, data.accessToken);\n\n logVerbose(`performLogin: checking opt ins, acceptOptIns: ${acceptOptIns}`);\n // Do opt in to TOS and Privacy Policy stuff\n const shouldContinue = await optins(ctx, acceptOptIns ?? false);\n if (!shouldContinue) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: null,\n });\n }\n}\n\n/// There are fields like version, but we keep them opaque\ntype OptIn = Record<string, unknown>;\n\ntype OptInToAccept = {\n optIn: OptIn;\n message: string;\n};\n\ntype AcceptOptInsArgs = {\n optInsAccepted: OptIn[];\n};\n\n// Returns whether we can proceed or not.\nasync function optins(ctx: Context, acceptOptIns: boolean): Promise<boolean> {\n const bbAuth = ctx.bigBrainAuth();\n if (bbAuth === null) {\n // This should never happen, but if we're not even logged in, we can't proceed.\n return false;\n }\n switch (bbAuth.kind) {\n case \"accessToken\":\n break;\n case \"deploymentKey\":\n case \"projectKey\":\n case \"previewDeployKey\":\n // If we have a key configured as auth, we do not need to check opt ins.\n return true;\n default: {\n bbAuth satisfies never;\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n errForSentry: `Unexpected auth kind ${(bbAuth as any).kind}`,\n printedMessage: \"Hit an unexpected error while logging in.\",\n });\n }\n }\n const data = await bigBrainAPI({\n ctx,\n method: \"POST\",\n path: \"check_opt_ins\",\n });\n if (data.optInsToAccept.length === 0) {\n return true;\n }\n for (const optInToAccept of data.optInsToAccept) {\n const confirmed =\n acceptOptIns ||\n (await promptYesNo(ctx, {\n message: optInToAccept.message,\n }));\n if (!confirmed) {\n logFailure(\"Please accept the Terms of Service to use Convex.\");\n return Promise.resolve(false);\n }\n }\n\n const optInsAccepted = data.optInsToAccept.map((o: OptInToAccept) => o.optIn);\n const args: AcceptOptInsArgs = { optInsAccepted };\n await bigBrainAPI({\n ctx,\n method: \"POST\",\n path: \"accept_opt_ins\",\n data: args,\n });\n return true;\n}\n\nexport async function ensureLoggedIn(\n ctx: Context,\n options?: {\n message?: string | undefined;\n overrideAuthUrl?: string | undefined;\n overrideAuthClient?: string | undefined;\n overrideAuthUsername?: string | undefined;\n overrideAuthPassword?: string | undefined;\n },\n) {\n const isLoggedIn = await checkAuthorization(ctx, false);\n if (!isLoggedIn) {\n if (options?.message) {\n logMessage(options.message);\n }\n await performLogin(ctx, {\n acceptOptIns: false,\n overrideAuthUrl: options?.overrideAuthUrl,\n overrideAuthClient: options?.overrideAuthClient,\n overrideAuthUsername: options?.overrideAuthUsername,\n overrideAuthPassword: options?.overrideAuthPassword,\n });\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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ACA,aAAO,MAAM,IAAI,MAAM;AAAA,QACrB,UAAU;AAAA,QACV,WAAW;AAAA,QACX,cAAc,wBAAyB,OAAe,IAAI;AAAA,QAC1D,gBAAgB;AAAA,MAClB,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,OAAO,UAAM,0BAAY;AAAA,IAC7B;AAAA,IACA,QAAQ;AAAA,IACR,MAAM;AAAA,EACR,CAAC;AACD,MAAI,KAAK,eAAe,WAAW,GAAG;AACpC,WAAO;AAAA,EACT;AACA,aAAW,iBAAiB,KAAK,gBAAgB;AAC/C,UAAM,YACJ,gBACC,UAAM,4BAAY,KAAK;AAAA,MACtB,SAAS,cAAc;AAAA,IACzB,CAAC;AACH,QAAI,CAAC,WAAW;AACd,iCAAW,mDAAmD;AAC9D,aAAO,QAAQ,QAAQ,KAAK;AAAA,IAC9B;AAAA,EACF;AAEA,QAAM,iBAAiB,KAAK,eAAe,IAAI,CAAC,MAAqB,EAAE,KAAK;AAC5E,QAAM,OAAyB,EAAE,eAAe;AAChD,YAAM,0BAAY;AAAA,IAChB;AAAA,IACA,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,MAAM;AAAA,EACR,CAAC;AACD,SAAO;AACT;AAEA,eAAsB,eACpB,KACA,SAOA;AACA,QAAM,aAAa,MAAM,mBAAmB,KAAK,KAAK;AACtD,MAAI,CAAC,YAAY;AACf,QAAI,SAAS,SAAS;AACpB,iCAAW,QAAQ,OAAO;AAAA,IAC5B;AACA,UAAM,aAAa,KAAK;AAAA,MACtB,cAAc;AAAA,MACd,iBAAiB,SAAS;AAAA,MAC1B,oBAAoB,SAAS;AAAA,MAC7B,sBAAsB,SAAS;AAAA,MAC/B,sBAAsB,SAAS;AAAA,IACjC,CAAC;AAAA,EACH;AACF;",
6
- "names": ["import_openid_client", "open"]
4
+ "sourcesContent": ["import { errors, BaseClient, custom } from \"openid-client\";\nimport {\n bigBrainAPI,\n bigBrainFetch,\n logAndHandleFetchError,\n throwingFetch,\n isWebContainer,\n} from \"./utils/utils.js\";\nimport open from \"open\";\nimport { chalkStderr } from \"chalk\";\nimport { provisionHost } from \"./config.js\";\nimport { version } from \"../version.js\";\nimport { Context } from \"../../bundler/context.js\";\nimport {\n changeSpinner,\n logError,\n logFailure,\n logFinishedStep,\n logMessage,\n logOutput,\n logVerbose,\n showSpinner,\n} from \"../../bundler/log.js\";\nimport { Issuer } from \"openid-client\";\nimport { hostname } from \"os\";\nimport { execSync } from \"child_process\";\nimport { promptString, promptYesNo } from \"./utils/prompts.js\";\nimport {\n formatPathForPrinting,\n globalConfigPath,\n modifyGlobalConfig,\n} from \"./utils/globalConfig.js\";\nimport { updateBigBrainAuthAfterLogin } from \"./deploymentSelection.js\";\n\n// Per https://github.com/panva/node-openid-client/tree/main/docs#customizing\ncustom.setHttpOptionsDefaults({\n timeout: parseInt(process.env.OPENID_CLIENT_TIMEOUT || \"10000\"),\n});\n\ninterface AuthorizeArgs {\n authnToken: string;\n deviceName: string;\n anonymousId?: string | undefined;\n}\n\nexport async function checkAuthorization(\n ctx: Context,\n acceptOptIns: boolean,\n): Promise<boolean> {\n const header = ctx.bigBrainAuth()?.header ?? null;\n if (header === null) {\n return false;\n }\n try {\n const resp = await fetch(`${provisionHost}/api/authorize`, {\n method: \"HEAD\",\n headers: {\n Authorization: header,\n \"Convex-Client\": `npm-cli-${version}`,\n },\n });\n // Don't throw an error if this request returns a non-200 status.\n // Big Brain responds with a variety of error codes -- 401 if the token is correctly-formed but not valid, and either 400 or 500 if the token is ill-formed.\n // We only care if this check returns a 200 code (so we can skip logging in again) -- any other errors should be silently skipped and we'll run the whole login flow again.\n if (resp.status !== 200) {\n return false;\n }\n } catch (e: any) {\n // This `catch` block should only be hit if a network error was encountered\n logError(\n `Unexpected error when authorizing - are you connected to the internet?`,\n );\n return await logAndHandleFetchError(ctx, e);\n }\n\n // Check that we have optin as well\n const shouldContinue = await optins(ctx, acceptOptIns);\n if (!shouldContinue) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: null,\n });\n }\n return true;\n}\n\nasync function performDeviceAuthorization(\n ctx: Context,\n authClient: BaseClient,\n shouldOpen: boolean,\n vercel?: boolean,\n vercelOverride?: string,\n): Promise<string> {\n // Device authorization flow follows this guide: https://github.com/auth0/auth0-device-flow-cli-sample/blob/9f0f3b76a6cd56ea8d99e76769187ea5102d519d/cli.js\n // License: MIT License\n // Copyright (c) 2019 Auth0 Samples\n /*\n The MIT License (MIT)\n\n Copyright (c) 2019 Auth0 Samples\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n */\n\n // Device Authorization Request - https://tools.ietf.org/html/rfc8628#section-3.1\n // Get authentication URL\n let handle;\n try {\n handle = await authClient.deviceAuthorization();\n } catch {\n // We couldn't get verification URL from the auth provider, proceed with manual auth\n return promptString(ctx, {\n message:\n \"Open https://dashboard.convex.dev/auth, log in and paste the token here:\",\n });\n }\n\n // Device Authorization Response - https://tools.ietf.org/html/rfc8628#section-3.2\n // Open authentication URL\n const { verification_uri_complete, user_code, expires_in } = handle;\n\n // Construct Vercel URL if --vercel flag is used\n const urlToOpen = vercel\n ? `https://vercel.com/sso/integrations/${vercelOverride || \"convex\"}?url=${verification_uri_complete}`\n : verification_uri_complete;\n\n logMessage(\n `Visit ${urlToOpen} to finish logging in.\\n` +\n `You should see the following code which expires in ${\n expires_in % 60 === 0\n ? `${expires_in / 60} minutes`\n : `${expires_in} seconds`\n }: ${user_code}`,\n );\n if (shouldOpen) {\n shouldOpen = await promptYesNo(ctx, {\n message: `Open the browser?`,\n default: true,\n });\n }\n\n if (shouldOpen) {\n showSpinner(`Opening ${urlToOpen} in your browser to log in...\\n`);\n try {\n const p = await open(urlToOpen);\n p.once(\"error\", () => {\n changeSpinner(`Manually open ${urlToOpen} in your browser to log in.`);\n });\n changeSpinner(\"Waiting for the confirmation...\");\n } catch {\n logError(chalkStderr.red(`Unable to open browser.`));\n changeSpinner(`Manually open ${urlToOpen} in your browser to log in.`);\n }\n } else {\n showSpinner(`Open ${urlToOpen} in your browser to log in.`);\n }\n\n // Device Access Token Request - https://tools.ietf.org/html/rfc8628#section-3.4\n // Device Access Token Response - https://tools.ietf.org/html/rfc8628#section-3.5\n try {\n const tokens = await handle.poll();\n if (typeof tokens.access_token === \"string\") {\n return tokens.access_token;\n } else {\n // Unexpected error\n // eslint-disable-next-line no-restricted-syntax\n throw Error(\"Access token is missing\");\n }\n } catch (err: any) {\n switch (err.error) {\n case \"access_denied\": // end-user declined the device confirmation prompt, consent or rules failed\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"Access denied.\",\n errForSentry: err,\n });\n case \"expired_token\": // end-user did not complete the interaction in time\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"Device flow expired.\",\n errForSentry: err,\n });\n default: {\n const message =\n err instanceof errors.OPError\n ? `Error = ${err.error}; error_description = ${err.error_description}`\n : `Login failed with error: ${err}`;\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: message,\n errForSentry: err,\n });\n }\n }\n }\n}\n\nasync function performPasswordAuthentication(\n ctx: Context,\n clientId: string,\n username: string,\n password: string,\n): Promise<string> {\n if (!process.env.WORKOS_API_SECRET) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: \"WORKOS_API_SECRET environment variable is not set\",\n });\n }\n\n // Unfortunately, `openid-client` doesn't support the resource owner password credentials flow so we need to manually send the requests.\n const options: Parameters<typeof throwingFetch>[1] = {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n grant_type: \"password\",\n email: username,\n password: password,\n client_id: clientId,\n client_secret: process.env.WORKOS_API_SECRET,\n }),\n };\n\n try {\n const response = await throwingFetch(\n \"https://apiauth.convex.dev/user_management/authenticate\",\n options,\n );\n const data = await response.json();\n if (typeof data.access_token === \"string\") {\n return data.access_token;\n } else {\n // Unexpected error\n // eslint-disable-next-line no-restricted-syntax\n throw Error(\"Access token is missing\");\n }\n } catch (err: any) {\n logFailure(`Password flow failed: ${err}`);\n if (err.response) {\n logError(chalkStderr.red(`${JSON.stringify(err.response.data)}`));\n }\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n errForSentry: err,\n printedMessage: null,\n });\n }\n}\n\nexport async function performLogin(\n ctx: Context,\n {\n overrideAuthUrl,\n overrideAuthClient,\n overrideAuthUsername,\n overrideAuthPassword,\n overrideAccessToken,\n loginFlow,\n open,\n acceptOptIns,\n dumpAccessToken,\n deviceName: deviceNameOverride,\n anonymousId,\n vercel,\n vercelOverride,\n }: {\n overrideAuthUrl?: string | undefined;\n overrideAuthClient?: string | undefined;\n overrideAuthUsername?: string | undefined;\n overrideAuthPassword?: string | undefined;\n overrideAccessToken?: string | undefined;\n loginFlow?: \"auto\" | \"paste\" | \"poll\" | undefined;\n // default `true`\n open?: boolean | undefined;\n // default `false`\n acceptOptIns?: boolean | undefined;\n dumpAccessToken?: boolean | undefined;\n deviceName?: string | undefined;\n anonymousId?: string | undefined;\n vercel?: boolean | undefined;\n vercelOverride?: string | undefined;\n } = {},\n) {\n loginFlow = loginFlow || \"auto\";\n // Get access token from big-brain\n // Default the device name to the hostname, but allow the user to change this if the terminal is interactive.\n // On Macs, the `hostname()` may be a weirdly-truncated form of the computer name. Attempt to read the \"real\" name before falling back to hostname.\n let deviceName = deviceNameOverride ?? \"\";\n if (!deviceName && process.platform === \"darwin\") {\n try {\n deviceName = execSync(\"scutil --get ComputerName\").toString().trim();\n } catch {\n // Just fall back to the hostname default below.\n }\n }\n if (!deviceName) {\n deviceName = hostname();\n }\n if (!deviceNameOverride) {\n logMessage(\n chalkStderr.bold(\n `Welcome to developing with Convex, let's get you logged in.`,\n ),\n );\n deviceName = await promptString(ctx, {\n message: \"Device name:\",\n default: deviceName,\n });\n }\n\n const issuer = overrideAuthUrl ?? \"https://auth.convex.dev\";\n let authIssuer;\n let accessToken: string;\n\n if (loginFlow === \"paste\" || (loginFlow === \"auto\" && isWebContainer())) {\n accessToken = await promptString(ctx, {\n message:\n \"Open https://dashboard.convex.dev/auth, log in and paste the token here:\",\n });\n } else {\n try {\n authIssuer = await Issuer.discover(issuer);\n } catch {\n // Couldn't contact https://auth.convex.dev/.well-known/openid-configuration,\n // proceed with manual auth.\n accessToken = await promptString(ctx, {\n message:\n \"Open https://dashboard.convex.dev/auth, log in and paste the token here:\",\n });\n }\n }\n\n // typical path\n if (authIssuer) {\n const clientId = overrideAuthClient ?? \"HFtA247jp9iNs08NTLIB7JsNPMmRIyfi\";\n const authClient = new authIssuer.Client({\n client_id: clientId,\n token_endpoint_auth_method: \"none\",\n id_token_signed_response_alg: \"RS256\",\n });\n\n if (overrideAccessToken) {\n accessToken = overrideAccessToken;\n } else if (overrideAuthUsername && overrideAuthPassword) {\n accessToken = await performPasswordAuthentication(\n ctx,\n clientId,\n overrideAuthUsername,\n overrideAuthPassword,\n );\n } else {\n accessToken = await performDeviceAuthorization(\n ctx,\n authClient,\n open ?? true,\n vercel,\n vercelOverride,\n );\n }\n }\n\n if (dumpAccessToken) {\n logOutput(`${accessToken!}`);\n return await ctx.crash({\n exitCode: 0,\n errorType: \"fatal\",\n printedMessage: null,\n });\n }\n\n const authorizeArgs: AuthorizeArgs = {\n authnToken: accessToken!,\n deviceName: deviceName,\n anonymousId: anonymousId,\n };\n const data = await bigBrainAPI({\n ctx,\n method: \"POST\",\n path: \"authorize\",\n data: authorizeArgs,\n });\n const globalConfig = { accessToken: data.accessToken };\n try {\n await modifyGlobalConfig(ctx, globalConfig);\n const path = globalConfigPath();\n logFinishedStep(`Saved credentials to ${formatPathForPrinting(path)}`);\n } catch (err: unknown) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"invalid filesystem data\",\n errForSentry: err,\n printedMessage: null,\n });\n }\n\n logVerbose(`performLogin: updating big brain auth after login`);\n await updateBigBrainAuthAfterLogin(ctx, data.accessToken);\n\n logVerbose(`performLogin: checking opt ins, acceptOptIns: ${acceptOptIns}`);\n // Do opt in to TOS and Privacy Policy stuff\n const shouldContinue = await optins(ctx, acceptOptIns ?? false);\n if (!shouldContinue) {\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n printedMessage: null,\n });\n }\n\n if (vercel) {\n await promptJoinVercelTeams(ctx);\n }\n}\n\ntype PotentialVercelTeam = {\n teamId: number;\n teamName: string;\n teamSlug: string;\n planId: string;\n planName: string;\n pricingNotice: string | null;\n};\n\n// After `--vercel` login, surface any Vercel-marketplace teams the user has\n// access to but isn't yet a member of, and prompt to join each.\nasync function promptJoinVercelTeams(ctx: Context): Promise<void> {\n const fetch = bigBrainFetch(ctx);\n let teams: PotentialVercelTeam[];\n try {\n const res = await fetch(\n new URL(\"vercel/potential_teams\", `${provisionHost}/`),\n );\n if (!res.ok) {\n logVerbose(\n `vercel/potential_teams returned ${res.status}; skipping team-join prompt`,\n );\n return;\n }\n teams = await res.json();\n } catch (err) {\n logVerbose(`Failed to fetch potential Vercel teams: ${String(err)}`);\n return;\n }\n if (teams.length === 0) return;\n\n for (const [index, team] of teams.entries()) {\n const displayName = team.teamName.replace(/ \\(Vercel\\)$/, \"\");\n const counter = teams.length > 1 ? `[${index + 1}/${teams.length}] ` : \"\";\n const lines = [\n chalkStderr.bold(`${counter}You've been invited to join ${displayName}`) +\n ` (${team.planName}) through the Vercel marketplace.`,\n ];\n if (team.pricingNotice) {\n lines.push(chalkStderr.yellow(team.pricingNotice));\n }\n lines.push(`Join \"${displayName}\"?`);\n const join = await promptYesNo(ctx, {\n message: `${lines.join(\"\\n\")}`,\n default: true,\n });\n if (!join) continue;\n try {\n await fetch(\n new URL(\n `vercel/potential_teams/${team.teamId}/join`,\n `${provisionHost}/`,\n ),\n { method: \"POST\" },\n );\n logFinishedStep(`Joined ${displayName}`);\n } catch (err) {\n logFailure(`Failed to join ${displayName}: ${String(err)}`);\n }\n }\n}\n\n/// There are fields like version, but we keep them opaque\ntype OptIn = Record<string, unknown>;\n\ntype OptInToAccept = {\n optIn: OptIn;\n message: string;\n};\n\ntype AcceptOptInsArgs = {\n optInsAccepted: OptIn[];\n};\n\n// Returns whether we can proceed or not.\nasync function optins(ctx: Context, acceptOptIns: boolean): Promise<boolean> {\n const bbAuth = ctx.bigBrainAuth();\n if (bbAuth === null) {\n // This should never happen, but if we're not even logged in, we can't proceed.\n return false;\n }\n switch (bbAuth.kind) {\n case \"accessToken\":\n break;\n case \"deploymentKey\":\n case \"projectKey\":\n case \"previewDeployKey\":\n // If we have a key configured as auth, we do not need to check opt ins.\n return true;\n default: {\n bbAuth satisfies never;\n return await ctx.crash({\n exitCode: 1,\n errorType: \"fatal\",\n errForSentry: `Unexpected auth kind ${(bbAuth as any).kind}`,\n printedMessage: \"Hit an unexpected error while logging in.\",\n });\n }\n }\n const data = await bigBrainAPI({\n ctx,\n method: \"POST\",\n path: \"check_opt_ins\",\n });\n if (data.optInsToAccept.length === 0) {\n return true;\n }\n for (const optInToAccept of data.optInsToAccept) {\n const confirmed =\n acceptOptIns ||\n (await promptYesNo(ctx, {\n message: optInToAccept.message,\n }));\n if (!confirmed) {\n logFailure(\"Please accept the Terms of Service to use Convex.\");\n return Promise.resolve(false);\n }\n }\n\n const optInsAccepted = data.optInsToAccept.map((o: OptInToAccept) => o.optIn);\n const args: AcceptOptInsArgs = { optInsAccepted };\n await bigBrainAPI({\n ctx,\n method: \"POST\",\n path: \"accept_opt_ins\",\n data: args,\n });\n return true;\n}\n\nexport async function ensureLoggedIn(\n ctx: Context,\n options?: {\n message?: string | undefined;\n overrideAuthUrl?: string | undefined;\n overrideAuthClient?: string | undefined;\n overrideAuthUsername?: string | undefined;\n overrideAuthPassword?: string | undefined;\n },\n) {\n const isLoggedIn = await checkAuthorization(ctx, false);\n if (!isLoggedIn) {\n if (options?.message) {\n logMessage(options.message);\n }\n await performLogin(ctx, {\n acceptOptIns: false,\n overrideAuthUrl: options?.overrideAuthUrl,\n overrideAuthClient: options?.overrideAuthClient,\n overrideAuthUsername: options?.overrideAuthUsername,\n overrideAuthPassword: options?.overrideAuthPassword,\n });\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAA2C;AAC3C,mBAMO;AACP,kBAAiB;AACjB,mBAA4B;AAC5B,oBAA8B;AAC9B,qBAAwB;AAExB,iBASO;AACP,IAAAA,wBAAuB;AACvB,gBAAyB;AACzB,2BAAyB;AACzB,qBAA0C;AAC1C,0BAIO;AACP,iCAA6C;AAG7C,4BAAO,uBAAuB;AAAA,EAC5B,SAAS,SAAS,QAAQ,IAAI,yBAAyB,OAAO;AAChE,CAAC;AAQD,eAAsB,mBACpB,KACA,cACkB;AAClB,QAAM,SAAS,IAAI,aAAa,GAAG,UAAU;AAC7C,MAAI,WAAW,MAAM;AACnB,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,OAAO,MAAM,MAAM,GAAG,2BAAa,kBAAkB;AAAA,MACzD,QAAQ;AAAA,MACR,SAAS;AAAA,QACP,eAAe;AAAA,QACf,iBAAiB,WAAW,sB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AAI,CAAC,WAAW;AACd,iCAAW,mDAAmD;AAC9D,aAAO,QAAQ,QAAQ,KAAK;AAAA,IAC9B;AAAA,EACF;AAEA,QAAM,iBAAiB,KAAK,eAAe,IAAI,CAAC,MAAqB,EAAE,KAAK;AAC5E,QAAM,OAAyB,EAAE,eAAe;AAChD,YAAM,0BAAY;AAAA,IAChB;AAAA,IACA,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,MAAM;AAAA,EACR,CAAC;AACD,SAAO;AACT;AAEA,eAAsB,eACpB,KACA,SAOA;AACA,QAAM,aAAa,MAAM,mBAAmB,KAAK,KAAK;AACtD,MAAI,CAAC,YAAY;AACf,QAAI,SAAS,SAAS;AACpB,iCAAW,QAAQ,OAAO;AAAA,IAC5B;AACA,UAAM,aAAa,KAAK;AAAA,MACtB,cAAc;AAAA,MACd,iBAAiB,SAAS;AAAA,MAC1B,oBAAoB,SAAS;AAAA,MAC7B,sBAAsB,SAAS;AAAA,MAC/B,sBAAsB,SAAS;AAAA,IACjC,CAAC;AAAA,EACH;AACF;",
6
+ "names": ["import_openid_client", "open", "fetch"]
7
7
  }
package/dist/cjs/index.js CHANGED
@@ -21,5 +21,5 @@ __export(index_exports, {
21
21
  version: () => version
22
22
  });
23
23
  module.exports = __toCommonJS(index_exports);
24
- const version = "1.36.0";
24
+ const version = "1.36.1";
25
25
  //# sourceMappingURL=index.js.map