wrangler 0.0.0-e09abbc → 0.0.0-e0abf917

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