wrangler 0.0.0-ece06ea → 0.0.0-ecfbb0c

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