wrangler 0.0.0-e9ab55a → 0.0.0-e9c2b04a

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