wrangler 0.0.0-ece06ea → 0.0.0-ef13735

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 (63) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +35 -21
  3. package/pages/functions/buildWorker.ts +62 -0
  4. package/pages/functions/filepath-routing.test.ts +66 -0
  5. package/pages/functions/filepath-routing.ts +219 -0
  6. package/pages/functions/identifiers.ts +78 -0
  7. package/pages/functions/routes.ts +151 -0
  8. package/pages/functions/template-worker.ts +130 -0
  9. package/src/__tests__/dev.test.tsx +73 -0
  10. package/src/__tests__/guess-worker-format.test.ts +51 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  14. package/src/__tests__/helpers/mock-bin.ts +33 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +207 -0
  16. package/src/__tests__/helpers/mock-console.ts +56 -0
  17. package/src/__tests__/helpers/mock-dialogs.ts +65 -0
  18. package/src/__tests__/helpers/mock-kv.ts +40 -0
  19. package/src/__tests__/helpers/mock-user.ts +27 -0
  20. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  21. package/src/__tests__/helpers/run-wrangler.ts +14 -0
  22. package/src/__tests__/index.test.ts +715 -119
  23. package/src/__tests__/jest.setup.ts +37 -0
  24. package/src/__tests__/kv.test.ts +1139 -0
  25. package/src/__tests__/logout.test.ts +50 -0
  26. package/src/__tests__/package-manager.test.ts +206 -0
  27. package/src/__tests__/publish.test.ts +1381 -0
  28. package/src/__tests__/secret.test.ts +210 -0
  29. package/src/__tests__/whoami.test.tsx +86 -0
  30. package/src/api/form_data.ts +93 -100
  31. package/src/api/preview.ts +29 -24
  32. package/src/api/worker.ts +55 -47
  33. package/src/cfetch/index.ts +102 -0
  34. package/src/cfetch/internal.ts +101 -0
  35. package/src/cli.ts +6 -7
  36. package/src/config.ts +641 -112
  37. package/src/dev.tsx +476 -355
  38. package/src/dialogs.tsx +6 -14
  39. package/src/guess-worker-format.ts +66 -0
  40. package/src/index.tsx +828 -496
  41. package/src/inspect.ts +596 -0
  42. package/src/kv.tsx +118 -45
  43. package/src/module-collection.ts +63 -0
  44. package/src/open-in-browser.ts +13 -0
  45. package/src/package-manager.ts +120 -0
  46. package/src/pages.tsx +915 -215
  47. package/src/paths.ts +26 -0
  48. package/src/proxy.ts +370 -0
  49. package/src/publish.ts +349 -290
  50. package/src/sites.tsx +184 -55
  51. package/src/tail.tsx +5 -3
  52. package/src/user.tsx +81 -91
  53. package/src/whoami.tsx +69 -0
  54. package/templates/new-worker.js +15 -0
  55. package/templates/new-worker.ts +15 -0
  56. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  57. package/wrangler-dist/cli.js +119231 -130682
  58. package/wrangler-dist/cli.js.map +3 -3
  59. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  60. package/src/__tests__/mock-cfetch.js +0 -46
  61. package/src/api/inspect.ts +0 -441
  62. package/src/cfetch.ts +0 -72
  63. package/src/util/fetch.ts +0 -74
package/src/index.tsx CHANGED
@@ -1,23 +1,19 @@
1
- import React from "react";
1
+ import * as fs from "node:fs";
2
+ import { readFile, writeFile, mkdir } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { setTimeout } from "node:timers/promises";
5
+ import TOML from "@iarna/toml";
6
+ import { findUp } from "find-up";
2
7
  import { render } from "ink";
3
- import { Dev } from "./dev";
4
- import { readFile } from "node:fs/promises";
8
+ import React from "react";
9
+ import onExit from "signal-exit";
5
10
  import makeCLI from "yargs";
6
- import { hideBin } from "yargs/helpers";
7
- import type yargs from "yargs";
8
- import { findUp } from "find-up";
9
- import TOML from "@iarna/toml";
10
- import type { Config } from "./config";
11
- import { confirm, prompt } from "./dialogs";
12
11
  import { version as wranglerVersion } from "../package.json";
13
- import {
14
- login,
15
- logout,
16
- listScopes,
17
- initialise as initialiseUserConfig,
18
- loginOrRefreshIfRequired,
19
- getAccountId,
20
- } from "./user";
12
+ import { toFormData } from "./api/form_data";
13
+ import { fetchResult } from "./cfetch";
14
+ import { normaliseAndValidateEnvironmentsConfig } from "./config";
15
+ import Dev from "./dev";
16
+ import { confirm, prompt } from "./dialogs";
21
17
  import {
22
18
  getNamespaceId,
23
19
  listNamespaces,
@@ -25,80 +21,70 @@ import {
25
21
  putKeyValue,
26
22
  putBulkKeyValue,
27
23
  deleteBulkKeyValue,
24
+ createNamespace,
25
+ isValidNamespaceBinding,
26
+ getKeyValue,
28
27
  } from "./kv";
29
-
28
+ import { getPackageManager } from "./package-manager";
30
29
  import { pages } from "./pages";
31
-
32
- import cfetch from "./cfetch";
33
-
34
30
  import publish from "./publish";
35
- import path from "path/posix";
36
- import { writeFile } from "node:fs/promises";
37
- import { toFormData } from "./api/form_data";
38
-
31
+ import { getAssetPaths } from "./sites";
39
32
  import { createTail } from "./tail";
40
- import onExit from "signal-exit";
41
- import { setTimeout } from "node:timers/promises";
42
- import * as fs from "node:fs";
43
- import { execa } from "execa";
33
+ import {
34
+ login,
35
+ logout,
36
+ listScopes,
37
+ initialise as initialiseUserConfig,
38
+ loginOrRefreshIfRequired,
39
+ getAccountId,
40
+ validateScopeKeys,
41
+ } from "./user";
42
+ import { whoami } from "./whoami";
43
+
44
+ import type { Config } from "./config";
45
+ import type Yargs from "yargs";
46
+
47
+ const resetColor = "\x1b[0m";
48
+ const fgGreenColor = "\x1b[32m";
44
49
 
45
- async function readConfig(path?: string): Promise<Config> {
50
+ async function readConfig(configPath?: string): Promise<Config> {
46
51
  const config: Config = {};
47
- if (!path) {
48
- path = await findUp("wrangler.toml");
52
+ if (!configPath) {
53
+ configPath = await findUp("wrangler.toml");
49
54
  // TODO - terminate this early instead of going all the way to the root
50
55
  }
51
56
 
52
- if (path) {
53
- const tml: string = await readFile(path, "utf-8");
57
+ if (configPath) {
58
+ const tml: string = await readFile(configPath, "utf-8");
54
59
  const parsed = TOML.parse(tml) as Config;
55
60
  Object.assign(config, parsed);
56
61
  }
57
62
 
58
- const inheritedFields = [
59
- "name",
60
- "account_id",
61
- "workers_dev",
62
- "compatibility_date",
63
- "compatibility_flags",
64
- "zone_id",
65
- "routes",
66
- "route",
67
- "jsx_factory",
68
- "jsx_fragment",
69
- "polyfill_node",
70
- "site",
71
- "triggers",
72
- "usage_model",
73
- ];
74
-
75
- Object.keys(config.env || {}).forEach((env) => {
76
- inheritedFields.forEach((field) => {
77
- if (config[field] !== undefined && config.env[env][field] === undefined) {
78
- config.env[env][field] = config[field]; // TODO: - shallow copy?
79
- }
80
- });
81
- });
82
-
83
- const mirroredFields = ["vars", "kv_namespaces", "durable_objects"];
84
- Object.keys(config.env || {}).forEach((env) => {
85
- mirroredFields.forEach((field) => {
86
- // if it exists on top level, it should exist on env defns
87
- Object.keys(config[field] || {}).forEach((fieldKey) => {
88
- if (!(fieldKey in config.env[env][field])) {
89
- console.error(
90
- `In your configuration, "${field}.${fieldKey}" exists at a top level, but not on "env.${env}". This is not what you probably want, since the field "${field}" is not inherited by environments. Please add "${field}.${fieldKey}" to "env.${env}".`
91
- );
92
- }
93
- });
94
- });
95
- });
63
+ normaliseAndValidateEnvironmentsConfig(config);
64
+
65
+ if ("experimental_services" in config) {
66
+ console.warn(
67
+ "The experimental_services field is only for cloudflare internal usage right now, and is subject to change. Please do not use this on production projects"
68
+ );
69
+ }
70
+
71
+ if (configPath && "wasm_modules" in config) {
72
+ // rewrite wasm_module paths to be absolute
73
+ const modules = {};
74
+ for (const [name, filePath] of Object.entries(config.wasm_modules || {})) {
75
+ modules[name] = path.relative(
76
+ process.cwd(),
77
+ path.join(path.dirname(configPath), filePath)
78
+ );
79
+ }
80
+ config.wasm_modules = modules;
81
+ }
96
82
 
97
83
  // todo: validate, add defaults
98
84
  // let's just do some basics for now
99
85
 
100
- // @ts-expect-error we're being sneaky here for now
101
- config.__path__ = path;
86
+ // @ts-expect-error we're being sneaky here
87
+ config.__path__ = configPath;
102
88
 
103
89
  return config;
104
90
  }
@@ -106,18 +92,18 @@ async function readConfig(path?: string): Promise<Config> {
106
92
  // a helper to demand one of a set of options
107
93
  // via https://github.com/yargs/yargs/issues/1093#issuecomment-491299261
108
94
  function demandOneOfOption(...options: string[]) {
109
- return function (argv: yargs.Arguments) {
95
+ return function (argv: Yargs.Arguments) {
110
96
  const count = options.filter((option) => argv[option]).length;
111
97
  const lastOption = options.pop();
112
98
 
113
99
  if (count === 0) {
114
- throw new Error(
100
+ throw new CommandLineArgsError(
115
101
  `Exactly one of the arguments ${options.join(
116
102
  ", "
117
103
  )} and ${lastOption} is required`
118
104
  );
119
105
  } else if (count > 1) {
120
- throw new Error(
106
+ throw new CommandLineArgsError(
121
107
  `Arguments ${options.join(
122
108
  ", "
123
109
  )} and ${lastOption} are mutually exclusive`
@@ -128,30 +114,49 @@ function demandOneOfOption(...options: string[]) {
128
114
  };
129
115
  }
130
116
 
117
+ class CommandLineArgsError extends Error {}
118
+ class DeprecationError extends Error {}
119
+ class NotImplementedError extends Error {}
120
+
131
121
  export async function main(argv: string[]): Promise<void> {
132
- const yargs = makeCLI(hideBin(process.argv))
133
- .command(
134
- // the default is to simply print the help menu
135
- ["*"],
136
- false,
137
- () => {},
138
- () => {
139
- yargs.showHelp("log");
122
+ const wrangler = makeCLI(argv)
123
+ // We handle errors ourselves in a try-catch around `yargs.parse`.
124
+ // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
125
+ // Otherwise we just log the error that was thrown without any "help info".
126
+ .showHelpOnFail(false)
127
+ .fail((msg, error) => {
128
+ if (!error) {
129
+ // If there is only a `msg` then this came from yargs own validation, so wrap in a `CommandLineArgsError`.
130
+ error = new CommandLineArgsError(msg);
140
131
  }
141
- )
132
+ throw error;
133
+ })
142
134
  .scriptName("wrangler")
143
135
  .wrap(null);
144
136
 
145
- // you will note that we use the form for all commands where we use the builder function
146
- // to define options and subcommands. Further we return the result of this builder even
147
- // tho it's not completely necessary. The reason is that it's required for type inference
148
- // of the args in the handle function.I wish we could enforce this pattern, but this
149
- // comment will have to do for now.
137
+ // the default is to simply print the help menu
138
+ wrangler.command(
139
+ ["*"],
140
+ false,
141
+ () => {},
142
+ (args) => {
143
+ if (args._.length > 0) {
144
+ throw new CommandLineArgsError(`Unknown command: ${args._}.`);
145
+ } else {
146
+ wrangler.showHelp("log");
147
+ }
148
+ }
149
+ );
150
150
 
151
- // also annoying that choices[] doesn't get inferred as an enum. bleh.
151
+ // You will note that we use the form for all commands where we use the builder function
152
+ // to define options and subcommands.
153
+ // Further we return the result of this builder even though it's not completely necessary.
154
+ // The reason is that it's required for type inference of the args in the handle function.
155
+ // I wish we could enforce this pattern, but this comment will have to do for now.
156
+ // (It's also annoying that choices[] doesn't get inferred as an enum. 🤷‍♂.)
152
157
 
153
158
  // [DEPRECATED] generate
154
- yargs.command(
159
+ wrangler.command(
155
160
  // we definitely want to move away from us cloning github templates
156
161
  // we can do something better here, let's see
157
162
  "generate [name] [template]",
@@ -169,14 +174,14 @@ export async function main(argv: string[]): Promise<void> {
169
174
  },
170
175
  () => {
171
176
  // "👯 [DEPRECATED]. Scaffold a Cloudflare Workers project from a public GitHub repository.",
172
- console.error(
177
+ throw new DeprecationError(
173
178
  "`wrangler generate` has been deprecated, please refer to TODO://some/path for alternatives"
174
179
  );
175
180
  }
176
181
  );
177
182
 
178
183
  // init
179
- yargs.command(
184
+ wrangler.command(
180
185
  "init [name]",
181
186
  "📥 Create a wrangler.toml configuration file",
182
187
  (yargs) => {
@@ -185,65 +190,119 @@ export async function main(argv: string[]): Promise<void> {
185
190
  type: "string",
186
191
  });
187
192
  },
188
- async () => {
189
- const destination = path.join(process.cwd(), "wrangler.toml");
193
+ async (args) => {
194
+ if ("type" in args) {
195
+ let message = "The --type option is no longer supported.";
196
+ if (args.type === "webpack") {
197
+ message +=
198
+ "\nIf you wish to use webpack then you will need to create a custom build.";
199
+ // TODO: Add a link to docs
200
+ }
201
+ throw new CommandLineArgsError(message);
202
+ }
203
+
204
+ const packageManager = await getPackageManager(process.cwd());
205
+
206
+ const destination = "./wrangler.toml";
190
207
  if (fs.existsSync(destination)) {
191
- console.error(`${destination} already exists.`);
208
+ console.warn(`${destination} file already exists!`);
209
+ const shouldContinue = await confirm(
210
+ "Do you want to continue initializing this project?"
211
+ );
212
+ if (!shouldContinue) {
213
+ return;
214
+ }
192
215
  } else {
193
216
  const compatibilityDate = new Date().toISOString().substring(0, 10);
194
217
  try {
195
218
  await writeFile(
196
219
  destination,
197
- `compatibility_date = "${compatibilityDate}"` + "\n"
220
+ TOML.stringify({
221
+ name: args.name || path.basename(path.resolve(process.cwd())),
222
+ compatibility_date: compatibilityDate,
223
+ }) + "\n"
198
224
  );
199
- console.log(`✨ Succesfully created wrangler.toml`);
225
+ console.log(`✨ Successfully created wrangler.toml`);
200
226
  // TODO: suggest next steps?
201
227
  } catch (err) {
202
- console.error(`Failed to create wrangler.toml`);
203
- console.error(err);
204
- throw err;
228
+ throw new Error(
229
+ `Failed to create wrangler.toml.\n${err.message ?? err}`
230
+ );
205
231
  }
206
232
  }
207
233
 
208
- // if no package.json, ask, and if yes, create one
209
234
  let pathToPackageJson = await findUp("package.json");
210
-
235
+ let shouldCreatePackageJson = false;
211
236
  if (!pathToPackageJson) {
212
- if (
213
- await confirm("No package.json found. Would you like to create one?")
214
- ) {
237
+ // If no package.json exists, ask to create one
238
+ shouldCreatePackageJson = await confirm(
239
+ "No package.json found. Would you like to create one?"
240
+ );
241
+ if (shouldCreatePackageJson) {
215
242
  await writeFile(
216
- path.join(process.cwd(), "package.json"),
243
+ "./package.json",
217
244
  JSON.stringify(
218
245
  {
219
- name: "worker",
220
- version: "0.0.1",
246
+ name: args.name || path.basename(path.resolve(process.cwd())),
247
+ version: "0.0.0",
248
+ devDependencies: {
249
+ wrangler: wranglerVersion,
250
+ },
251
+ private: true,
221
252
  },
222
253
  null,
223
254
  " "
224
255
  ) + "\n"
225
256
  );
257
+ await packageManager.install();
226
258
  console.log(`✨ Created package.json`);
227
259
  pathToPackageJson = path.join(process.cwd(), "package.json");
228
260
  } else {
229
261
  return;
230
262
  }
263
+ } else {
264
+ // If package.json exists and wrangler isn't installed,
265
+ // then ask to add wrangler to devDependencies
266
+ const packageJson = JSON.parse(
267
+ await readFile(pathToPackageJson, "utf-8")
268
+ );
269
+ if (
270
+ !(
271
+ packageJson.devDependencies?.wrangler ||
272
+ packageJson.dependencies?.wrangler
273
+ )
274
+ ) {
275
+ const shouldInstall = await confirm(
276
+ "Would you like to install wrangler into your package.json?"
277
+ );
278
+ if (shouldInstall) {
279
+ await packageManager.addDevDeps(`wrangler@${wranglerVersion}`);
280
+ console.log(`✨ Installed wrangler`);
281
+ }
282
+ }
231
283
  }
232
284
 
233
- // if workers-types doesn't exist as a dependency
234
- // offer to install it
235
- // and make a tsconfig?
285
+ let isTypescriptProject = false;
236
286
  let pathToTSConfig = await findUp("tsconfig.json");
237
287
  if (!pathToTSConfig) {
238
- if (await confirm("Would you like to use typescript?")) {
288
+ // If there's no tsconfig, offer to create one
289
+ // and install @cloudflare/workers-types
290
+ if (await confirm("Would you like to use TypeScript?")) {
291
+ isTypescriptProject = true;
239
292
  await writeFile(
240
- path.join(process.cwd(), "tsconfig.json"),
293
+ "./tsconfig.json",
241
294
  JSON.stringify(
242
295
  {
243
296
  compilerOptions: {
244
- target: "ES2020",
245
- module: "CommonJS",
246
- lib: ["ES2020"],
297
+ target: "es2021",
298
+ module: "es2022",
299
+ moduleResolution: "node",
300
+ allowJs: true,
301
+ allowSyntheticDefaultImports: true,
302
+ isolatedModules: true,
303
+ noEmit: true,
304
+ lib: ["es2021"],
305
+ resolveJsonModule: true,
247
306
  types: ["@cloudflare/workers-types"],
248
307
  },
249
308
  },
@@ -251,22 +310,140 @@ export async function main(argv: string[]): Promise<void> {
251
310
  " "
252
311
  ) + "\n"
253
312
  );
254
- await execa("npm", [
255
- "install",
313
+ await packageManager.addDevDeps(
256
314
  "@cloudflare/workers-types",
257
- "--save-dev",
258
- ]);
315
+ "typescript"
316
+ );
317
+
259
318
  console.log(
260
319
  `✨ Created tsconfig.json, installed @cloudflare/workers-types into devDependencies`
261
320
  );
262
321
  pathToTSConfig = path.join(process.cwd(), "tsconfig.json");
263
322
  }
323
+ } else {
324
+ isTypescriptProject = true;
325
+ // If there's a tsconfig, check if @cloudflare/workers-types
326
+ // is already installed, and offer to install it if not
327
+ const packageJson = JSON.parse(
328
+ await readFile(pathToPackageJson, "utf-8")
329
+ );
330
+ if (
331
+ !(
332
+ packageJson.devDependencies?.["@cloudflare/workers-types"] ||
333
+ packageJson.dependencies?.["@cloudflare/workers-types"]
334
+ )
335
+ ) {
336
+ const shouldInstall = await confirm(
337
+ "Would you like to install the type definitions for Workers into your package.json?"
338
+ );
339
+ if (shouldInstall) {
340
+ await packageManager.addDevDeps("@cloudflare/workers-types");
341
+ // We don't update the tsconfig.json because
342
+ // it could be complicated in existing projects
343
+ // and we don't want to break them. Instead, we simply
344
+ // tell the user that they need to update their tsconfig.json
345
+ console.log(
346
+ `✨ Installed @cloudflare/workers-types.\nPlease add "@cloudflare/workers-types" to compilerOptions.types in your tsconfig.json`
347
+ );
348
+ }
349
+ }
350
+ }
351
+
352
+ const packageJsonContent = JSON.parse(
353
+ await readFile(pathToPackageJson, "utf-8")
354
+ );
355
+ const shouldWritePackageJsonScripts =
356
+ !packageJsonContent.scripts?.start &&
357
+ !packageJsonContent.scripts?.deploy &&
358
+ shouldCreatePackageJson;
359
+ async function writePackageJsonScripts(
360
+ isWritingScripts: boolean,
361
+ packagePath: string,
362
+ scriptPath: string
363
+ ) {
364
+ if (isWritingScripts) {
365
+ await writeFile(
366
+ packagePath,
367
+ JSON.stringify(
368
+ {
369
+ ...packageJsonContent,
370
+ scripts: {
371
+ ...packageJsonContent.scripts,
372
+ start: `wrangler dev ${scriptPath}`,
373
+ deploy: `wrangler publish ${scriptPath}`,
374
+ },
375
+ },
376
+ null,
377
+ " "
378
+ ) + "\n"
379
+ );
380
+ console.log(`To start developing on your worker, run npm start.`);
381
+ console.log(
382
+ `To publish your worker on to the internet, run npm run deploy.`
383
+ );
384
+ } else {
385
+ console.log(
386
+ `To start developing on your worker, npx wrangler dev ${scriptPath}`
387
+ );
388
+ console.log(
389
+ `To publish your worker on to the internet, npx wrangler publish ${scriptPath}`
390
+ );
391
+ }
392
+ }
393
+ if (isTypescriptProject) {
394
+ if (!fs.existsSync("./src/index.ts")) {
395
+ const shouldCreateSource = await confirm(
396
+ `Would you like to create a Worker at src/index.ts?`
397
+ );
398
+ if (shouldCreateSource) {
399
+ await mkdir("./src", { recursive: true });
400
+ await writeFile(
401
+ "./src/index.ts",
402
+ await readFile(
403
+ path.join(__dirname, "../templates/new-worker.ts"),
404
+ "utf-8"
405
+ )
406
+ );
407
+
408
+ await writePackageJsonScripts(
409
+ shouldWritePackageJsonScripts,
410
+ pathToPackageJson,
411
+ "src/index.ts"
412
+ );
413
+
414
+ console.log(`✨ Created src/index.ts`);
415
+ }
416
+ }
417
+ } else {
418
+ if (!fs.existsSync("./src/index.js")) {
419
+ const shouldCreateSource = await confirm(
420
+ `Would you like to create a Worker at src/index.js?`
421
+ );
422
+ if (shouldCreateSource) {
423
+ await mkdir("./src", { recursive: true });
424
+ await writeFile(
425
+ path.join("./src/index.js"),
426
+ await readFile(
427
+ path.join(__dirname, "../templates/new-worker.js"),
428
+ "utf-8"
429
+ )
430
+ );
431
+
432
+ await writePackageJsonScripts(
433
+ shouldWritePackageJsonScripts,
434
+ pathToPackageJson,
435
+ "src/index.js"
436
+ );
437
+
438
+ console.log(`✨ Created src/index.js`);
439
+ }
440
+ }
264
441
  }
265
442
  }
266
443
  );
267
444
 
268
445
  // build
269
- yargs.command(
446
+ wrangler.command(
270
447
  "build",
271
448
  false,
272
449
  (yargs) => {
@@ -276,14 +453,14 @@ export async function main(argv: string[]): Promise<void> {
276
453
  },
277
454
  () => {
278
455
  // "[DEPRECATED] 🦀 Build your project (if applicable)",
279
- console.error(
456
+ throw new DeprecationError(
280
457
  "`wrangler build` has been deprecated, please refer to TODO://some/path for alternatives"
281
458
  );
282
459
  }
283
460
  );
284
461
 
285
462
  // login
286
- yargs.command(
463
+ wrangler.command(
287
464
  // this needs scopes as an option?
288
465
  "login",
289
466
  false, // we don't need to show this in the menu
@@ -314,19 +491,24 @@ export async function main(argv: string[]): Promise<void> {
314
491
  listScopes();
315
492
  return;
316
493
  }
494
+ if (!validateScopeKeys(args.scopes)) {
495
+ throw new CommandLineArgsError(
496
+ `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
497
+ );
498
+ }
317
499
  await login({ scopes: args.scopes });
318
500
  return;
319
501
  }
320
502
  await login();
321
503
 
322
504
  // TODO: would be nice if it optionally saved login
323
- // creds inside node_modules/.cache or something
505
+ // credentials inside node_modules/.cache or something
324
506
  // this way you could have multiple users on a single machine
325
507
  }
326
508
  );
327
509
 
328
510
  // logout
329
- yargs.command(
511
+ wrangler.command(
330
512
  // this needs scopes as an option?
331
513
  "logout",
332
514
  false, // we don't need to show this in the menu
@@ -338,36 +520,39 @@ export async function main(argv: string[]): Promise<void> {
338
520
  );
339
521
 
340
522
  // whoami
341
- yargs.command(
523
+ wrangler.command(
342
524
  "whoami",
343
- false, // we don't need to show this the menu
344
- // "🕵️ Retrieve your user info and test your auth config",
525
+ "🕵️ Retrieve your user info and test your auth config",
345
526
  () => {},
346
- (args) => {
347
- console.log(":whoami", args);
527
+ async () => {
528
+ await whoami();
348
529
  }
349
530
  );
350
531
 
351
532
  // config
352
- yargs.command(
533
+ wrangler.command(
353
534
  "config",
354
535
  false,
355
536
  () => {},
356
537
  () => {
357
538
  // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
358
- console.error(
539
+ throw new DeprecationError(
359
540
  "`wrangler config` has been deprecated, please refer to TODO://some/path for alternatives"
360
541
  );
361
542
  }
362
543
  );
363
544
 
364
545
  // dev
365
- yargs.command(
546
+ wrangler.command(
366
547
  "dev <filename>",
367
548
  "👂 Start a local server for developing your worker",
368
549
  (yargs) => {
369
550
  return yargs
370
- .positional("filename", { describe: "entry point", type: "string" })
551
+ .positional("filename", {
552
+ describe: "entry point",
553
+ type: "string",
554
+ demandOption: true,
555
+ })
371
556
  .option("name", {
372
557
  describe: "name of the script",
373
558
  type: "string",
@@ -381,6 +566,20 @@ export async function main(argv: string[]): Promise<void> {
381
566
  type: "string",
382
567
  // TODO: get choices for the toml file?
383
568
  })
569
+ .option("compatibility-date", {
570
+ describe: "Date to use for compatibility checks",
571
+ type: "string",
572
+ })
573
+ .option("compatibility-flags", {
574
+ describe: "Flags to use for compatibility checks",
575
+ type: "array",
576
+ alias: "compatibility-flag",
577
+ })
578
+ .option("latest", {
579
+ describe: "Use the latest version of the worker runtime",
580
+ type: "boolean",
581
+ default: true,
582
+ })
384
583
  .option("ip", {
385
584
  describe: "IP address to listen on",
386
585
  type: "string",
@@ -401,7 +600,7 @@ export async function main(argv: string[]): Promise<void> {
401
600
  describe: "Protocol to listen to requests on, defaults to http.",
402
601
  choices: ["http", "https"],
403
602
  })
404
- .option("public", {
603
+ .option("experimental-public", {
405
604
  describe: "Static assets to be served",
406
605
  type: "string",
407
606
  })
@@ -409,6 +608,18 @@ export async function main(argv: string[]): Promise<void> {
409
608
  describe: "Root folder of static assets for Workers Sites",
410
609
  type: "string",
411
610
  })
611
+ .option("site-include", {
612
+ describe:
613
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
614
+ type: "string",
615
+ array: true,
616
+ })
617
+ .option("site-exclude", {
618
+ describe:
619
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
620
+ type: "string",
621
+ array: true,
622
+ })
412
623
  .option("upstream-protocol", {
413
624
  default: "https",
414
625
  describe:
@@ -423,89 +634,134 @@ export async function main(argv: string[]): Promise<void> {
423
634
  describe: "The function that is called for each JSX fragment",
424
635
  type: "string",
425
636
  })
426
- .option("polyfill-node", {
427
- describe: "Try to polyfill node builtins",
637
+ .option("experimental-enable-local-persistence", {
638
+ describe: "Enable persistence for this session (only for local mode)",
428
639
  type: "boolean",
429
640
  });
430
641
  },
431
642
  async (args) => {
432
- const { filename, format } = args;
643
+ const { filename } = args;
433
644
  const config = args.config as Config;
434
645
 
435
- // -- snip, extract --
646
+ if (args["experimental-public"]) {
647
+ console.warn(
648
+ "🚨 The --experimental-public field is experimental and will change in the future."
649
+ );
650
+ }
651
+
652
+ if (args.public) {
653
+ throw new Error(
654
+ "🚨 The --public field has been renamed to --experimental-public, and will change behaviour in the future."
655
+ );
656
+ }
657
+
658
+ if (config.site?.["entry-point"]) {
659
+ console.warn(
660
+ "Deprecation notice: The `site.entry-point` config field is no longer used.\n" +
661
+ "The entry-point is specified via the command line (e.g. `wrangler dev path/to/script`).\n" +
662
+ "Please remove the `site.entry-point` field from the `wrangler.toml` file."
663
+ );
664
+ }
436
665
 
437
666
  if (!args.local) {
667
+ // -- snip, extract --
438
668
  const loggedIn = await loginOrRefreshIfRequired();
439
669
  if (!loggedIn) {
440
670
  // didn't login, let's just quit
441
671
  console.log("Did not login, quitting...");
442
672
  return;
443
673
  }
674
+
444
675
  if (!config.account_id) {
445
676
  config.account_id = await getAccountId();
446
677
  if (!config.account_id) {
447
- console.error("No account id found, quitting...");
448
- return;
678
+ throw new Error("No account id found, quitting...");
449
679
  }
450
680
  }
681
+ // -- snip, end --
451
682
  }
452
683
 
453
- // -- snip, end --
454
-
455
- const envRootObj = args.env ? config.env[args.env] || {} : config;
684
+ const environments = config.env ?? {};
685
+ const envRootObj = args.env ? environments[args.env] || {} : config;
456
686
 
457
- const polyfillNode = args["polyfill-node"] ?? config.polyfill_node;
458
- if (polyfillNode) {
459
- console.warn(
460
- "Using polyfills for node builtin modules. These are not meant to be completely reliable, and have serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
461
- );
687
+ // TODO: this error shouldn't actually happen,
688
+ // but we haven't fixed it internally yet
689
+ if ("durable_objects" in envRootObj) {
690
+ if (!(args.name || config.name)) {
691
+ console.warn(
692
+ 'A worker with durable objects needs to be named, or it may not work as expected. Add a "name" into wrangler.toml, or pass it in the command line with --name.'
693
+ );
694
+ }
695
+ // TODO: if not already published, publish a draft worker
462
696
  }
463
697
 
464
- render(
698
+ const { waitUntilExit } = render(
465
699
  <Dev
466
700
  name={args.name || config.name}
467
- entry={filename}
468
- format={format}
701
+ entry={path.relative(process.cwd(), filename)}
702
+ env={args.env}
703
+ buildCommand={config.build || {}}
704
+ format={args.format || config.build?.upload?.format}
469
705
  initialMode={args.local ? "local" : "remote"}
470
706
  jsxFactory={args["jsx-factory"] || envRootObj?.jsx_factory}
471
707
  jsxFragment={args["jsx-fragment"] || envRootObj?.jsx_fragment}
708
+ enableLocalPersistence={
709
+ args["experimental-enable-local-persistence"] || false
710
+ }
472
711
  accountId={config.account_id}
473
- site={args.site || config.site?.bucket}
712
+ assetPaths={getAssetPaths(
713
+ config,
714
+ args.site,
715
+ args.siteInclude,
716
+ args.siteExclude
717
+ )}
474
718
  port={args.port || config.dev?.port}
475
- polyfillNode={polyfillNode}
476
- public={args.public}
477
- compatibilityDate={config.compatibility_date}
478
- compatibilityFlags={config.compatibility_flags}
719
+ public={args["experimental-public"]}
720
+ compatibilityDate={
721
+ args["compatibility-date"] ||
722
+ config.compatibility_date ||
723
+ new Date().toISOString().substring(0, 10)
724
+ }
725
+ compatibilityFlags={
726
+ (args["compatibility-flags"] as string[]) ||
727
+ config.compatibility_flags
728
+ }
479
729
  usageModel={config.usage_model}
480
- variables={{
481
- ...(envRootObj?.vars || {}),
482
- ...(envRootObj?.kv_namespaces || []).reduce(
483
- (obj, { binding, preview_id }) => {
730
+ bindings={{
731
+ kv_namespaces: envRootObj.kv_namespaces?.map(
732
+ ({ binding, preview_id, id: _id }) => {
733
+ // In `dev`, we make folks use a separate kv namespace called
734
+ // `preview_id` instead of `id` so that they don't
735
+ // break production data. So here we check that a `preview_id`
736
+ // has actually been configured.
737
+ // This whole block of code will be obsoleted in the future
738
+ // when we have copy-on-write for previews on edge workers.
484
739
  if (!preview_id) {
485
740
  // TODO: This error has to be a _lot_ better, ideally just asking
486
741
  // to create a preview namespace for the user automatically
487
742
  throw new Error(
488
- "kv namespaces need a preview id during dev mode"
489
- );
743
+ `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
744
+ ); // Ugh, I really don't like this message very much
490
745
  }
491
- return { ...obj, [binding]: { namespaceId: preview_id } };
492
- },
493
- {}
494
- ),
495
- ...(envRootObj?.durable_objects?.bindings || []).reduce(
496
- (obj, { name, class_name, script_name }) => {
497
- return { ...obj, [name]: { class_name, script_name } };
498
- },
499
- {}
746
+ return {
747
+ binding,
748
+ id: preview_id,
749
+ };
750
+ }
500
751
  ),
752
+ vars: envRootObj.vars,
753
+ wasm_modules: config.wasm_modules,
754
+ durable_objects: envRootObj.durable_objects,
755
+ services: envRootObj.experimental_services,
501
756
  }}
502
757
  />
503
758
  );
759
+ await waitUntilExit();
504
760
  }
505
761
  );
506
762
 
507
763
  // publish
508
- yargs.command(
764
+ wrangler.command(
509
765
  "publish [script]",
510
766
  "🆙 Publish your Worker to Cloudflare.",
511
767
  (yargs) => {
@@ -522,7 +778,25 @@ export async function main(argv: string[]): Promise<void> {
522
778
  describe: "name to use when uploading",
523
779
  type: "string",
524
780
  })
525
- .option("public", {
781
+ .option("format", {
782
+ choices: ["modules", "service-worker"] as const,
783
+ describe: "Choose an entry type",
784
+ })
785
+ .option("compatibility-date", {
786
+ describe: "Date to use for compatibility checks",
787
+ type: "string",
788
+ })
789
+ .option("compatibility-flags", {
790
+ describe: "Flags to use for compatibility checks",
791
+ type: "array",
792
+ alias: "compatibility-flag",
793
+ })
794
+ .option("latest", {
795
+ describe: "Use the latest version of the worker runtime",
796
+ type: "boolean",
797
+ default: false,
798
+ })
799
+ .option("experimental-public", {
526
800
  describe: "Static assets to be served",
527
801
  type: "string",
528
802
  })
@@ -530,6 +804,18 @@ export async function main(argv: string[]): Promise<void> {
530
804
  describe: "Root folder of static assets for Workers Sites",
531
805
  type: "string",
532
806
  })
807
+ .option("site-include", {
808
+ describe:
809
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
810
+ type: "string",
811
+ array: true,
812
+ })
813
+ .option("site-exclude", {
814
+ describe:
815
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
816
+ type: "string",
817
+ array: true,
818
+ })
533
819
  .option("triggers", {
534
820
  describe: "cron schedules to attach",
535
821
  alias: ["schedule", "schedules"],
@@ -553,63 +839,81 @@ export async function main(argv: string[]): Promise<void> {
553
839
  .option("jsx-fragment", {
554
840
  describe: "The function that is called for each JSX fragment",
555
841
  type: "string",
556
- })
557
- .option("polyfill-node", {
558
- describe: "Try to polyfill node builtins",
559
- type: "boolean",
560
842
  });
561
843
  },
562
844
  async (args) => {
563
845
  if (args.local) {
564
- console.error("🚫 Local publishing is not yet supported");
565
- return;
846
+ throw new NotImplementedError(
847
+ "🚫 Local publishing is not yet supported"
848
+ );
849
+ }
850
+
851
+ if (args["experimental-public"]) {
852
+ console.warn(
853
+ "🚨 The --experimental-public field is experimental and will change in the future."
854
+ );
855
+ }
856
+ if (args.public) {
857
+ throw new Error(
858
+ "🚨 The --public field has been renamed to --experimental-public, and will change behaviour in the future."
859
+ );
566
860
  }
861
+
567
862
  const config = args.config as Config;
568
863
 
569
- // -- snip, extract --
864
+ if (args.latest) {
865
+ console.warn(
866
+ "⚠️ Using the latest version of the Workers runtime. To silence this warning, please choose a specific version of the runtime with --compatibility-date, or add a compatibility_date to your wrangler.toml.\n"
867
+ );
868
+ }
869
+
570
870
  if (!args.local) {
871
+ // -- snip, extract --
571
872
  const loggedIn = await loginOrRefreshIfRequired();
572
873
  if (!loggedIn) {
573
874
  // didn't login, let's just quit
574
875
  console.log("Did not login, quitting...");
575
876
  return;
576
877
  }
878
+
577
879
  if (!config.account_id) {
578
880
  config.account_id = await getAccountId();
579
881
  if (!config.account_id) {
580
- console.error("No account id found, quitting...");
581
- return;
882
+ throw new Error("No account id found, quitting...");
582
883
  }
583
884
  }
885
+ // -- snip, end --
584
886
  }
585
887
 
586
- // -- snip, end --
587
-
588
- const polyfillNode = args["polyfill-node"] ?? config.polyfill_node;
589
- if (polyfillNode) {
590
- console.warn(
591
- "Using polyfills for node builtin modules. These are not meant to be completely reliable, and have serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
592
- );
593
- }
594
-
888
+ const assetPaths = getAssetPaths(
889
+ config,
890
+ args["experimental-public"] || args.site,
891
+ args.siteInclude,
892
+ args.siteExclude
893
+ );
595
894
  await publish({
596
- config: args.config as Config,
895
+ config,
597
896
  name: args.name,
897
+ format: args.format || config.build?.upload?.format,
598
898
  script: args.script,
599
899
  env: args.env,
900
+ compatibilityDate: args.latest
901
+ ? new Date().toISOString().substring(0, 10)
902
+ : args["compatibility-date"],
903
+ compatibilityFlags: args["compatibility-flags"] as string[],
600
904
  triggers: args.triggers,
601
905
  jsxFactory: args["jsx-factory"],
602
906
  jsxFragment: args["jsx-fragment"],
603
- polyfillNode: args["polyfill-node"],
604
907
  routes: args.routes,
605
- public: args.public,
606
- site: args.site,
908
+ assetPaths,
909
+ legacyEnv: undefined, // TODO: get this from somewhere... config?
910
+ experimentalPublic: args["experimental-public"] !== undefined,
607
911
  });
608
912
  }
609
913
  );
610
914
 
611
915
  // tail
612
- yargs.command(
916
+ wrangler.command(
613
917
  "tail [name]",
614
918
  "🦚 Starts a log tailing session for a deployed Worker.",
615
919
  (yargs) => {
@@ -653,34 +957,35 @@ export async function main(argv: string[]): Promise<void> {
653
957
  // TODO: filter by client ip, which can be 'self' or an ip address
654
958
  },
655
959
  async (args) => {
960
+ if (args.local) {
961
+ throw new NotImplementedError(
962
+ `local mode is not yet supported for this command`
963
+ );
964
+ }
965
+
656
966
  const config = args.config as Config;
657
967
 
658
968
  if (!(args.name || config.name)) {
659
- console.error("Missing script name");
660
- return;
969
+ throw new Error("Missing script name");
661
970
  }
662
971
  const scriptName = `${args.name || config.name}${
663
972
  args.env ? `-${args.env}` : ""
664
973
  }`;
665
974
 
666
975
  // -- snip, extract --
976
+ const loggedIn = await loginOrRefreshIfRequired();
977
+ if (!loggedIn) {
978
+ // didn't login, let's just quit
979
+ console.log("Did not login, quitting...");
980
+ return;
981
+ }
667
982
 
668
- if (!args.local) {
669
- const loggedIn = await loginOrRefreshIfRequired();
670
- if (!loggedIn) {
671
- // didn't login, let's just quit
672
- console.log("Did not login, quitting...");
673
- return;
674
- }
983
+ if (!config.account_id) {
984
+ config.account_id = await getAccountId();
675
985
  if (!config.account_id) {
676
- config.account_id = await getAccountId();
677
- if (!config.account_id) {
678
- console.error("No account id found, quitting...");
679
- return;
680
- }
986
+ throw new Error("No account id found, quitting...");
681
987
  }
682
988
  }
683
-
684
989
  // -- snip, end --
685
990
 
686
991
  const accountId = config.account_id;
@@ -700,9 +1005,9 @@ export async function main(argv: string[]): Promise<void> {
700
1005
  `successfully created tail, expires at ${expiration.toLocaleString()}`
701
1006
  );
702
1007
 
703
- onExit(() => {
1008
+ onExit(async () => {
704
1009
  tail.terminate();
705
- deleteTail();
1010
+ await deleteTail();
706
1011
  });
707
1012
 
708
1013
  tail.on("message", (data) => {
@@ -727,7 +1032,7 @@ export async function main(argv: string[]): Promise<void> {
727
1032
  );
728
1033
 
729
1034
  // preview
730
- yargs.command(
1035
+ wrangler.command(
731
1036
  "preview [method] [body]",
732
1037
  false,
733
1038
  (yargs) => {
@@ -753,20 +1058,20 @@ export async function main(argv: string[]): Promise<void> {
753
1058
  });
754
1059
  },
755
1060
  () => {
756
- // "🔬 [DEPRECATED] Preview your code temporarily on cloudflareworkers.com"
757
- console.error(
1061
+ // "🔬 [DEPRECATED] Preview your code temporarily on https://cloudflareworkers.com"
1062
+ throw new DeprecationError(
758
1063
  "`wrangler preview` has been deprecated, please refer to TODO://some/path for alternatives"
759
1064
  );
760
1065
  }
761
1066
  );
762
1067
 
763
1068
  // route
764
- yargs.command(
1069
+ wrangler.command(
765
1070
  "route",
766
1071
  false, // I think we want to hide this command
767
1072
  // "➡️ List or delete worker routes",
768
- (yargs) => {
769
- return yargs
1073
+ (routeYargs) => {
1074
+ return routeYargs
770
1075
  .command(
771
1076
  "list",
772
1077
  "List a route associated with a zone",
@@ -790,11 +1095,10 @@ export async function main(argv: string[]): Promise<void> {
790
1095
  // TODO: use environment (current wrangler doesn't do so?)
791
1096
  const zone = args.zone || (args.config as Config).zone_id;
792
1097
  if (!zone) {
793
- console.error("missing zone id");
794
- return;
1098
+ throw new Error("missing zone id");
795
1099
  }
796
1100
 
797
- console.log(await cfetch(`/zones/${zone}/workers/routes`));
1101
+ console.log(await fetchResult(`/zones/${zone}/workers/routes`));
798
1102
  }
799
1103
  )
800
1104
  .command(
@@ -824,7 +1128,7 @@ export async function main(argv: string[]): Promise<void> {
824
1128
  }
825
1129
 
826
1130
  console.log(
827
- await cfetch(`/zones/${zone}/workers/routes/${args.id}`, {
1131
+ await fetchResult(`/zones/${zone}/workers/routes/${args.id}`, {
828
1132
  method: "DELETE",
829
1133
  })
830
1134
  );
@@ -834,7 +1138,7 @@ export async function main(argv: string[]): Promise<void> {
834
1138
  );
835
1139
 
836
1140
  // subdomain
837
- yargs.command(
1141
+ wrangler.command(
838
1142
  "subdomain [name]",
839
1143
  false,
840
1144
  // "👷 Create or change your workers.dev subdomain.",
@@ -842,18 +1146,18 @@ export async function main(argv: string[]): Promise<void> {
842
1146
  return yargs.positional("name", { type: "string" });
843
1147
  },
844
1148
  () => {
845
- console.error(
1149
+ throw new DeprecationError(
846
1150
  "`wrangler subdomain` has been deprecated, please refer to TODO://some/path for alternatives"
847
1151
  );
848
1152
  }
849
1153
  );
850
1154
 
851
1155
  // secret
852
- yargs.command(
1156
+ wrangler.command(
853
1157
  "secret",
854
1158
  "🤫 Generate a secret that can be referenced in the worker script",
855
- (yargs) => {
856
- return yargs
1159
+ (secretYargs) => {
1160
+ return secretYargs
857
1161
  .command(
858
1162
  "put <key>",
859
1163
  "Create or update a secret variable for a script",
@@ -874,45 +1178,49 @@ export async function main(argv: string[]): Promise<void> {
874
1178
  });
875
1179
  },
876
1180
  async (args) => {
877
- if (args.local) {
878
- console.error("--local not implemented for this command yet");
879
- return;
880
- }
881
1181
  const config = args.config as Config;
882
1182
 
883
1183
  // TODO: use environment (how does current wrangler do it?)
884
1184
  const scriptName = args.name || config.name;
885
1185
  if (!scriptName) {
886
- console.error("Missing script name");
887
- return;
1186
+ throw new Error("Missing script name");
888
1187
  }
889
1188
 
890
- // -- snip, extract --
1189
+ if (args.local) {
1190
+ console.warn("`wrangler secret put` is a no-op in --local mode");
1191
+ }
891
1192
 
892
1193
  if (!args.local) {
1194
+ // -- snip, extract --
893
1195
  const loggedIn = await loginOrRefreshIfRequired();
894
1196
  if (!loggedIn) {
895
1197
  // didn't login, let's just quit
896
1198
  console.log("Did not login, quitting...");
897
1199
  return;
898
1200
  }
1201
+
899
1202
  if (!config.account_id) {
900
1203
  config.account_id = await getAccountId();
901
1204
  if (!config.account_id) {
902
- console.error("No account id found, quitting...");
903
- return;
1205
+ throw new Error("No account id found, quitting...");
904
1206
  }
905
1207
  }
1208
+ // -- snip, end --
906
1209
  }
907
1210
 
908
- // -- snip, end --
909
-
910
1211
  const secretValue = await prompt(
911
1212
  "Enter a secret value:",
912
1213
  "password"
913
1214
  );
1215
+
1216
+ if (args.local) {
1217
+ return;
1218
+ }
1219
+
1220
+ console.log(`🌀 Creating the secret for script ${scriptName}`);
1221
+
914
1222
  async function submitSecret() {
915
- return await cfetch(
1223
+ return await fetchResult(
916
1224
  `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/`,
917
1225
  {
918
1226
  method: "PUT",
@@ -927,32 +1235,41 @@ export async function main(argv: string[]): Promise<void> {
927
1235
  }
928
1236
 
929
1237
  try {
930
- console.log(await submitSecret());
1238
+ await submitSecret();
931
1239
  } catch (e) {
932
1240
  if (e.code === 10007) {
933
1241
  // upload a draft worker
934
- await cfetch(
1242
+ await fetchResult(
935
1243
  `/accounts/${config.account_id}/workers/scripts/${scriptName}`,
936
1244
  {
937
1245
  method: "PUT",
938
- // @ts-expect-error TODO: fix this error!
939
1246
  body: toFormData({
1247
+ name: scriptName,
940
1248
  main: {
941
1249
  name: scriptName,
942
1250
  content: `export default { fetch() {} }`,
943
1251
  type: "esm",
944
1252
  },
945
- variables: {},
1253
+ bindings: {
1254
+ kv_namespaces: [],
1255
+ vars: {},
1256
+ durable_objects: { bindings: [] },
1257
+ },
946
1258
  modules: [],
1259
+ migrations: undefined,
1260
+ compatibility_date: undefined,
1261
+ compatibility_flags: undefined,
1262
+ usage_model: undefined,
947
1263
  }),
948
1264
  }
949
1265
  );
950
1266
 
951
1267
  // and then try again
952
- console.log(await submitSecret());
1268
+ await submitSecret();
953
1269
  // TODO: delete the draft worker if this failed too?
954
1270
  }
955
1271
  }
1272
+ console.log(`✨ Success! Uploaded secret ${args.key}`);
956
1273
  }
957
1274
  )
958
1275
  .command(
@@ -975,10 +1292,6 @@ export async function main(argv: string[]): Promise<void> {
975
1292
  });
976
1293
  },
977
1294
  async (args) => {
978
- if (args.local) {
979
- console.error("--local not implemented for this command yet");
980
- return;
981
- }
982
1295
  const config = args.config as Config;
983
1296
 
984
1297
  // TODO: use environment (how does current wrangler do it?)
@@ -987,37 +1300,48 @@ export async function main(argv: string[]): Promise<void> {
987
1300
  throw new Error("Missing script name");
988
1301
  }
989
1302
 
990
- // -- snip, extract --
1303
+ if (args.local) {
1304
+ console.warn(
1305
+ "`wrangler secret delete` is a no-op in --local mode"
1306
+ );
1307
+ }
991
1308
 
992
1309
  if (!args.local) {
1310
+ // -- snip, extract --
993
1311
  const loggedIn = await loginOrRefreshIfRequired();
994
1312
  if (!loggedIn) {
995
1313
  // didn't login, let's just quit
996
1314
  console.log("Did not login, quitting...");
997
1315
  return;
998
1316
  }
1317
+
999
1318
  if (!config.account_id) {
1000
1319
  config.account_id = await getAccountId();
1001
1320
  if (!config.account_id) {
1002
- console.error("No account id found, quitting...");
1003
- return;
1321
+ throw new Error("No account id found, quitting...");
1004
1322
  }
1005
1323
  }
1324
+ // -- snip, end --
1006
1325
  }
1007
1326
 
1008
- // -- snip, end --
1009
-
1010
- if (await confirm("Are you sure you want to delete this secret?")) {
1327
+ if (
1328
+ await confirm(
1329
+ `Are you sure you want to permanently delete the variable ${args.key} on the script ${scriptName}?`
1330
+ )
1331
+ ) {
1011
1332
  console.log(
1012
- `Deleting the secret ${args.key} on script ${scriptName}.`
1333
+ `🌀 Deleting the secret ${args.key} on script ${scriptName}.`
1013
1334
  );
1014
1335
 
1015
- console.log(
1016
- await cfetch(
1017
- `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/${args.key}`,
1018
- { method: "DELETE" }
1019
- )
1336
+ if (args.local) {
1337
+ return;
1338
+ }
1339
+
1340
+ await fetchResult(
1341
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/${args.key}`,
1342
+ { method: "DELETE" }
1020
1343
  );
1344
+ console.log(`✨ Success! Deleted secret ${args.key}`);
1021
1345
  }
1022
1346
  }
1023
1347
  )
@@ -1037,42 +1361,47 @@ export async function main(argv: string[]): Promise<void> {
1037
1361
  });
1038
1362
  },
1039
1363
  async (args) => {
1040
- if (args.local) {
1041
- console.error("--local not implemented for this command yet");
1042
- return;
1043
- }
1044
1364
  const config = args.config as Config;
1045
1365
 
1046
1366
  // TODO: use environment (how does current wrangler do it?)
1047
1367
  const scriptName = args.name || config.name;
1048
1368
  if (!scriptName) {
1049
- console.error("Missing script name");
1050
- return;
1369
+ throw new Error("Missing script name");
1051
1370
  }
1052
1371
 
1053
- // -- snip, extract --
1372
+ if (args.local) {
1373
+ console.warn("`wrangler secret list` is a no-op in --local mode");
1374
+ }
1054
1375
 
1055
1376
  if (!args.local) {
1377
+ // -- snip, extract --
1056
1378
  const loggedIn = await loginOrRefreshIfRequired();
1057
1379
  if (!loggedIn) {
1058
1380
  // didn't login, let's just quit
1059
1381
  console.log("Did not login, quitting...");
1060
1382
  return;
1061
1383
  }
1384
+
1062
1385
  if (!config.account_id) {
1063
1386
  config.account_id = await getAccountId();
1064
1387
  if (!config.account_id) {
1065
- console.error("No account id found, quitting...");
1066
- return;
1388
+ throw new Error("No account id found, quitting...");
1067
1389
  }
1068
1390
  }
1391
+ // -- snip, end --
1069
1392
  }
1070
1393
 
1071
- // -- snip, end --
1394
+ if (args.local) {
1395
+ return;
1396
+ }
1072
1397
 
1073
1398
  console.log(
1074
- await cfetch(
1075
- `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets`
1399
+ JSON.stringify(
1400
+ await fetchResult(
1401
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets`
1402
+ ),
1403
+ null,
1404
+ " "
1076
1405
  )
1077
1406
  );
1078
1407
  }
@@ -1082,11 +1411,11 @@ export async function main(argv: string[]): Promise<void> {
1082
1411
 
1083
1412
  // kv
1084
1413
  // :namespace
1085
- yargs.command(
1414
+ wrangler.command(
1086
1415
  "kv:namespace",
1087
1416
  "🗂️ Interact with your Workers KV Namespaces",
1088
- (yargs) => {
1089
- return yargs
1417
+ (namespaceYargs) => {
1418
+ return namespaceYargs
1090
1419
  .command(
1091
1420
  "create <namespace>",
1092
1421
  "Create a new namespace",
@@ -1095,6 +1424,7 @@ export async function main(argv: string[]): Promise<void> {
1095
1424
  .positional("namespace", {
1096
1425
  describe: "The name of the new namespace",
1097
1426
  type: "string",
1427
+ demandOption: true,
1098
1428
  })
1099
1429
  .option("env", {
1100
1430
  type: "string",
@@ -1106,13 +1436,19 @@ export async function main(argv: string[]): Promise<void> {
1106
1436
  });
1107
1437
  },
1108
1438
  async (args) => {
1109
- if (args._.length !== 2) {
1110
- throw new Error(
1111
- `Did you forget to add quotes around "${
1112
- args.namespace
1113
- } ${args._.slice(2).join(" ")}"?`
1439
+ if (args._.length > 2) {
1440
+ const extraArgs = args._.slice(2).join(" ");
1441
+ throw new CommandLineArgsError(
1442
+ `Unexpected additional positional arguments "${extraArgs}".`
1114
1443
  );
1115
1444
  }
1445
+
1446
+ if (!isValidNamespaceBinding(args.namespace)) {
1447
+ throw new CommandLineArgsError(
1448
+ `The namespace binding name "${args.namespace}" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.`
1449
+ );
1450
+ }
1451
+
1116
1452
  const config = args.config as Config;
1117
1453
  if (!config.name) {
1118
1454
  console.warn(
@@ -1120,13 +1456,10 @@ export async function main(argv: string[]): Promise<void> {
1120
1456
  );
1121
1457
  }
1122
1458
 
1123
- const title = `${config.name || "worker"}${
1124
- args.env ? `-${args.env}` : ""
1125
- }-${args.namespace}${args.preview ? "_preview" : ""}`;
1126
-
1127
- if (/[\W]+/.test(args.namespace)) {
1128
- throw new Error("invalid binding name, needs to be js friendly");
1129
- }
1459
+ const name = config.name || "worker";
1460
+ const environment = args.env ? `-${args.env}` : "";
1461
+ const preview = args.preview ? "_preview" : "";
1462
+ const title = `${name}${environment}-${args.namespace}${preview}`;
1130
1463
 
1131
1464
  if (args.local) {
1132
1465
  const { Miniflare } = await import("miniflare");
@@ -1135,59 +1468,45 @@ export async function main(argv: string[]): Promise<void> {
1135
1468
  // TODO: these options shouldn't be required
1136
1469
  script: ` `, // has to be a string with at least one char
1137
1470
  });
1138
- mf.getKVNamespace(title); // this should "create" the namespace
1471
+ await mf.getKVNamespace(title); // this should "create" the namespace
1139
1472
  console.log(`✨ Success! Created KV namespace ${title}`);
1140
- return;
1141
- }
1142
-
1143
- // -- snip, extract --
1144
-
1145
- if (!args.local) {
1473
+ } else {
1474
+ // -- snip, extract --
1146
1475
  const loggedIn = await loginOrRefreshIfRequired();
1147
1476
  if (!loggedIn) {
1148
1477
  // didn't login, let's just quit
1149
1478
  console.log("Did not login, quitting...");
1150
1479
  return;
1151
1480
  }
1481
+
1152
1482
  if (!config.account_id) {
1153
1483
  config.account_id = await getAccountId();
1154
1484
  if (!config.account_id) {
1155
- console.error("No account id found, quitting...");
1156
- return;
1485
+ throw new Error("No account id found, quitting...");
1157
1486
  }
1158
1487
  }
1159
- }
1160
-
1161
- // -- snip, end --
1488
+ // -- snip, end --
1162
1489
 
1163
- // TODO: generate a binding name stripping non alphanumeric chars
1490
+ // TODO: generate a binding name stripping non alphanumeric chars
1164
1491
 
1165
- console.log(`🌀 Creating namespace with title "${title}"`);
1492
+ console.log(`🌀 Creating namespace with title "${title}"`);
1493
+ const namespaceId = await createNamespace(
1494
+ config.account_id,
1495
+ title
1496
+ );
1166
1497
 
1167
- const response = await cfetch<{ id: string }>(
1168
- `/accounts/${config.account_id}/storage/kv/namespaces`,
1169
- {
1170
- method: "POST",
1171
- headers: {
1172
- "Content-Type": "application/json",
1173
- },
1174
- body: JSON.stringify({
1175
- title,
1176
- }),
1177
- }
1178
- );
1498
+ console.log("✨ Success!");
1499
+ const envString = args.env ? ` under [env.${args.env}]` : "";
1500
+ const previewString = args.preview ? "preview_" : "";
1501
+ console.log(
1502
+ `Add the following to your configuration file in your kv_namespaces array${envString}:`
1503
+ );
1504
+ console.log(
1505
+ `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
1506
+ );
1179
1507
 
1180
- console.log("✨ Success!");
1181
- console.log(
1182
- `Add the following to your configuration file in your kv_namespaces array${
1183
- args.env ? ` under [env.${args.env}]` : ""
1184
- }:`
1185
- );
1186
- console.log(
1187
- `{ binding = "${args.namespace}", ${
1188
- args.preview ? "preview_" : ""
1189
- }id = "${response.id}" }`
1190
- );
1508
+ // TODO: automatically write this block to the wrangler.toml config file??
1509
+ }
1191
1510
  }
1192
1511
  )
1193
1512
  .command(
@@ -1195,42 +1514,39 @@ export async function main(argv: string[]): Promise<void> {
1195
1514
  "Outputs a list of all KV namespaces associated with your account id.",
1196
1515
  {},
1197
1516
  async (args) => {
1198
- if (args.local) {
1199
- console.error(`local mode is not yet supported for this command`);
1200
- return;
1201
- }
1202
-
1203
1517
  const config = args.config as Config;
1204
1518
 
1205
- // -- snip, extract --
1206
-
1207
- if (!args.local) {
1519
+ if (args.local) {
1520
+ throw new NotImplementedError(
1521
+ `local mode is not yet supported for this command`
1522
+ );
1523
+ } else {
1524
+ // -- snip, extract --
1208
1525
  const loggedIn = await loginOrRefreshIfRequired();
1209
1526
  if (!loggedIn) {
1210
1527
  // didn't login, let's just quit
1211
1528
  console.log("Did not login, quitting...");
1212
1529
  return;
1213
1530
  }
1531
+
1214
1532
  if (!config.account_id) {
1215
1533
  config.account_id = await getAccountId();
1216
1534
  if (!config.account_id) {
1217
- console.error("No account id found, quitting...");
1218
- return;
1535
+ throw new Error("No account id found, quitting...");
1219
1536
  }
1220
1537
  }
1221
- }
1222
-
1223
- // -- snip, end --
1538
+ // -- snip, end --
1224
1539
 
1225
- // TODO: we should show bindings if they exist for given ids
1540
+ // TODO: we should show bindings if they exist for given ids
1226
1541
 
1227
- console.log(
1228
- JSON.stringify(
1229
- await listNamespaces(config.account_id),
1230
- null,
1231
- " "
1232
- )
1233
- );
1542
+ console.log(
1543
+ JSON.stringify(
1544
+ await listNamespaces(config.account_id),
1545
+ null,
1546
+ " "
1547
+ )
1548
+ );
1549
+ }
1234
1550
  }
1235
1551
  )
1236
1552
  .command(
@@ -1257,27 +1573,23 @@ export async function main(argv: string[]): Promise<void> {
1257
1573
  });
1258
1574
  },
1259
1575
  async (args) => {
1260
- if (args.local) {
1261
- console.error(`local mode is not yet supported for this command`);
1262
- return;
1263
- }
1264
1576
  const config = args.config as Config;
1265
1577
 
1266
- const id =
1267
- args["namespace-id"] ||
1268
- (args.env
1269
- ? config.env[args.env] || {}
1270
- : config
1271
- ).kv_namespaces.find(
1272
- (namespace) => namespace.binding === args.binding
1273
- )[args.preview ? "preview_id" : "id"];
1274
- if (!id) {
1275
- throw new Error("Are you sure? id not found");
1276
- }
1277
-
1278
- // -- snip, extract --
1578
+ if (args.local) {
1579
+ throw new NotImplementedError(
1580
+ `local mode is not yet supported for this command`
1581
+ );
1582
+ } else {
1583
+ let id;
1584
+ try {
1585
+ id = getNamespaceId(args);
1586
+ } catch (e) {
1587
+ throw new CommandLineArgsError(
1588
+ "Not able to delete namespace.\n" + e.message
1589
+ );
1590
+ }
1279
1591
 
1280
- if (!args.local) {
1592
+ // -- snip, extract --
1281
1593
  const loggedIn = await loginOrRefreshIfRequired();
1282
1594
  if (!loggedIn) {
1283
1595
  // didn't login, let's just quit
@@ -1288,55 +1600,54 @@ export async function main(argv: string[]): Promise<void> {
1288
1600
  if (!config.account_id) {
1289
1601
  config.account_id = await getAccountId();
1290
1602
  if (!config.account_id) {
1291
- console.error("No account id found, quitting...");
1292
- return;
1603
+ throw new Error("No account id found, quitting...");
1293
1604
  }
1294
1605
  }
1295
- }
1296
-
1297
- // -- snip, end --
1606
+ // -- snip, end --
1298
1607
 
1299
- await cfetch<{ id: string }>(
1300
- `/accounts/${config.account_id}/storage/kv/namespaces/${id}`,
1301
- { method: "DELETE" }
1302
- );
1608
+ await fetchResult<{ id: string }>(
1609
+ `/accounts/${config.account_id}/storage/kv/namespaces/${id}`,
1610
+ { method: "DELETE" }
1611
+ );
1303
1612
 
1304
- // TODO: recommend they remove it from wrangler.toml
1613
+ // TODO: recommend they remove it from wrangler.toml
1305
1614
 
1306
- // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1307
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1308
- // n
1309
- // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1310
- // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1311
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1312
- // y
1313
- // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1314
- // ✨ Success
1315
- // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
1316
- // ➜ test-mf
1615
+ // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1616
+ // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1617
+ // n
1618
+ // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1619
+ // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1620
+ // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1621
+ // y
1622
+ // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1623
+ // ✨ Success
1624
+ // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
1625
+ // ➜ test-mf
1317
1626
 
1318
- // TODO: do it automatically
1627
+ // TODO: do it automatically
1319
1628
 
1320
- // TODO: delete the preview namespace as well?
1629
+ // TODO: delete the preview namespace as well?
1630
+ }
1321
1631
  }
1322
1632
  );
1323
1633
  }
1324
1634
  );
1325
1635
 
1326
1636
  // :key
1327
- yargs.command(
1637
+ wrangler.command(
1328
1638
  "kv:key",
1329
1639
  "🔑 Individually manage Workers KV key-value pairs",
1330
- (yargs) => {
1331
- return yargs
1640
+ (kvKeyYargs) => {
1641
+ return kvKeyYargs
1332
1642
  .command(
1333
- "put <key> <value>",
1643
+ "put <key> [value]",
1334
1644
  "Writes a single key/value pair to the given namespace.",
1335
1645
  (yargs) => {
1336
1646
  return yargs
1337
1647
  .positional("key", {
1338
1648
  type: "string",
1339
1649
  describe: "The key to write to.",
1650
+ demandOption: true,
1340
1651
  })
1341
1652
  .positional("value", {
1342
1653
  type: "string",
@@ -1371,16 +1682,28 @@ export async function main(argv: string[]): Promise<void> {
1371
1682
  .option("path", {
1372
1683
  type: "string",
1373
1684
  describe: "Read value from the file at a given path.",
1374
- });
1685
+ })
1686
+ .check(demandOneOfOption("value", "path"));
1375
1687
  },
1376
1688
  async ({ key, ttl, expiration, ...args }) => {
1377
1689
  const namespaceId = getNamespaceId(args);
1690
+ // One of `args.path` and `args.value` must be defined
1378
1691
  const value = args.path
1379
1692
  ? await readFile(args.path, "utf-8")
1380
- : args.value;
1693
+ : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
1694
+ args.value!;
1381
1695
  const config = args.config as Config;
1382
1696
 
1383
- console.log(`writing ${key}=${value} to namespace ${namespaceId}`);
1697
+ if (args.path) {
1698
+ console.log(
1699
+ `writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}`
1700
+ );
1701
+ } else {
1702
+ console.log(
1703
+ `writing the value "${value}" to key "${key}" on namespace ${namespaceId}`
1704
+ );
1705
+ }
1706
+
1384
1707
  if (args.local) {
1385
1708
  const { Miniflare } = await import("miniflare");
1386
1709
  const mf = new Miniflare({
@@ -1390,11 +1713,8 @@ export async function main(argv: string[]): Promise<void> {
1390
1713
  });
1391
1714
  const ns = await mf.getKVNamespace(namespaceId);
1392
1715
  await ns.put(key, value, { expiration, expirationTtl: ttl });
1393
- return;
1394
- }
1395
- // -- snip, extract --
1396
-
1397
- if (!args.local) {
1716
+ } else {
1717
+ // -- snip, extract --
1398
1718
  const loggedIn = await loginOrRefreshIfRequired();
1399
1719
  if (!loggedIn) {
1400
1720
  // didn't login, let's just quit
@@ -1405,18 +1725,16 @@ export async function main(argv: string[]): Promise<void> {
1405
1725
  if (!config.account_id) {
1406
1726
  config.account_id = await getAccountId();
1407
1727
  if (!config.account_id) {
1408
- console.error("No account id found, quitting...");
1409
- return;
1728
+ throw new Error("No account id found, quitting...");
1410
1729
  }
1411
1730
  }
1412
- }
1731
+ // -- snip, end --
1413
1732
 
1414
- // -- snip, end --
1415
-
1416
- await putKeyValue(config.account_id, namespaceId, key, value, {
1417
- expiration,
1418
- expiration_ttl: ttl,
1419
- });
1733
+ await putKeyValue(config.account_id, namespaceId, key, value, {
1734
+ expiration,
1735
+ expiration_ttl: ttl,
1736
+ });
1737
+ }
1420
1738
  }
1421
1739
  )
1422
1740
  .command(
@@ -1437,6 +1755,12 @@ export async function main(argv: string[]): Promise<void> {
1437
1755
  type: "string",
1438
1756
  describe: "Perform on a specific environment",
1439
1757
  })
1758
+ .option("preview", {
1759
+ type: "boolean",
1760
+ // In the case of listing keys we will default to non-preview mode
1761
+ default: false,
1762
+ describe: "Interact with a preview namespace",
1763
+ })
1440
1764
  .option("prefix", {
1441
1765
  type: "string",
1442
1766
  describe: "A prefix to filter listed keys",
@@ -1458,12 +1782,8 @@ export async function main(argv: string[]): Promise<void> {
1458
1782
  const ns = await mf.getKVNamespace(namespaceId);
1459
1783
  const listResponse = await ns.list({ prefix });
1460
1784
  console.log(JSON.stringify(listResponse.keys, null, " ")); // TODO: paginate, collate
1461
- return;
1462
- }
1463
-
1464
- // -- snip, extract --
1465
-
1466
- if (!args.local) {
1785
+ } else {
1786
+ // -- snip, extract --
1467
1787
  const loggedIn = await loginOrRefreshIfRequired();
1468
1788
  if (!loggedIn) {
1469
1789
  // didn't login, let's just quit
@@ -1474,17 +1794,18 @@ export async function main(argv: string[]): Promise<void> {
1474
1794
  if (!config.account_id) {
1475
1795
  config.account_id = await getAccountId();
1476
1796
  if (!config.account_id) {
1477
- console.error("No account id found, quitting...");
1478
- return;
1797
+ throw new Error("No account id found, quitting...");
1479
1798
  }
1480
1799
  }
1481
- }
1800
+ // -- snip, end --
1482
1801
 
1483
- // -- snip, end --
1484
-
1485
- console.log(
1486
- await listNamespaceKeys(config.account_id, namespaceId, prefix)
1487
- );
1802
+ const results = await listNamespaceKeys(
1803
+ config.account_id,
1804
+ namespaceId,
1805
+ prefix
1806
+ );
1807
+ console.log(JSON.stringify(results, undefined, 2));
1808
+ }
1488
1809
  }
1489
1810
  )
1490
1811
  .command(
@@ -1495,6 +1816,7 @@ export async function main(argv: string[]): Promise<void> {
1495
1816
  .positional("key", {
1496
1817
  describe: "The key value to get.",
1497
1818
  type: "string",
1819
+ demandOption: true,
1498
1820
  })
1499
1821
  .option("binding", {
1500
1822
  type: "string",
@@ -1512,6 +1834,12 @@ export async function main(argv: string[]): Promise<void> {
1512
1834
  .option("preview", {
1513
1835
  type: "boolean",
1514
1836
  describe: "Interact with a preview namespace",
1837
+ })
1838
+ .option("preview", {
1839
+ type: "boolean",
1840
+ // In the case of getting key values we will default to non-preview mode
1841
+ default: false,
1842
+ describe: "Interact with a preview namespace",
1515
1843
  });
1516
1844
  },
1517
1845
  async ({ key, ...args }) => {
@@ -1530,9 +1858,8 @@ export async function main(argv: string[]): Promise<void> {
1530
1858
  return;
1531
1859
  }
1532
1860
 
1533
- // -- snip, extract --
1534
-
1535
1861
  if (!args.local) {
1862
+ // -- snip, extract --
1536
1863
  const loggedIn = await loginOrRefreshIfRequired();
1537
1864
  if (!loggedIn) {
1538
1865
  // didn't login, let's just quit
@@ -1543,23 +1870,15 @@ export async function main(argv: string[]): Promise<void> {
1543
1870
  if (!config.account_id) {
1544
1871
  config.account_id = await getAccountId();
1545
1872
  if (!config.account_id) {
1546
- console.error("No account id found, quitting...");
1547
- return;
1873
+ throw new Error("No account id found, quitting...");
1548
1874
  }
1549
1875
  }
1550
- }
1551
-
1552
- // -- snip, end --
1876
+ // -- snip, end --
1553
1877
 
1554
- // annoyingly, the API for this one doesn't return the
1555
- // data in the 'standard' format. goddamit.
1556
- // That's why we have the fallthrough response in cfetch.
1557
- // Oh well.
1558
- console.log(
1559
- await cfetch(
1560
- `/accounts/${config.account_id}/storage/kv/namespaces/${namespaceId}/values/${key}`
1561
- )
1562
- );
1878
+ console.log(
1879
+ await getKeyValue(config.account_id, namespaceId, key)
1880
+ );
1881
+ }
1563
1882
  }
1564
1883
  )
1565
1884
  .command(
@@ -1570,6 +1889,7 @@ export async function main(argv: string[]): Promise<void> {
1570
1889
  .positional("key", {
1571
1890
  describe: "The key value to delete",
1572
1891
  type: "string",
1892
+ demandOption: true,
1573
1893
  })
1574
1894
  .option("binding", {
1575
1895
  type: "string",
@@ -1592,6 +1912,10 @@ export async function main(argv: string[]): Promise<void> {
1592
1912
  async ({ key, ...args }) => {
1593
1913
  const namespaceId = getNamespaceId(args);
1594
1914
 
1915
+ console.log(
1916
+ `deleting the key "${key}" on namespace ${namespaceId}`
1917
+ );
1918
+
1595
1919
  if (args.local) {
1596
1920
  const { Miniflare } = await import("miniflare");
1597
1921
  const mf = new Miniflare({
@@ -1606,9 +1930,8 @@ export async function main(argv: string[]): Promise<void> {
1606
1930
 
1607
1931
  const config = args.config as Config;
1608
1932
 
1609
- // -- snip, extract --
1610
-
1611
1933
  if (!args.local) {
1934
+ // -- snip, extract --
1612
1935
  const loggedIn = await loginOrRefreshIfRequired();
1613
1936
  if (!loggedIn) {
1614
1937
  // didn't login, let's just quit
@@ -1619,15 +1942,13 @@ export async function main(argv: string[]): Promise<void> {
1619
1942
  if (!config.account_id) {
1620
1943
  config.account_id = await getAccountId();
1621
1944
  if (!config.account_id) {
1622
- console.error("No account id found, quitting...");
1623
- return;
1945
+ throw new Error("No account id found, quitting...");
1624
1946
  }
1625
1947
  }
1948
+ // -- snip, end --
1626
1949
  }
1627
1950
 
1628
- // -- snip, end --
1629
-
1630
- await cfetch(
1951
+ await fetchResult(
1631
1952
  `/accounts/${config.account_id}/storage/kv/namespaces/${namespaceId}/values/${key}`,
1632
1953
  { method: "DELETE" }
1633
1954
  );
@@ -1637,11 +1958,11 @@ export async function main(argv: string[]): Promise<void> {
1637
1958
  );
1638
1959
 
1639
1960
  // :bulk
1640
- yargs.command(
1961
+ wrangler.command(
1641
1962
  "kv:bulk",
1642
1963
  "💪 Interact with multiple Workers KV key-value pairs at once",
1643
- (yargs) => {
1644
- return yargs
1964
+ (kvBulkYargs) => {
1965
+ return kvBulkYargs
1645
1966
  .command(
1646
1967
  "put <filename>",
1647
1968
  "Upload multiple key-value pairs to a namespace",
@@ -1650,6 +1971,7 @@ export async function main(argv: string[]): Promise<void> {
1650
1971
  .positional("filename", {
1651
1972
  describe: `The JSON file of key-value pairs to upload, in form [{"key":..., "value":...}"...]`,
1652
1973
  type: "string",
1974
+ demandOption: true,
1653
1975
  })
1654
1976
  .option("binding", {
1655
1977
  type: "string",
@@ -1681,8 +2003,9 @@ export async function main(argv: string[]): Promise<void> {
1681
2003
  try {
1682
2004
  parsedContent = JSON.parse(content);
1683
2005
  } catch (err) {
1684
- console.error(`could not parse json from ${filename}`);
1685
- throw err;
2006
+ throw new Error(
2007
+ `Could not parse json from ${filename}.\n${err.message ?? err}`
2008
+ );
1686
2009
  }
1687
2010
 
1688
2011
  if (args.local) {
@@ -1704,13 +2027,8 @@ export async function main(argv: string[]): Promise<void> {
1704
2027
  expirationTtl: expiration_ttl,
1705
2028
  });
1706
2029
  }
1707
-
1708
- return;
1709
- }
1710
-
1711
- // -- snip, extract --
1712
-
1713
- if (!args.local) {
2030
+ } else {
2031
+ // -- snip, extract --
1714
2032
  const loggedIn = await loginOrRefreshIfRequired();
1715
2033
  if (!loggedIn) {
1716
2034
  // didn't login, let's just quit
@@ -1721,27 +2039,26 @@ export async function main(argv: string[]): Promise<void> {
1721
2039
  if (!config.account_id) {
1722
2040
  config.account_id = await getAccountId();
1723
2041
  if (!config.account_id) {
1724
- console.error("No account id found, quitting...");
1725
- return;
2042
+ throw new Error("No account id found, quitting...");
1726
2043
  }
1727
2044
  }
1728
- }
1729
-
1730
- // -- snip, end --
2045
+ // -- snip, end --
1731
2046
 
1732
- console.log(
1733
- await putBulkKeyValue(config.account_id, namespaceId, content)
1734
- );
2047
+ console.log(
2048
+ await putBulkKeyValue(config.account_id, namespaceId, content)
2049
+ );
2050
+ }
1735
2051
  }
1736
2052
  )
1737
2053
  .command(
1738
2054
  "delete <filename>",
1739
- "Upload multiple key-value pairs to a namespace",
2055
+ "Delete multiple key-value pairs from a namespace",
1740
2056
  (yargs) => {
1741
2057
  return yargs
1742
2058
  .positional("filename", {
1743
- describe: `The JSON file of key-value pairs to upload, in form ["key1", "key2", ...]`,
2059
+ describe: `The JSON file of keys to delete, in the form ["key1", "key2", ...]`,
1744
2060
  type: "string",
2061
+ demandOption: true,
1745
2062
  })
1746
2063
  .option("binding", {
1747
2064
  type: "string",
@@ -1769,8 +2086,9 @@ export async function main(argv: string[]): Promise<void> {
1769
2086
  try {
1770
2087
  parsedContent = JSON.parse(content);
1771
2088
  } catch (err) {
1772
- console.error(`could not parse json from ${filename}`);
1773
- throw err;
2089
+ throw new Error(
2090
+ `Could not parse json from ${filename}.\n${err.message ?? err}`
2091
+ );
1774
2092
  }
1775
2093
 
1776
2094
  if (args.local) {
@@ -1784,13 +2102,8 @@ export async function main(argv: string[]): Promise<void> {
1784
2102
  for (const key of parsedContent) {
1785
2103
  await ns.delete(key);
1786
2104
  }
1787
-
1788
- return;
1789
- }
1790
-
1791
- // -- snip, extract --
1792
-
1793
- if (!args.local) {
2105
+ } else {
2106
+ // -- snip, extract --
1794
2107
  const loggedIn = await loginOrRefreshIfRequired();
1795
2108
  if (!loggedIn) {
1796
2109
  // didn't login, let's just quit
@@ -1801,26 +2114,29 @@ export async function main(argv: string[]): Promise<void> {
1801
2114
  if (!config.account_id) {
1802
2115
  config.account_id = await getAccountId();
1803
2116
  if (!config.account_id) {
1804
- console.error("No account id found, quitting...");
1805
- return;
2117
+ throw new Error("No account id found, quitting...");
1806
2118
  }
1807
2119
  }
1808
- }
1809
-
1810
- // -- snip, end --
2120
+ // -- snip, end --
1811
2121
 
1812
- console.log(
1813
- await deleteBulkKeyValue(config.account_id, namespaceId, content)
1814
- );
2122
+ console.log(
2123
+ await deleteBulkKeyValue(
2124
+ config.account_id,
2125
+ namespaceId,
2126
+ content
2127
+ )
2128
+ );
2129
+ }
1815
2130
  }
1816
2131
  );
1817
2132
  }
1818
2133
  );
1819
2134
 
1820
- yargs.command("pages", "⚡️ Configure Cloudflare Pages", pages);
2135
+ wrangler.command("pages", "⚡️ Configure Cloudflare Pages", pages);
1821
2136
 
1822
- yargs
2137
+ wrangler
1823
2138
  .option("config", {
2139
+ alias: "c",
1824
2140
  describe: "Path to .toml configuration file",
1825
2141
  type: "string",
1826
2142
  async coerce(arg) {
@@ -1828,18 +2144,34 @@ export async function main(argv: string[]): Promise<void> {
1828
2144
  },
1829
2145
  })
1830
2146
  .option("local", {
2147
+ alias: "l",
1831
2148
  describe: "Run on my machine",
1832
2149
  type: "boolean",
1833
2150
  default: false, // I bet this will a point of contention. We'll revisit it.
1834
2151
  });
1835
2152
 
1836
- yargs.group(["config", "help", "version"], "Flags:");
1837
- yargs.version(wranglerVersion);
2153
+ wrangler.group(["config", "help", "version"], "Flags:");
2154
+ wrangler.help().alias("h", "help");
2155
+ wrangler.version(wranglerVersion).alias("v", "version");
2156
+ wrangler.exitProcess(false);
2157
+
1838
2158
  await initialiseUserConfig();
1839
2159
 
1840
- await yargs.parse(argv, (err, argv, output) => {
1841
- if (output) {
1842
- console.log(output);
2160
+ try {
2161
+ await wrangler.parse();
2162
+ } catch (e) {
2163
+ if (e instanceof CommandLineArgsError) {
2164
+ wrangler.showHelp("error");
2165
+ console.error(""); // Just adds a bit of space
2166
+ console.error(e.message);
2167
+ } else {
2168
+ console.error(e.message);
2169
+ console.error(""); // Just adds a bit of space
2170
+ console.error(
2171
+ `${fgGreenColor}%s${resetColor}`,
2172
+ "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
2173
+ );
1843
2174
  }
1844
- });
2175
+ throw e;
2176
+ }
1845
2177
  }