wrangler 0.0.0-efa548c → 0.0.0-fb43821

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 (40) hide show
  1. package/README.md +51 -0
  2. package/bin/wrangler.js +36 -2
  3. package/import_meta_url.js +3 -0
  4. package/package.json +56 -22
  5. package/src/__tests__/clipboardy-mock.js +4 -0
  6. package/src/__tests__/index.test.ts +422 -0
  7. package/src/__tests__/mock-cfetch.js +42 -0
  8. package/src/api/form_data.ts +141 -0
  9. package/src/api/inspect.ts +430 -0
  10. package/src/api/preview.ts +128 -0
  11. package/src/api/worker.ts +161 -0
  12. package/src/cfetch.ts +72 -0
  13. package/src/cli.ts +10 -0
  14. package/src/config.ts +122 -0
  15. package/src/dev.tsx +776 -0
  16. package/src/dialogs.tsx +77 -0
  17. package/src/index.tsx +1874 -0
  18. package/src/kv.tsx +211 -0
  19. package/src/module-collection.ts +64 -0
  20. package/src/pages.tsx +818 -0
  21. package/src/publish.ts +346 -0
  22. package/src/sites.tsx +115 -0
  23. package/src/tail.tsx +71 -0
  24. package/src/user.tsx +1029 -0
  25. package/{facade.js → static-asset-facade.js} +2 -7
  26. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +262 -192
  27. package/vendor/@cloudflare/kv-asset-handler/package.json +1 -1
  28. package/vendor/{mime → wrangler-mime}/CHANGELOG.md +0 -0
  29. package/vendor/{mime → wrangler-mime}/LICENSE +0 -0
  30. package/vendor/{mime → wrangler-mime}/Mime.js +0 -0
  31. package/vendor/{mime → wrangler-mime}/README.md +0 -0
  32. package/vendor/{mime → wrangler-mime}/cli.js +0 -0
  33. package/vendor/{mime → wrangler-mime}/index.js +0 -0
  34. package/vendor/{mime → wrangler-mime}/lite.js +0 -0
  35. package/vendor/{mime → wrangler-mime}/package.json +1 -1
  36. package/vendor/{mime → wrangler-mime}/types/other.js +0 -0
  37. package/vendor/{mime → wrangler-mime}/types/standard.js +0 -0
  38. package/wrangler-dist/{index_node.js → cli.js} +90785 -61395
  39. package/wrangler-dist/cli.js.map +7 -0
  40. package/wrangler-dist/index_node.js.map +0 -7
package/src/index.tsx ADDED
@@ -0,0 +1,1874 @@
1
+ import React from "react";
2
+ import { render } from "ink";
3
+ import Dev from "./dev";
4
+ import { readFile } from "node:fs/promises";
5
+ 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
+ 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";
21
+ import {
22
+ getNamespaceId,
23
+ listNamespaces,
24
+ listNamespaceKeys,
25
+ putKeyValue,
26
+ putBulkKeyValue,
27
+ deleteBulkKeyValue,
28
+ } from "./kv";
29
+
30
+ import { pages } from "./pages";
31
+
32
+ import cfetch from "./cfetch";
33
+
34
+ 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
+
39
+ 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";
44
+
45
+ async function readConfig(path?: string): Promise<Config> {
46
+ const config: Config = {};
47
+ if (!path) {
48
+ path = await findUp("wrangler.toml");
49
+ // TODO - terminate this early instead of going all the way to the root
50
+ }
51
+
52
+ if (path) {
53
+ const tml: string = await readFile(path, "utf-8");
54
+ const parsed = TOML.parse(tml) as Config;
55
+ Object.assign(config, parsed);
56
+ }
57
+
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
+ "site",
70
+ "triggers",
71
+ "usage_model",
72
+ ];
73
+
74
+ Object.keys(config.env || {}).forEach((env) => {
75
+ inheritedFields.forEach((field) => {
76
+ if (config[field] !== undefined && config.env[env][field] === undefined) {
77
+ config.env[env][field] = config[field]; // TODO: - shallow copy?
78
+ }
79
+ });
80
+ });
81
+
82
+ const mirroredFields = ["vars", "kv_namespaces", "durable_objects"];
83
+ Object.keys(config.env || {}).forEach((env) => {
84
+ mirroredFields.forEach((field) => {
85
+ // if it exists on top level, it should exist on env defns
86
+ Object.keys(config[field] || {}).forEach((fieldKey) => {
87
+ if (!(fieldKey in config.env[env][field])) {
88
+ console.error(
89
+ `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}".`
90
+ );
91
+ }
92
+ });
93
+ });
94
+ });
95
+
96
+ // todo: validate, add defaults
97
+ // let's just do some basics for now
98
+
99
+ // @ts-expect-error we're being sneaky here for now
100
+ config.__path__ = path;
101
+
102
+ return config;
103
+ }
104
+
105
+ // a helper to demand one of a set of options
106
+ // via https://github.com/yargs/yargs/issues/1093#issuecomment-491299261
107
+ function demandOneOfOption(...options: string[]) {
108
+ return function (argv: yargs.Arguments) {
109
+ const count = options.filter((option) => argv[option]).length;
110
+ const lastOption = options.pop();
111
+
112
+ if (count === 0) {
113
+ throw new Error(
114
+ `Exactly one of the arguments ${options.join(
115
+ ", "
116
+ )} and ${lastOption} is required`
117
+ );
118
+ } else if (count > 1) {
119
+ throw new Error(
120
+ `Arguments ${options.join(
121
+ ", "
122
+ )} and ${lastOption} are mutually exclusive`
123
+ );
124
+ }
125
+
126
+ return true;
127
+ };
128
+ }
129
+
130
+ export async function main(argv: string[]): Promise<void> {
131
+ const yargs = makeCLI(hideBin(process.argv))
132
+ .command(
133
+ // the default is to simply print the help menu
134
+ ["*"],
135
+ false,
136
+ () => {},
137
+ (args) => {
138
+ yargs.showHelp("log");
139
+ if (args._.length > 0) {
140
+ console.error(`\nUnknown command: ${args._}.`);
141
+ }
142
+ }
143
+ )
144
+ .scriptName("wrangler")
145
+ .wrap(null);
146
+
147
+ // you will note that we use the form for all commands where we use the builder function
148
+ // to define options and subcommands. Further we return the result of this builder even
149
+ // tho it's not completely necessary. The reason is that it's required for type inference
150
+ // of the args in the handle function.I wish we could enforce this pattern, but this
151
+ // comment will have to do for now.
152
+
153
+ // also annoying that choices[] doesn't get inferred as an enum. bleh.
154
+
155
+ // [DEPRECATED] generate
156
+ yargs.command(
157
+ // we definitely want to move away from us cloning github templates
158
+ // we can do something better here, let's see
159
+ "generate [name] [template]",
160
+ false,
161
+ (yargs) => {
162
+ return yargs
163
+ .positional("name", {
164
+ describe: "Name of the Workers project",
165
+ default: "worker",
166
+ })
167
+ .positional("template", {
168
+ describe: "a link to a GitHub template",
169
+ default: "https://github.com/cloudflare/worker-template",
170
+ });
171
+ },
172
+ () => {
173
+ // "👯 [DEPRECATED]. Scaffold a Cloudflare Workers project from a public GitHub repository.",
174
+ console.error(
175
+ "`wrangler generate` has been deprecated, please refer to TODO://some/path for alternatives"
176
+ );
177
+ }
178
+ );
179
+
180
+ // init
181
+ yargs.command(
182
+ "init [name]",
183
+ "📥 Create a wrangler.toml configuration file",
184
+ (yargs) => {
185
+ return yargs.positional("name", {
186
+ describe: "The name of your worker.",
187
+ type: "string",
188
+ });
189
+ },
190
+ async (args) => {
191
+ if ("type" in args) {
192
+ let message = "The --type option is no longer supported.";
193
+ if (args.type === "webpack") {
194
+ message +=
195
+ "\nIf you wish to use webpack then you will need to create a custom build.";
196
+ // TODO: Add a link to docs
197
+ }
198
+ console.error(message);
199
+ return;
200
+ }
201
+
202
+ const destination = path.join(process.cwd(), "wrangler.toml");
203
+ if (fs.existsSync(destination)) {
204
+ console.error(`${destination} file already exists!`);
205
+ const result = await confirm(
206
+ "Do you want to continue initializing this project?"
207
+ );
208
+ if (!result) {
209
+ return;
210
+ }
211
+ }
212
+
213
+ const compatibilityDate = new Date().toISOString().substring(0, 10);
214
+ try {
215
+ await writeFile(
216
+ destination,
217
+ `compatibility_date = "${compatibilityDate}"` + "\n"
218
+ );
219
+ console.log(`✨ Successfully created wrangler.toml`);
220
+ // TODO: suggest next steps?
221
+ } catch (err) {
222
+ console.error(`Failed to create wrangler.toml`);
223
+ console.error(err);
224
+ throw err;
225
+ }
226
+
227
+ // if no package.json, ask, and if yes, create one
228
+ let pathToPackageJson = await findUp("package.json");
229
+
230
+ if (!pathToPackageJson) {
231
+ if (
232
+ await confirm("No package.json found. Would you like to create one?")
233
+ ) {
234
+ await writeFile(
235
+ path.join(process.cwd(), "package.json"),
236
+ JSON.stringify(
237
+ {
238
+ name: "worker",
239
+ version: "0.0.1",
240
+ },
241
+ null,
242
+ " "
243
+ ) + "\n"
244
+ );
245
+ console.log(`✨ Created package.json`);
246
+ pathToPackageJson = path.join(process.cwd(), "package.json");
247
+ } else {
248
+ return;
249
+ }
250
+ }
251
+
252
+ // if workers-types doesn't exist as a dependency
253
+ // offer to install it
254
+ // and make a tsconfig?
255
+ let pathToTSConfig = await findUp("tsconfig.json");
256
+ if (!pathToTSConfig) {
257
+ if (await confirm("Would you like to use typescript?")) {
258
+ await writeFile(
259
+ path.join(process.cwd(), "tsconfig.json"),
260
+ JSON.stringify(
261
+ {
262
+ compilerOptions: {
263
+ target: "esnext",
264
+ module: "esnext",
265
+ moduleResolution: "node",
266
+ esModuleInterop: true,
267
+ allowJs: true,
268
+ allowSyntheticDefaultImports: true,
269
+ isolatedModules: true,
270
+ noEmit: true,
271
+ lib: ["esnext"],
272
+ jsx: "react",
273
+ resolveJsonModule: true,
274
+ types: ["@cloudflare/workers-types"],
275
+ },
276
+ },
277
+ null,
278
+ " "
279
+ ) + "\n"
280
+ );
281
+ await execa("npm", [
282
+ "install",
283
+ "@cloudflare/workers-types",
284
+ "--save-dev",
285
+ ]);
286
+ console.log(
287
+ `✨ Created tsconfig.json, installed @cloudflare/workers-types into devDependencies`
288
+ );
289
+ pathToTSConfig = path.join(process.cwd(), "tsconfig.json");
290
+ }
291
+ }
292
+ }
293
+ );
294
+
295
+ // build
296
+ yargs.command(
297
+ "build",
298
+ false,
299
+ (yargs) => {
300
+ return yargs.option("env", {
301
+ describe: "Perform on a specific environment",
302
+ });
303
+ },
304
+ () => {
305
+ // "[DEPRECATED] 🦀 Build your project (if applicable)",
306
+ console.error(
307
+ "`wrangler build` has been deprecated, please refer to TODO://some/path for alternatives"
308
+ );
309
+ }
310
+ );
311
+
312
+ // login
313
+ yargs.command(
314
+ // this needs scopes as an option?
315
+ "login",
316
+ false, // we don't need to show this in the menu
317
+ // "🔓 Login to Cloudflare",
318
+ (yargs) => {
319
+ // TODO: This needs some copy editing
320
+ // I mean, this entire app does, but this too.
321
+ return yargs
322
+ .option("scopes-list", {
323
+ describe: "list all the available OAuth scopes with descriptions.",
324
+ })
325
+ .option("scopes", {
326
+ describe: "allows to choose your set of OAuth scopes.",
327
+ array: true,
328
+ type: "string",
329
+ });
330
+
331
+ // TODO: scopes
332
+ },
333
+ async (args) => {
334
+ if (args["scopes-list"]) {
335
+ listScopes();
336
+ return;
337
+ }
338
+ if (args.scopes) {
339
+ if (args.scopes.length === 0) {
340
+ // don't allow no scopes to be passed, that would be weird
341
+ listScopes();
342
+ return;
343
+ }
344
+ await login({ scopes: args.scopes });
345
+ return;
346
+ }
347
+ await login();
348
+
349
+ // TODO: would be nice if it optionally saved login
350
+ // creds inside node_modules/.cache or something
351
+ // this way you could have multiple users on a single machine
352
+ }
353
+ );
354
+
355
+ // logout
356
+ yargs.command(
357
+ // this needs scopes as an option?
358
+ "logout",
359
+ false, // we don't need to show this in the menu
360
+ // "🚪 Logout from Cloudflare",
361
+ () => {},
362
+ async () => {
363
+ await logout();
364
+ }
365
+ );
366
+
367
+ // whoami
368
+ yargs.command(
369
+ "whoami",
370
+ false, // we don't need to show this the menu
371
+ // "🕵️ Retrieve your user info and test your auth config",
372
+ () => {},
373
+ (args) => {
374
+ console.log(":whoami", args);
375
+ }
376
+ );
377
+
378
+ // config
379
+ yargs.command(
380
+ "config",
381
+ false,
382
+ () => {},
383
+ () => {
384
+ // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
385
+ console.error(
386
+ "`wrangler config` has been deprecated, please refer to TODO://some/path for alternatives"
387
+ );
388
+ }
389
+ );
390
+
391
+ // dev
392
+ yargs.command(
393
+ "dev <filename>",
394
+ "👂 Start a local server for developing your worker",
395
+ (yargs) => {
396
+ return yargs
397
+ .positional("filename", { describe: "entry point", type: "string" })
398
+ .option("name", {
399
+ describe: "name of the script",
400
+ type: "string",
401
+ })
402
+ .option("format", {
403
+ choices: ["modules", "service-worker"] as const,
404
+ describe: "Choose an entry type",
405
+ })
406
+ .option("env", {
407
+ describe: "Perform on a specific environment",
408
+ type: "string",
409
+ // TODO: get choices for the toml file?
410
+ })
411
+ .option("ip", {
412
+ describe: "IP address to listen on",
413
+ type: "string",
414
+ default: "127.0.0.1",
415
+ })
416
+ .option("port", {
417
+ describe: "Port to listen on, defaults to 8787",
418
+ type: "number",
419
+ default: 8787,
420
+ })
421
+ .option("host", {
422
+ type: "string",
423
+ describe:
424
+ "Host to forward requests to, defaults to the zone of project",
425
+ })
426
+ .option("local-protocol", {
427
+ default: "http",
428
+ describe: "Protocol to listen to requests on, defaults to http.",
429
+ choices: ["http", "https"],
430
+ })
431
+ .option("public", {
432
+ describe: "Static assets to be served",
433
+ type: "string",
434
+ })
435
+ .option("site", {
436
+ describe: "Root folder of static assets for Workers Sites",
437
+ type: "string",
438
+ })
439
+ .option("upstream-protocol", {
440
+ default: "https",
441
+ describe:
442
+ "Protocol to forward requests to host on, defaults to https.",
443
+ choices: ["http", "https"],
444
+ })
445
+ .option("jsx-factory", {
446
+ describe: "The function that is called for each JSX element",
447
+ type: "string",
448
+ })
449
+ .option("jsx-fragment", {
450
+ describe: "The function that is called for each JSX fragment",
451
+ type: "string",
452
+ });
453
+ },
454
+ async (args) => {
455
+ const { filename, format } = args;
456
+ const config = args.config as Config;
457
+
458
+ // -- snip, extract --
459
+
460
+ if (!args.local) {
461
+ const loggedIn = await loginOrRefreshIfRequired();
462
+ if (!loggedIn) {
463
+ // didn't login, let's just quit
464
+ console.log("Did not login, quitting...");
465
+ return;
466
+ }
467
+ if (!config.account_id) {
468
+ config.account_id = await getAccountId();
469
+ if (!config.account_id) {
470
+ console.error("No account id found, quitting...");
471
+ return;
472
+ }
473
+ }
474
+ }
475
+
476
+ // -- snip, end --
477
+
478
+ const envRootObj = args.env ? config.env[args.env] || {} : config;
479
+
480
+ // TODO: this error shouldn't actually happen,
481
+ // but we haven't fixed it internally yet
482
+ if ("durable_objects" in envRootObj) {
483
+ if (!(args.name || config.name)) {
484
+ console.warn(
485
+ 'A worker with durable objects need 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.'
486
+ );
487
+ }
488
+ // TODO: if not already published, publish a draft worker
489
+ }
490
+
491
+ render(
492
+ <Dev
493
+ name={args.name || config.name}
494
+ entry={filename}
495
+ format={format}
496
+ initialMode={args.local ? "local" : "remote"}
497
+ jsxFactory={args["jsx-factory"] || envRootObj?.jsx_factory}
498
+ jsxFragment={args["jsx-fragment"] || envRootObj?.jsx_fragment}
499
+ accountId={config.account_id}
500
+ site={args.site || config.site?.bucket}
501
+ port={args.port || config.dev?.port}
502
+ public={args.public}
503
+ compatibilityDate={config.compatibility_date}
504
+ compatibilityFlags={config.compatibility_flags}
505
+ usageModel={config.usage_model}
506
+ variables={{
507
+ ...(envRootObj?.vars || {}),
508
+ ...(envRootObj?.kv_namespaces || []).reduce(
509
+ (obj, { binding, preview_id }) => {
510
+ if (!preview_id) {
511
+ // TODO: This error has to be a _lot_ better, ideally just asking
512
+ // to create a preview namespace for the user automatically
513
+ throw new Error(
514
+ "kv namespaces need a preview id during dev mode"
515
+ );
516
+ }
517
+ return { ...obj, [binding]: { namespaceId: preview_id } };
518
+ },
519
+ {}
520
+ ),
521
+ ...(envRootObj?.durable_objects?.bindings || []).reduce(
522
+ (obj, { name, class_name, script_name }) => {
523
+ return { ...obj, [name]: { class_name, script_name } };
524
+ },
525
+ {}
526
+ ),
527
+ }}
528
+ />
529
+ );
530
+ }
531
+ );
532
+
533
+ // publish
534
+ yargs.command(
535
+ "publish [script]",
536
+ "🆙 Publish your Worker to Cloudflare.",
537
+ (yargs) => {
538
+ return yargs
539
+ .option("env", {
540
+ type: "string",
541
+ describe: "Perform on a specific environment",
542
+ })
543
+ .positional("script", {
544
+ describe: "script to upload",
545
+ type: "string",
546
+ })
547
+ .option("name", {
548
+ describe: "name to use when uploading",
549
+ type: "string",
550
+ })
551
+ .option("public", {
552
+ describe: "Static assets to be served",
553
+ type: "string",
554
+ })
555
+ .option("site", {
556
+ describe: "Root folder of static assets for Workers Sites",
557
+ type: "string",
558
+ })
559
+ .option("triggers", {
560
+ describe: "cron schedules to attach",
561
+ alias: ["schedule", "schedules"],
562
+ type: "array",
563
+ })
564
+ .option("routes", {
565
+ describe: "routes to upload",
566
+ alias: "route",
567
+ type: "array",
568
+ })
569
+ .option("services", {
570
+ describe: "experimental support for services",
571
+ type: "boolean",
572
+ default: "false",
573
+ hidden: true,
574
+ })
575
+ .option("jsx-factory", {
576
+ describe: "The function that is called for each JSX element",
577
+ type: "string",
578
+ })
579
+ .option("jsx-fragment", {
580
+ describe: "The function that is called for each JSX fragment",
581
+ type: "string",
582
+ });
583
+ },
584
+ async (args) => {
585
+ if (args.local) {
586
+ console.error("🚫 Local publishing is not yet supported");
587
+ return;
588
+ }
589
+ const config = args.config as Config;
590
+
591
+ // -- snip, extract --
592
+ if (!args.local) {
593
+ const loggedIn = await loginOrRefreshIfRequired();
594
+ if (!loggedIn) {
595
+ // didn't login, let's just quit
596
+ console.log("Did not login, quitting...");
597
+ return;
598
+ }
599
+ if (!config.account_id) {
600
+ config.account_id = await getAccountId();
601
+ if (!config.account_id) {
602
+ console.error("No account id found, quitting...");
603
+ return;
604
+ }
605
+ }
606
+ }
607
+
608
+ // -- snip, end --
609
+
610
+ await publish({
611
+ config: args.config as Config,
612
+ name: args.name,
613
+ script: args.script,
614
+ env: args.env,
615
+ triggers: args.triggers,
616
+ jsxFactory: args["jsx-factory"],
617
+ jsxFragment: args["jsx-fragment"],
618
+ routes: args.routes,
619
+ public: args.public,
620
+ site: args.site,
621
+ });
622
+ }
623
+ );
624
+
625
+ // tail
626
+ yargs.command(
627
+ "tail [name]",
628
+ "🦚 Starts a log tailing session for a deployed Worker.",
629
+ (yargs) => {
630
+ return (
631
+ yargs
632
+ .positional("name", {
633
+ describe: "name of the worker",
634
+ type: "string",
635
+ })
636
+ // TODO: auto-detect if this should be json or pretty based on atty
637
+ .option("format", {
638
+ default: "json",
639
+ choices: ["json", "pretty"],
640
+ describe: "The format of log entries",
641
+ })
642
+ .option("status", {
643
+ choices: ["ok", "error", "canceled"],
644
+ describe: "Filter by invocation status",
645
+ })
646
+ .option("header", {
647
+ type: "string",
648
+ describe: "Filter by HTTP header",
649
+ })
650
+ .option("method", {
651
+ type: "string",
652
+ describe: "Filter by HTTP method",
653
+ })
654
+ .option("sampling-rate", {
655
+ type: "number",
656
+ describe: "Adds a percentage of requests to log sampling rate",
657
+ })
658
+ .option("search", {
659
+ type: "string",
660
+ describe: "Filter by a text match in console.log messages",
661
+ })
662
+ .option("env", {
663
+ type: "string",
664
+ describe: "Perform on a specific environment",
665
+ })
666
+ );
667
+ // TODO: filter by client ip, which can be 'self' or an ip address
668
+ },
669
+ async (args) => {
670
+ const config = args.config as Config;
671
+
672
+ if (!(args.name || config.name)) {
673
+ console.error("Missing script name");
674
+ return;
675
+ }
676
+ const scriptName = `${args.name || config.name}${
677
+ args.env ? `-${args.env}` : ""
678
+ }`;
679
+
680
+ // -- snip, extract --
681
+
682
+ if (!args.local) {
683
+ const loggedIn = await loginOrRefreshIfRequired();
684
+ if (!loggedIn) {
685
+ // didn't login, let's just quit
686
+ console.log("Did not login, quitting...");
687
+ return;
688
+ }
689
+ if (!config.account_id) {
690
+ config.account_id = await getAccountId();
691
+ if (!config.account_id) {
692
+ console.error("No account id found, quitting...");
693
+ return;
694
+ }
695
+ }
696
+ }
697
+
698
+ // -- snip, end --
699
+
700
+ const accountId = config.account_id;
701
+
702
+ const filters = {
703
+ status: args.status as "ok" | "error" | "canceled",
704
+ header: args.header,
705
+ method: args.method,
706
+ "sampling-rate": args["sampling-rate"],
707
+ search: args.search,
708
+ };
709
+
710
+ const { tail, expiration, /* sendHeartbeat, */ deleteTail } =
711
+ await createTail(accountId, scriptName, filters);
712
+
713
+ console.log(
714
+ `successfully created tail, expires at ${expiration.toLocaleString()}`
715
+ );
716
+
717
+ onExit(async () => {
718
+ tail.terminate();
719
+ await deleteTail();
720
+ });
721
+
722
+ tail.on("message", (data) => {
723
+ console.log(JSON.stringify(JSON.parse(data.toString()), null, " "));
724
+ });
725
+
726
+ while (tail.readyState !== tail.OPEN) {
727
+ switch (tail.readyState) {
728
+ case tail.CONNECTING:
729
+ await setTimeout(1000);
730
+ break;
731
+ case tail.CLOSING:
732
+ await setTimeout(1000);
733
+ break;
734
+ case tail.CLOSED:
735
+ process.exit(1);
736
+ }
737
+ }
738
+
739
+ console.log(`Connected to ${scriptName}, waiting for logs...`);
740
+ }
741
+ );
742
+
743
+ // preview
744
+ yargs.command(
745
+ "preview [method] [body]",
746
+ false,
747
+ (yargs) => {
748
+ return yargs
749
+ .positional("method", {
750
+ describe: "Type of request to preview your worker",
751
+ choices: ["GET", "POST"],
752
+ default: ["GET"],
753
+ })
754
+ .positional("body", {
755
+ type: "string",
756
+ describe: "Body string to post to your preview worker request.",
757
+ default: "Null",
758
+ })
759
+ .option("env", {
760
+ type: "string",
761
+ describe: "Perform on a specific environment",
762
+ })
763
+ .option("watch", {
764
+ default: true,
765
+ describe: "Enable live preview",
766
+ type: "boolean",
767
+ });
768
+ },
769
+ () => {
770
+ // "🔬 [DEPRECATED] Preview your code temporarily on cloudflareworkers.com"
771
+ console.error(
772
+ "`wrangler preview` has been deprecated, please refer to TODO://some/path for alternatives"
773
+ );
774
+ }
775
+ );
776
+
777
+ // route
778
+ yargs.command(
779
+ "route",
780
+ false, // I think we want to hide this command
781
+ // "➡️ List or delete worker routes",
782
+ (yargs) => {
783
+ return yargs
784
+ .command(
785
+ "list",
786
+ "List a route associated with a zone",
787
+ (yargs) => {
788
+ return yargs
789
+ .option("env", {
790
+ type: "string",
791
+ describe: "Perform on a specific environment",
792
+ })
793
+ .option("zone", {
794
+ type: "string",
795
+ describe: "zone id",
796
+ })
797
+ .positional("zone", {
798
+ describe: "zone id",
799
+ type: "string",
800
+ });
801
+ },
802
+ async (args) => {
803
+ console.log(":route list", args);
804
+ // TODO: use environment (current wrangler doesn't do so?)
805
+ const zone = args.zone || (args.config as Config).zone_id;
806
+ if (!zone) {
807
+ console.error("missing zone id");
808
+ return;
809
+ }
810
+
811
+ console.log(await cfetch(`/zones/${zone}/workers/routes`));
812
+ }
813
+ )
814
+ .command(
815
+ "delete <id>",
816
+ "Delete a route associated with a zone",
817
+ (yargs) => {
818
+ return yargs
819
+ .positional("id", {
820
+ describe: "The hash of the route ID to delete.",
821
+ type: "string",
822
+ })
823
+ .option("zone", {
824
+ type: "string",
825
+ describe: "zone id",
826
+ })
827
+ .option("env", {
828
+ type: "string",
829
+ describe: "Perform on a specific environment",
830
+ });
831
+ },
832
+ async (args) => {
833
+ console.log(":route delete", args);
834
+ // TODO: use environment (current wrangler doesn't do so?)
835
+ const zone = args.zone || (args.config as Config).zone_id;
836
+ if (!zone) {
837
+ throw new Error("missing zone id");
838
+ }
839
+
840
+ console.log(
841
+ await cfetch(`/zones/${zone}/workers/routes/${args.id}`, {
842
+ method: "DELETE",
843
+ })
844
+ );
845
+ }
846
+ );
847
+ }
848
+ );
849
+
850
+ // subdomain
851
+ yargs.command(
852
+ "subdomain [name]",
853
+ false,
854
+ // "👷 Create or change your workers.dev subdomain.",
855
+ (yargs) => {
856
+ return yargs.positional("name", { type: "string" });
857
+ },
858
+ () => {
859
+ console.error(
860
+ "`wrangler subdomain` has been deprecated, please refer to TODO://some/path for alternatives"
861
+ );
862
+ }
863
+ );
864
+
865
+ // secret
866
+ yargs.command(
867
+ "secret",
868
+ "🤫 Generate a secret that can be referenced in the worker script",
869
+ (yargs) => {
870
+ return yargs
871
+ .command(
872
+ "put <key>",
873
+ "Create or update a secret variable for a script",
874
+ (yargs) => {
875
+ return yargs
876
+ .positional("key", {
877
+ describe: "The variable name to be accessible in the script.",
878
+ type: "string",
879
+ })
880
+ .option("name", {
881
+ describe: "name of the script",
882
+ type: "string",
883
+ })
884
+ .option("env", {
885
+ type: "string",
886
+ describe:
887
+ "Binds the secret to the script of the specific environment.",
888
+ });
889
+ },
890
+ async (args) => {
891
+ if (args.local) {
892
+ console.error("--local not implemented for this command yet");
893
+ return;
894
+ }
895
+ const config = args.config as Config;
896
+
897
+ // TODO: use environment (how does current wrangler do it?)
898
+ const scriptName = args.name || config.name;
899
+ if (!scriptName) {
900
+ console.error("Missing script name");
901
+ return;
902
+ }
903
+
904
+ // -- snip, extract --
905
+
906
+ if (!args.local) {
907
+ const loggedIn = await loginOrRefreshIfRequired();
908
+ if (!loggedIn) {
909
+ // didn't login, let's just quit
910
+ console.log("Did not login, quitting...");
911
+ return;
912
+ }
913
+ if (!config.account_id) {
914
+ config.account_id = await getAccountId();
915
+ if (!config.account_id) {
916
+ console.error("No account id found, quitting...");
917
+ return;
918
+ }
919
+ }
920
+ }
921
+
922
+ // -- snip, end --
923
+
924
+ const secretValue = await prompt(
925
+ "Enter a secret value:",
926
+ "password"
927
+ );
928
+ async function submitSecret() {
929
+ return await cfetch(
930
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/`,
931
+ {
932
+ method: "PUT",
933
+ headers: { "Content-Type": "application/json" },
934
+ body: JSON.stringify({
935
+ name: args.key,
936
+ text: secretValue,
937
+ type: "secret_text",
938
+ }),
939
+ }
940
+ );
941
+ }
942
+
943
+ try {
944
+ console.log(await submitSecret());
945
+ } catch (e) {
946
+ if (e.code === 10007) {
947
+ // upload a draft worker
948
+ await cfetch(
949
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}`,
950
+ {
951
+ method: "PUT",
952
+ // @ts-expect-error TODO: fix this error!
953
+ body: toFormData({
954
+ main: {
955
+ name: scriptName,
956
+ content: `export default { fetch() {} }`,
957
+ type: "esm",
958
+ },
959
+ variables: {},
960
+ modules: [],
961
+ }),
962
+ }
963
+ );
964
+
965
+ // and then try again
966
+ console.log(await submitSecret());
967
+ // TODO: delete the draft worker if this failed too?
968
+ }
969
+ }
970
+ }
971
+ )
972
+ .command(
973
+ "delete <key>",
974
+ "Delete a secret variable from a script",
975
+ (yargs) => {
976
+ return yargs
977
+ .positional("key", {
978
+ describe: "The variable name to be accessible in the script.",
979
+ type: "string",
980
+ })
981
+ .option("name", {
982
+ describe: "name of the script",
983
+ type: "string",
984
+ })
985
+ .option("env", {
986
+ type: "string",
987
+ describe:
988
+ "Binds the secret to the script of the specific environment.",
989
+ });
990
+ },
991
+ async (args) => {
992
+ if (args.local) {
993
+ console.error("--local not implemented for this command yet");
994
+ return;
995
+ }
996
+ const config = args.config as Config;
997
+
998
+ // TODO: use environment (how does current wrangler do it?)
999
+ const scriptName = args.name || config.name;
1000
+ if (!scriptName) {
1001
+ throw new Error("Missing script name");
1002
+ }
1003
+
1004
+ // -- snip, extract --
1005
+
1006
+ if (!args.local) {
1007
+ const loggedIn = await loginOrRefreshIfRequired();
1008
+ if (!loggedIn) {
1009
+ // didn't login, let's just quit
1010
+ console.log("Did not login, quitting...");
1011
+ return;
1012
+ }
1013
+ if (!config.account_id) {
1014
+ config.account_id = await getAccountId();
1015
+ if (!config.account_id) {
1016
+ console.error("No account id found, quitting...");
1017
+ return;
1018
+ }
1019
+ }
1020
+ }
1021
+
1022
+ // -- snip, end --
1023
+
1024
+ if (await confirm("Are you sure you want to delete this secret?")) {
1025
+ console.log(
1026
+ `Deleting the secret ${args.key} on script ${scriptName}.`
1027
+ );
1028
+
1029
+ console.log(
1030
+ await cfetch(
1031
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets/${args.key}`,
1032
+ { method: "DELETE" }
1033
+ )
1034
+ );
1035
+ }
1036
+ }
1037
+ )
1038
+ .command(
1039
+ "list",
1040
+ "List all secrets for a script",
1041
+ (yargs) => {
1042
+ return yargs
1043
+ .option("name", {
1044
+ describe: "name of the script",
1045
+ type: "string",
1046
+ })
1047
+ .option("env", {
1048
+ type: "string",
1049
+ describe:
1050
+ "Binds the secret to the script of the specific environment.",
1051
+ });
1052
+ },
1053
+ async (args) => {
1054
+ if (args.local) {
1055
+ console.error("--local not implemented for this command yet");
1056
+ return;
1057
+ }
1058
+ const config = args.config as Config;
1059
+
1060
+ // TODO: use environment (how does current wrangler do it?)
1061
+ const scriptName = args.name || config.name;
1062
+ if (!scriptName) {
1063
+ console.error("Missing script name");
1064
+ return;
1065
+ }
1066
+
1067
+ // -- snip, extract --
1068
+
1069
+ if (!args.local) {
1070
+ const loggedIn = await loginOrRefreshIfRequired();
1071
+ if (!loggedIn) {
1072
+ // didn't login, let's just quit
1073
+ console.log("Did not login, quitting...");
1074
+ return;
1075
+ }
1076
+ if (!config.account_id) {
1077
+ config.account_id = await getAccountId();
1078
+ if (!config.account_id) {
1079
+ console.error("No account id found, quitting...");
1080
+ return;
1081
+ }
1082
+ }
1083
+ }
1084
+
1085
+ // -- snip, end --
1086
+
1087
+ console.log(
1088
+ await cfetch(
1089
+ `/accounts/${config.account_id}/workers/scripts/${scriptName}/secrets`
1090
+ )
1091
+ );
1092
+ }
1093
+ );
1094
+ }
1095
+ );
1096
+
1097
+ // kv
1098
+ // :namespace
1099
+ yargs.command(
1100
+ "kv:namespace",
1101
+ "🗂️ Interact with your Workers KV Namespaces",
1102
+ (yargs) => {
1103
+ return yargs
1104
+ .command(
1105
+ "create <namespace>",
1106
+ "Create a new namespace",
1107
+ (yargs) => {
1108
+ return yargs
1109
+ .positional("namespace", {
1110
+ describe: "The name of the new namespace",
1111
+ type: "string",
1112
+ })
1113
+ .option("env", {
1114
+ type: "string",
1115
+ describe: "Perform on a specific environment",
1116
+ })
1117
+ .option("preview", {
1118
+ type: "boolean",
1119
+ describe: "Interact with a preview namespace",
1120
+ });
1121
+ },
1122
+ async (args) => {
1123
+ if (args._.length !== 2) {
1124
+ throw new Error(
1125
+ `Did you forget to add quotes around "${
1126
+ args.namespace
1127
+ } ${args._.slice(2).join(" ")}"?`
1128
+ );
1129
+ }
1130
+ const config = args.config as Config;
1131
+ if (!config.name) {
1132
+ console.warn(
1133
+ "No configured name present, using `worker` as a prefix for the title"
1134
+ );
1135
+ }
1136
+
1137
+ const title = `${config.name || "worker"}${
1138
+ args.env ? `-${args.env}` : ""
1139
+ }-${args.namespace}${args.preview ? "_preview" : ""}`;
1140
+
1141
+ if (/[\W]+/.test(args.namespace)) {
1142
+ throw new Error("invalid binding name, needs to be js friendly");
1143
+ }
1144
+
1145
+ if (args.local) {
1146
+ const { Miniflare } = await import("miniflare");
1147
+ const mf = new Miniflare({
1148
+ kvPersist: (args.kvPersist as string) || true,
1149
+ // TODO: these options shouldn't be required
1150
+ script: ` `, // has to be a string with at least one char
1151
+ });
1152
+ await mf.getKVNamespace(title); // this should "create" the namespace
1153
+ console.log(`✨ Success! Created KV namespace ${title}`);
1154
+ return;
1155
+ }
1156
+
1157
+ // -- snip, extract --
1158
+
1159
+ if (!args.local) {
1160
+ const loggedIn = await loginOrRefreshIfRequired();
1161
+ if (!loggedIn) {
1162
+ // didn't login, let's just quit
1163
+ console.log("Did not login, quitting...");
1164
+ return;
1165
+ }
1166
+ if (!config.account_id) {
1167
+ config.account_id = await getAccountId();
1168
+ if (!config.account_id) {
1169
+ console.error("No account id found, quitting...");
1170
+ return;
1171
+ }
1172
+ }
1173
+ }
1174
+
1175
+ // -- snip, end --
1176
+
1177
+ // TODO: generate a binding name stripping non alphanumeric chars
1178
+
1179
+ console.log(`🌀 Creating namespace with title "${title}"`);
1180
+
1181
+ const response = await cfetch<{ id: string }>(
1182
+ `/accounts/${config.account_id}/storage/kv/namespaces`,
1183
+ {
1184
+ method: "POST",
1185
+ headers: {
1186
+ "Content-Type": "application/json",
1187
+ },
1188
+ body: JSON.stringify({
1189
+ title,
1190
+ }),
1191
+ }
1192
+ );
1193
+
1194
+ console.log("✨ Success!");
1195
+ console.log(
1196
+ `Add the following to your configuration file in your kv_namespaces array${
1197
+ args.env ? ` under [env.${args.env}]` : ""
1198
+ }:`
1199
+ );
1200
+ console.log(
1201
+ `{ binding = "${args.namespace}", ${
1202
+ args.preview ? "preview_" : ""
1203
+ }id = "${response.id}" }`
1204
+ );
1205
+ }
1206
+ )
1207
+ .command(
1208
+ "list",
1209
+ "Outputs a list of all KV namespaces associated with your account id.",
1210
+ {},
1211
+ async (args) => {
1212
+ if (args.local) {
1213
+ console.error(`local mode is not yet supported for this command`);
1214
+ return;
1215
+ }
1216
+
1217
+ const config = args.config as Config;
1218
+
1219
+ // -- snip, extract --
1220
+
1221
+ if (!args.local) {
1222
+ const loggedIn = await loginOrRefreshIfRequired();
1223
+ if (!loggedIn) {
1224
+ // didn't login, let's just quit
1225
+ console.log("Did not login, quitting...");
1226
+ return;
1227
+ }
1228
+ if (!config.account_id) {
1229
+ config.account_id = await getAccountId();
1230
+ if (!config.account_id) {
1231
+ console.error("No account id found, quitting...");
1232
+ return;
1233
+ }
1234
+ }
1235
+ }
1236
+
1237
+ // -- snip, end --
1238
+
1239
+ // TODO: we should show bindings if they exist for given ids
1240
+
1241
+ console.log(
1242
+ JSON.stringify(
1243
+ await listNamespaces(config.account_id),
1244
+ null,
1245
+ " "
1246
+ )
1247
+ );
1248
+ }
1249
+ )
1250
+ .command(
1251
+ "delete",
1252
+ "Deletes a given namespace.",
1253
+ (yargs) => {
1254
+ return yargs
1255
+ .option("binding", {
1256
+ type: "string",
1257
+ describe: "The name of the namespace to delete",
1258
+ })
1259
+ .option("namespace-id", {
1260
+ type: "string",
1261
+ describe: "The id of the namespace to delete",
1262
+ })
1263
+ .check(demandOneOfOption("binding", "namespace-id"))
1264
+ .option("env", {
1265
+ type: "string",
1266
+ describe: "Perform on a specific environment",
1267
+ })
1268
+ .option("preview", {
1269
+ type: "boolean",
1270
+ describe: "Interact with a preview namespace",
1271
+ });
1272
+ },
1273
+ async (args) => {
1274
+ if (args.local) {
1275
+ console.error(`local mode is not yet supported for this command`);
1276
+ return;
1277
+ }
1278
+ const config = args.config as Config;
1279
+
1280
+ const id =
1281
+ args["namespace-id"] ||
1282
+ (args.env
1283
+ ? config.env[args.env] || {}
1284
+ : config
1285
+ ).kv_namespaces.find(
1286
+ (namespace) => namespace.binding === args.binding
1287
+ )[args.preview ? "preview_id" : "id"];
1288
+ if (!id) {
1289
+ throw new Error("Are you sure? id not found");
1290
+ }
1291
+
1292
+ // -- snip, extract --
1293
+
1294
+ if (!args.local) {
1295
+ const loggedIn = await loginOrRefreshIfRequired();
1296
+ if (!loggedIn) {
1297
+ // didn't login, let's just quit
1298
+ console.log("Did not login, quitting...");
1299
+ return;
1300
+ }
1301
+
1302
+ if (!config.account_id) {
1303
+ config.account_id = await getAccountId();
1304
+ if (!config.account_id) {
1305
+ console.error("No account id found, quitting...");
1306
+ return;
1307
+ }
1308
+ }
1309
+ }
1310
+
1311
+ // -- snip, end --
1312
+
1313
+ await cfetch<{ id: string }>(
1314
+ `/accounts/${config.account_id}/storage/kv/namespaces/${id}`,
1315
+ { method: "DELETE" }
1316
+ );
1317
+
1318
+ // TODO: recommend they remove it from wrangler.toml
1319
+
1320
+ // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1321
+ // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1322
+ // n
1323
+ // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1324
+ // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
1325
+ // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
1326
+ // y
1327
+ // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
1328
+ // ✨ Success
1329
+ // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
1330
+ // ➜ test-mf
1331
+
1332
+ // TODO: do it automatically
1333
+
1334
+ // TODO: delete the preview namespace as well?
1335
+ }
1336
+ );
1337
+ }
1338
+ );
1339
+
1340
+ // :key
1341
+ yargs.command(
1342
+ "kv:key",
1343
+ "🔑 Individually manage Workers KV key-value pairs",
1344
+ (yargs) => {
1345
+ return yargs
1346
+ .command(
1347
+ "put <key> [value]",
1348
+ "Writes a single key/value pair to the given namespace.",
1349
+ (yargs) => {
1350
+ return yargs
1351
+ .positional("key", {
1352
+ type: "string",
1353
+ describe: "The key to write to.",
1354
+ })
1355
+ .positional("value", {
1356
+ type: "string",
1357
+ describe: "The value to write.",
1358
+ })
1359
+ .option("binding", {
1360
+ type: "string",
1361
+ describe: "The binding of the namespace to write to.",
1362
+ })
1363
+ .option("namespace-id", {
1364
+ type: "string",
1365
+ describe: "The id of the namespace to write to.",
1366
+ })
1367
+ .check(demandOneOfOption("binding", "namespace-id"))
1368
+ .option("env", {
1369
+ type: "string",
1370
+ describe: "Perform on a specific environment",
1371
+ })
1372
+ .option("preview", {
1373
+ type: "boolean",
1374
+ describe: "Interact with a preview namespace",
1375
+ })
1376
+ .option("ttl", {
1377
+ type: "number",
1378
+ describe: "Time for which the entries should be visible.",
1379
+ })
1380
+ .option("expiration", {
1381
+ type: "number",
1382
+ describe:
1383
+ "Time since the UNIX epoch after which the entry expires",
1384
+ })
1385
+ .option("path", {
1386
+ type: "string",
1387
+ describe: "Read value from the file at a given path.",
1388
+ })
1389
+ .check(demandOneOfOption("value", "path"));
1390
+ },
1391
+ async ({ key, ttl, expiration, ...args }) => {
1392
+ const namespaceId = getNamespaceId(args);
1393
+ const value = args.path
1394
+ ? await readFile(args.path, "utf-8")
1395
+ : args.value;
1396
+ const config = args.config as Config;
1397
+
1398
+ if (args.path) {
1399
+ console.log(
1400
+ `writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}`
1401
+ );
1402
+ } else {
1403
+ console.log(
1404
+ `writing the value "${value}" to key "${key}" on namespace ${namespaceId}`
1405
+ );
1406
+ }
1407
+
1408
+ if (args.local) {
1409
+ const { Miniflare } = await import("miniflare");
1410
+ const mf = new Miniflare({
1411
+ kvPersist: (args.kvPersist as string) || true,
1412
+ // TODO: these options shouldn't be required
1413
+ script: ` `, // has to be a string with at least one char
1414
+ });
1415
+ const ns = await mf.getKVNamespace(namespaceId);
1416
+ await ns.put(key, value, { expiration, expirationTtl: ttl });
1417
+ return;
1418
+ }
1419
+ // -- snip, extract --
1420
+
1421
+ if (!args.local) {
1422
+ const loggedIn = await loginOrRefreshIfRequired();
1423
+ if (!loggedIn) {
1424
+ // didn't login, let's just quit
1425
+ console.log("Did not login, quitting...");
1426
+ return;
1427
+ }
1428
+
1429
+ if (!config.account_id) {
1430
+ config.account_id = await getAccountId();
1431
+ if (!config.account_id) {
1432
+ console.error("No account id found, quitting...");
1433
+ return;
1434
+ }
1435
+ }
1436
+ }
1437
+
1438
+ // -- snip, end --
1439
+
1440
+ await putKeyValue(config.account_id, namespaceId, key, value, {
1441
+ expiration,
1442
+ expiration_ttl: ttl,
1443
+ });
1444
+ }
1445
+ )
1446
+ .command(
1447
+ "list",
1448
+ "Outputs a list of all keys in a given namespace.",
1449
+ (yargs) => {
1450
+ return yargs
1451
+ .option("binding", {
1452
+ type: "string",
1453
+ describe: "The name of the namespace to list",
1454
+ })
1455
+ .option("namespace-id", {
1456
+ type: "string",
1457
+ describe: "The id of the namespace to list",
1458
+ })
1459
+ .check(demandOneOfOption("binding", "namespace-id"))
1460
+ .option("env", {
1461
+ type: "string",
1462
+ describe: "Perform on a specific environment",
1463
+ })
1464
+ .option("prefix", {
1465
+ type: "string",
1466
+ describe: "A prefix to filter listed keys",
1467
+ });
1468
+ },
1469
+ async ({ prefix, ...args }) => {
1470
+ // TODO: support for limit+cursor (pagination)
1471
+
1472
+ const namespaceId = getNamespaceId(args);
1473
+ const config = args.config as Config;
1474
+
1475
+ if (args.local) {
1476
+ const { Miniflare } = await import("miniflare");
1477
+ const mf = new Miniflare({
1478
+ kvPersist: (args.kvPersist as string) || true,
1479
+ // TODO: these options shouldn't be required
1480
+ script: ` `, // has to be a string with at least one char
1481
+ });
1482
+ const ns = await mf.getKVNamespace(namespaceId);
1483
+ const listResponse = await ns.list({ prefix });
1484
+ console.log(JSON.stringify(listResponse.keys, null, " ")); // TODO: paginate, collate
1485
+ return;
1486
+ }
1487
+
1488
+ // -- snip, extract --
1489
+
1490
+ if (!args.local) {
1491
+ const loggedIn = await loginOrRefreshIfRequired();
1492
+ if (!loggedIn) {
1493
+ // didn't login, let's just quit
1494
+ console.log("Did not login, quitting...");
1495
+ return;
1496
+ }
1497
+
1498
+ if (!config.account_id) {
1499
+ config.account_id = await getAccountId();
1500
+ if (!config.account_id) {
1501
+ console.error("No account id found, quitting...");
1502
+ return;
1503
+ }
1504
+ }
1505
+ }
1506
+
1507
+ // -- snip, end --
1508
+
1509
+ console.log(
1510
+ await listNamespaceKeys(config.account_id, namespaceId, prefix)
1511
+ );
1512
+ }
1513
+ )
1514
+ .command(
1515
+ "get <key>",
1516
+ "Reads a single value by key from the given namespace.",
1517
+ (yargs) => {
1518
+ return yargs
1519
+ .positional("key", {
1520
+ describe: "The key value to get.",
1521
+ type: "string",
1522
+ })
1523
+ .option("binding", {
1524
+ type: "string",
1525
+ describe: "The name of the namespace to get from",
1526
+ })
1527
+ .option("namespace-id", {
1528
+ type: "string",
1529
+ describe: "The id of the namespace to get from",
1530
+ })
1531
+ .check(demandOneOfOption("binding", "namespace-id"))
1532
+ .option("env", {
1533
+ type: "string",
1534
+ describe: "Perform on a specific environment",
1535
+ })
1536
+ .option("preview", {
1537
+ type: "boolean",
1538
+ describe: "Interact with a preview namespace",
1539
+ });
1540
+ },
1541
+ async ({ key, ...args }) => {
1542
+ const namespaceId = getNamespaceId(args);
1543
+ const config = args.config as Config;
1544
+
1545
+ if (args.local) {
1546
+ const { Miniflare } = await import("miniflare");
1547
+ const mf = new Miniflare({
1548
+ kvPersist: (args.kvPersist as string) || true,
1549
+ // TODO: these options shouldn't be required
1550
+ script: ` `, // has to be a string with at least one char
1551
+ });
1552
+ const ns = await mf.getKVNamespace(namespaceId);
1553
+ console.log(await ns.get(key));
1554
+ return;
1555
+ }
1556
+
1557
+ // -- snip, extract --
1558
+
1559
+ if (!args.local) {
1560
+ const loggedIn = await loginOrRefreshIfRequired();
1561
+ if (!loggedIn) {
1562
+ // didn't login, let's just quit
1563
+ console.log("Did not login, quitting...");
1564
+ return;
1565
+ }
1566
+
1567
+ if (!config.account_id) {
1568
+ config.account_id = await getAccountId();
1569
+ if (!config.account_id) {
1570
+ console.error("No account id found, quitting...");
1571
+ return;
1572
+ }
1573
+ }
1574
+ }
1575
+
1576
+ // -- snip, end --
1577
+
1578
+ // annoyingly, the API for this one doesn't return the
1579
+ // data in the 'standard' format. goddammit.
1580
+ // That's why we have the fallthrough response in cfetch.
1581
+ // Oh well.
1582
+ console.log(
1583
+ await cfetch(
1584
+ `/accounts/${config.account_id}/storage/kv/namespaces/${namespaceId}/values/${key}`
1585
+ )
1586
+ );
1587
+ }
1588
+ )
1589
+ .command(
1590
+ "delete <key>",
1591
+ "Removes a single key value pair from the given namespace.",
1592
+ (yargs) => {
1593
+ return yargs
1594
+ .positional("key", {
1595
+ describe: "The key value to delete",
1596
+ type: "string",
1597
+ })
1598
+ .option("binding", {
1599
+ type: "string",
1600
+ describe: "The name of the namespace to delete from",
1601
+ })
1602
+ .option("namespace-id", {
1603
+ type: "string",
1604
+ describe: "The id of the namespace to delete from",
1605
+ })
1606
+ .check(demandOneOfOption("binding", "namespace-id"))
1607
+ .option("env", {
1608
+ type: "string",
1609
+ describe: "Perform on a specific environment",
1610
+ })
1611
+ .option("preview", {
1612
+ type: "boolean",
1613
+ describe: "Interact with a preview namespace",
1614
+ });
1615
+ },
1616
+ async ({ key, ...args }) => {
1617
+ const namespaceId = getNamespaceId(args);
1618
+
1619
+ console.log(
1620
+ `deleting the key "${key}" on namespace ${namespaceId}`
1621
+ );
1622
+
1623
+ if (args.local) {
1624
+ const { Miniflare } = await import("miniflare");
1625
+ const mf = new Miniflare({
1626
+ kvPersist: (args.kvPersist as string) || true,
1627
+ // TODO: these options shouldn't be required
1628
+ script: ` `, // has to be a string with at least one char
1629
+ });
1630
+ const ns = await mf.getKVNamespace(namespaceId);
1631
+ console.log(await ns.delete(key));
1632
+ return;
1633
+ }
1634
+
1635
+ const config = args.config as Config;
1636
+
1637
+ // -- snip, extract --
1638
+
1639
+ if (!args.local) {
1640
+ const loggedIn = await loginOrRefreshIfRequired();
1641
+ if (!loggedIn) {
1642
+ // didn't login, let's just quit
1643
+ console.log("Did not login, quitting...");
1644
+ return;
1645
+ }
1646
+
1647
+ if (!config.account_id) {
1648
+ config.account_id = await getAccountId();
1649
+ if (!config.account_id) {
1650
+ console.error("No account id found, quitting...");
1651
+ return;
1652
+ }
1653
+ }
1654
+ }
1655
+
1656
+ // -- snip, end --
1657
+
1658
+ await cfetch(
1659
+ `/accounts/${config.account_id}/storage/kv/namespaces/${namespaceId}/values/${key}`,
1660
+ { method: "DELETE" }
1661
+ );
1662
+ }
1663
+ );
1664
+ }
1665
+ );
1666
+
1667
+ // :bulk
1668
+ yargs.command(
1669
+ "kv:bulk",
1670
+ "💪 Interact with multiple Workers KV key-value pairs at once",
1671
+ (yargs) => {
1672
+ return yargs
1673
+ .command(
1674
+ "put <filename>",
1675
+ "Upload multiple key-value pairs to a namespace",
1676
+ (yargs) => {
1677
+ return yargs
1678
+ .positional("filename", {
1679
+ describe: `The JSON file of key-value pairs to upload, in form [{"key":..., "value":...}"...]`,
1680
+ type: "string",
1681
+ })
1682
+ .option("binding", {
1683
+ type: "string",
1684
+ describe: "The name of the namespace to put to",
1685
+ })
1686
+ .option("namespace-id", {
1687
+ type: "string",
1688
+ describe: "The id of the namespace to put to",
1689
+ })
1690
+ .check(demandOneOfOption("binding", "namespace-id"))
1691
+ .option("env", {
1692
+ type: "string",
1693
+ describe: "Perform on a specific environment",
1694
+ })
1695
+ .option("preview", {
1696
+ type: "boolean",
1697
+ describe: "Interact with a preview namespace",
1698
+ });
1699
+ },
1700
+ async ({ filename, ...args }) => {
1701
+ // The simplest implementation I could think of.
1702
+ // This could be made more efficient with a streaming parser/uploader
1703
+ // but we'll do that in the future if needed.
1704
+
1705
+ const namespaceId = getNamespaceId(args);
1706
+ const config = args.config as Config;
1707
+ const content = await readFile(filename, "utf-8");
1708
+ let parsedContent;
1709
+ try {
1710
+ parsedContent = JSON.parse(content);
1711
+ } catch (err) {
1712
+ console.error(`could not parse json from ${filename}`);
1713
+ throw err;
1714
+ }
1715
+
1716
+ if (args.local) {
1717
+ const { Miniflare } = await import("miniflare");
1718
+ const mf = new Miniflare({
1719
+ kvPersist: (args.kvPersist as string) || true,
1720
+ // TODO: these options shouldn't be required
1721
+ script: ` `, // has to be a string with at least one char
1722
+ });
1723
+ const ns = await mf.getKVNamespace(namespaceId);
1724
+ for (const {
1725
+ key,
1726
+ value,
1727
+ expiration,
1728
+ expiration_ttl,
1729
+ } of parsedContent) {
1730
+ await ns.put(key, value, {
1731
+ expiration,
1732
+ expirationTtl: expiration_ttl,
1733
+ });
1734
+ }
1735
+
1736
+ return;
1737
+ }
1738
+
1739
+ // -- snip, extract --
1740
+
1741
+ if (!args.local) {
1742
+ const loggedIn = await loginOrRefreshIfRequired();
1743
+ if (!loggedIn) {
1744
+ // didn't login, let's just quit
1745
+ console.log("Did not login, quitting...");
1746
+ return;
1747
+ }
1748
+
1749
+ if (!config.account_id) {
1750
+ config.account_id = await getAccountId();
1751
+ if (!config.account_id) {
1752
+ console.error("No account id found, quitting...");
1753
+ return;
1754
+ }
1755
+ }
1756
+ }
1757
+
1758
+ // -- snip, end --
1759
+
1760
+ console.log(
1761
+ await putBulkKeyValue(config.account_id, namespaceId, content)
1762
+ );
1763
+ }
1764
+ )
1765
+ .command(
1766
+ "delete <filename>",
1767
+ "Upload multiple key-value pairs to a namespace",
1768
+ (yargs) => {
1769
+ return yargs
1770
+ .positional("filename", {
1771
+ describe: `The JSON file of key-value pairs to upload, in form ["key1", "key2", ...]`,
1772
+ type: "string",
1773
+ })
1774
+ .option("binding", {
1775
+ type: "string",
1776
+ describe: "The name of the namespace to delete from",
1777
+ })
1778
+ .option("namespace-id", {
1779
+ type: "string",
1780
+ describe: "The id of the namespace to delete from",
1781
+ })
1782
+ .check(demandOneOfOption("binding", "namespace-id"))
1783
+ .option("env", {
1784
+ type: "string",
1785
+ describe: "Perform on a specific environment",
1786
+ })
1787
+ .option("preview", {
1788
+ type: "boolean",
1789
+ describe: "Interact with a preview namespace",
1790
+ });
1791
+ },
1792
+ async ({ filename, ...args }) => {
1793
+ const namespaceId = getNamespaceId(args);
1794
+ const config = args.config as Config;
1795
+ const content = await readFile(filename, "utf-8");
1796
+ let parsedContent;
1797
+ try {
1798
+ parsedContent = JSON.parse(content);
1799
+ } catch (err) {
1800
+ console.error(`could not parse json from ${filename}`);
1801
+ throw err;
1802
+ }
1803
+
1804
+ if (args.local) {
1805
+ const { Miniflare } = await import("miniflare");
1806
+ const mf = new Miniflare({
1807
+ kvPersist: (args.kvPersist as string) || true,
1808
+ // TODO: these options shouldn't be required
1809
+ script: ` `, // has to be a string with at least one char
1810
+ });
1811
+ const ns = await mf.getKVNamespace(namespaceId);
1812
+ for (const key of parsedContent) {
1813
+ await ns.delete(key);
1814
+ }
1815
+
1816
+ return;
1817
+ }
1818
+
1819
+ // -- snip, extract --
1820
+
1821
+ if (!args.local) {
1822
+ const loggedIn = await loginOrRefreshIfRequired();
1823
+ if (!loggedIn) {
1824
+ // didn't login, let's just quit
1825
+ console.log("Did not login, quitting...");
1826
+ return;
1827
+ }
1828
+
1829
+ if (!config.account_id) {
1830
+ config.account_id = await getAccountId();
1831
+ if (!config.account_id) {
1832
+ console.error("No account id found, quitting...");
1833
+ return;
1834
+ }
1835
+ }
1836
+ }
1837
+
1838
+ // -- snip, end --
1839
+
1840
+ console.log(
1841
+ await deleteBulkKeyValue(config.account_id, namespaceId, content)
1842
+ );
1843
+ }
1844
+ );
1845
+ }
1846
+ );
1847
+
1848
+ yargs.command("pages", "⚡️ Configure Cloudflare Pages", pages);
1849
+
1850
+ yargs
1851
+ .option("config", {
1852
+ alias: "c",
1853
+ describe: "Path to .toml configuration file",
1854
+ type: "string",
1855
+ async coerce(arg) {
1856
+ return await readConfig(arg);
1857
+ },
1858
+ })
1859
+ .option("local", {
1860
+ alias: "l",
1861
+ describe: "Run on my machine",
1862
+ type: "boolean",
1863
+ default: false, // I bet this will a point of contention. We'll revisit it.
1864
+ });
1865
+
1866
+ yargs.group(["config", "help", "version"], "Flags:");
1867
+ yargs.help().alias("h", "help");
1868
+ yargs.version(wranglerVersion).alias("v", "version");
1869
+ yargs.exitProcess(false);
1870
+
1871
+ await initialiseUserConfig();
1872
+
1873
+ await yargs.parse(argv);
1874
+ }