wrangler 0.0.0-e492c10 → 0.0.0-e4abed3e

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 (182) hide show
  1. package/README.md +30 -12
  2. package/bin/wrangler.js +90 -39
  3. package/config-schema.json +3059 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +132 -86
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +2 -3
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-pretty-error.ts +40 -0
  21. package/templates/middleware/middleware-scheduled.ts +15 -0
  22. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  23. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  24. package/templates/modules-watch-stub.js +4 -0
  25. package/templates/new-worker-scheduled.js +17 -0
  26. package/templates/new-worker-scheduled.ts +32 -0
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +22 -4
  29. package/templates/no-op-worker.js +10 -0
  30. package/templates/pages-dev-pipeline.ts +32 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +190 -0
  34. package/templates/pages-template-worker.ts +198 -0
  35. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  36. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +22 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +240 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26390 -0
  45. package/wrangler-dist/cli.js +201375 -103384
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -4886
  52. package/pages/functions/buildPlugin.ts +0 -92
  53. package/pages/functions/buildWorker.ts +0 -138
  54. package/pages/functions/filepath-routing.test.ts +0 -234
  55. package/pages/functions/filepath-routing.ts +0 -189
  56. package/pages/functions/identifiers.ts +0 -78
  57. package/pages/functions/routes.ts +0 -156
  58. package/pages/functions/template-plugin.ts +0 -146
  59. package/pages/functions/template-worker.ts +0 -143
  60. package/src/__tests__/config-cache.test.ts +0 -36
  61. package/src/__tests__/configuration.test.ts +0 -3125
  62. package/src/__tests__/dev.test.tsx +0 -827
  63. package/src/__tests__/guess-worker-format.test.ts +0 -85
  64. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  65. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  66. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  67. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  68. package/src/__tests__/helpers/mock-bin.ts +0 -36
  69. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  70. package/src/__tests__/helpers/mock-console.ts +0 -87
  71. package/src/__tests__/helpers/mock-dialogs.ts +0 -90
  72. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  73. package/src/__tests__/helpers/mock-istty.ts +0 -27
  74. package/src/__tests__/helpers/mock-kv.ts +0 -33
  75. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  76. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  77. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  78. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  79. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  80. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  81. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  82. package/src/__tests__/https-options.test.ts +0 -130
  83. package/src/__tests__/index.test.ts +0 -242
  84. package/src/__tests__/init.test.ts +0 -1516
  85. package/src/__tests__/jest.setup.ts +0 -77
  86. package/src/__tests__/kv.test.ts +0 -1442
  87. package/src/__tests__/logger.test.ts +0 -115
  88. package/src/__tests__/package-manager.test.ts +0 -206
  89. package/src/__tests__/pages.test.ts +0 -327
  90. package/src/__tests__/parse.test.ts +0 -326
  91. package/src/__tests__/publish.test.ts +0 -4948
  92. package/src/__tests__/r2.test.ts +0 -210
  93. package/src/__tests__/route.test.ts +0 -45
  94. package/src/__tests__/secret.test.ts +0 -446
  95. package/src/__tests__/tail.test.ts +0 -690
  96. package/src/__tests__/user.test.ts +0 -131
  97. package/src/__tests__/whoami.test.tsx +0 -105
  98. package/src/bundle.ts +0 -169
  99. package/src/cfetch/index.ts +0 -104
  100. package/src/cfetch/internal.ts +0 -137
  101. package/src/cli.ts +0 -13
  102. package/src/config/README.md +0 -107
  103. package/src/config/config.ts +0 -234
  104. package/src/config/diagnostics.ts +0 -80
  105. package/src/config/environment.ts +0 -394
  106. package/src/config/index.ts +0 -63
  107. package/src/config/validation-helpers.ts +0 -575
  108. package/src/config/validation.ts +0 -1424
  109. package/src/config-cache.ts +0 -45
  110. package/src/create-worker-preview.ts +0 -175
  111. package/src/create-worker-upload-form.ts +0 -240
  112. package/src/dev/dev-vars.ts +0 -36
  113. package/src/dev/dev.tsx +0 -418
  114. package/src/dev/local.tsx +0 -312
  115. package/src/dev/remote.tsx +0 -213
  116. package/src/dev/use-esbuild.ts +0 -118
  117. package/src/dialogs.tsx +0 -87
  118. package/src/entry.ts +0 -267
  119. package/src/environment-variables.ts +0 -35
  120. package/src/errors.ts +0 -11
  121. package/src/https-options.ts +0 -123
  122. package/src/index.tsx +0 -2698
  123. package/src/inspect.ts +0 -623
  124. package/src/intl-polyfill.d.ts +0 -139
  125. package/src/kv.ts +0 -319
  126. package/src/logger.ts +0 -66
  127. package/src/miniflare-cli/README.md +0 -30
  128. package/src/miniflare-cli/enum-keys.ts +0 -17
  129. package/src/miniflare-cli/index.ts +0 -41
  130. package/src/miniflare-cli/request-context.ts +0 -40
  131. package/src/module-collection.ts +0 -258
  132. package/src/open-in-browser.ts +0 -26
  133. package/src/package-manager.ts +0 -127
  134. package/src/pages.tsx +0 -1875
  135. package/src/parse.ts +0 -185
  136. package/src/paths.ts +0 -26
  137. package/src/proxy.ts +0 -449
  138. package/src/publish.ts +0 -469
  139. package/src/r2.ts +0 -50
  140. package/src/selfsigned.d.ts +0 -29
  141. package/src/sites.tsx +0 -293
  142. package/src/tail/filters.ts +0 -279
  143. package/src/tail/index.ts +0 -299
  144. package/src/tail/printing.ts +0 -67
  145. package/src/update-check.ts +0 -19
  146. package/src/user.tsx +0 -1203
  147. package/src/whoami.tsx +0 -70
  148. package/src/worker.ts +0 -172
  149. package/templates/static-asset-facade.js +0 -47
  150. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  151. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  152. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  153. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  154. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  155. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  156. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  157. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  158. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  159. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  160. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  164. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  165. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  166. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  167. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  168. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  169. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  170. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  171. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  172. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  173. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  174. package/vendor/wrangler-mime/LICENSE +0 -21
  175. package/vendor/wrangler-mime/Mime.js +0 -97
  176. package/vendor/wrangler-mime/README.md +0 -187
  177. package/vendor/wrangler-mime/cli.js +0 -46
  178. package/vendor/wrangler-mime/index.js +0 -4
  179. package/vendor/wrangler-mime/lite.js +0 -4
  180. package/vendor/wrangler-mime/package.json +0 -52
  181. package/vendor/wrangler-mime/types/other.js +0 -1
  182. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/index.tsx DELETED
@@ -1,2698 +0,0 @@
1
- import * as fs from "node:fs";
2
- import { writeFile, mkdir } from "node:fs/promises";
3
- import path from "node:path";
4
- import { setTimeout } from "node:timers/promises";
5
- import TOML from "@iarna/toml";
6
- import chalk from "chalk";
7
- import { execa } from "execa";
8
- import { findUp } from "find-up";
9
- import getPort from "get-port";
10
- import { render } from "ink";
11
- import React from "react";
12
- import onExit from "signal-exit";
13
- import supportsColor from "supports-color";
14
- import makeCLI from "yargs";
15
- import { version as wranglerVersion } from "../package.json";
16
- import { fetchResult } from "./cfetch";
17
- import { findWranglerToml, readConfig } from "./config";
18
- import { createWorkerUploadForm } from "./create-worker-upload-form";
19
- import Dev from "./dev/dev";
20
- import { getVarsForDev } from "./dev/dev-vars";
21
- import { confirm, prompt } from "./dialogs";
22
- import { getEntry } from "./entry";
23
- import { DeprecationError } from "./errors";
24
- import {
25
- getNamespaceId,
26
- listNamespaces,
27
- listNamespaceKeys,
28
- putKeyValue,
29
- putBulkKeyValue,
30
- deleteBulkKeyValue,
31
- createNamespace,
32
- isValidNamespaceBinding,
33
- getKeyValue,
34
- isKeyValue,
35
- unexpectedKeyValueProps,
36
- } from "./kv";
37
- import { logger } from "./logger";
38
- import { getPackageManager } from "./package-manager";
39
- import { pages, pagesBetaWarning } from "./pages";
40
- import {
41
- formatMessage,
42
- ParseError,
43
- parseJSON,
44
- parseTOML,
45
- readFileSync,
46
- } from "./parse";
47
- import publish from "./publish";
48
- import { createR2Bucket, deleteR2Bucket, listR2Buckets } from "./r2";
49
- import { getAssetPaths } 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 type { Config } from "./config";
67
- import type { TailCLIFilters } from "./tail";
68
- import type { RawData } from "ws";
69
- import type { CommandModule } from "yargs";
70
- import type Yargs from "yargs";
71
-
72
- type ConfigPath = string | undefined;
73
-
74
- const resetColor = "\x1b[0m";
75
- const fgGreenColor = "\x1b[32m";
76
- const DEFAULT_LOCAL_PORT = 8787;
77
-
78
- function getRules(config: Config): Config["rules"] {
79
- const rules = config.rules ?? config.build?.upload?.rules ?? [];
80
-
81
- if (config.rules && config.build?.upload?.rules) {
82
- throw new Error(
83
- `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
84
- );
85
- }
86
-
87
- if (config.build?.upload?.rules) {
88
- logger.warn(
89
- `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:
90
-
91
- ${TOML.stringify({ rules: config.build.upload.rules })}`
92
- );
93
- }
94
- return rules;
95
- }
96
-
97
- async function printWranglerBanner() {
98
- // Let's not print this in tests
99
- if (typeof jest !== "undefined") {
100
- return;
101
- }
102
-
103
- const text = ` ⛅️ wrangler ${wranglerVersion} ${await updateCheck()}`;
104
-
105
- logger.log(
106
- text +
107
- "\n" +
108
- (supportsColor.stdout
109
- ? chalk.hex("#FF8800")("-".repeat(text.length))
110
- : "-".repeat(text.length))
111
- );
112
- }
113
-
114
- function isLegacyEnv(config: Config): boolean {
115
- // We only read from config here, because we've already accounted for
116
- // args["legacy-env"] in https://github.com/cloudflare/wrangler2/blob/b24aeb5722370c2e04bce97a84a1fa1e55725d79/packages/wrangler/src/config/validation.ts#L94-L98
117
- return config.legacy_env;
118
- }
119
-
120
- function getScriptName(
121
- args: { name: string | undefined; env: string | undefined },
122
- config: Config
123
- ): string | undefined {
124
- if (args.name && isLegacyEnv(config) && args.env) {
125
- throw new CommandLineArgsError(
126
- "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:" +
127
- `
128
- [env.${args.env}]
129
- name = "${args.name}"
130
- `
131
- );
132
- }
133
-
134
- return args.name ?? config.name;
135
- }
136
-
137
- /**
138
- * Alternative to the getScriptName() because special Legacy cases allowed "name", and "env" together in Wrangler1
139
- */
140
- function getLegacyScriptName(
141
- args: { name: string | undefined; env: string | undefined },
142
- config: Config
143
- ) {
144
- return args.name && args.env && isLegacyEnv(config)
145
- ? `${args.name}-${args.env}`
146
- : args.name ?? config.name;
147
- }
148
-
149
- /**
150
- * Get a promise to the streamed input from stdin.
151
- *
152
- * This function can be used to grab the incoming stream of data from, say,
153
- * piping the output of another process into the wrangler process.
154
- */
155
- function readFromStdin(): Promise<string> {
156
- return new Promise((resolve, reject) => {
157
- const stdin = process.stdin;
158
- const chunks: string[] = [];
159
-
160
- // When there is data ready to be read, the `readable` event will be triggered.
161
- // In the handler for `readable` we call `read()` over and over until all the available data has been read.
162
- stdin.on("readable", () => {
163
- let chunk;
164
- while (null !== (chunk = stdin.read())) {
165
- chunks.push(chunk);
166
- }
167
- });
168
-
169
- // When the streamed data is complete the `end` event will be triggered.
170
- // In the handler for `end` we join the chunks together and resolve the promise.
171
- stdin.on("end", () => {
172
- resolve(chunks.join(""));
173
- });
174
-
175
- // If there is an `error` event then the handler will reject the promise.
176
- stdin.on("error", (err) => {
177
- reject(err);
178
- });
179
- });
180
- }
181
-
182
- // a helper to demand one of a set of options
183
- // via https://github.com/yargs/yargs/issues/1093#issuecomment-491299261
184
- function demandOneOfOption(...options: string[]) {
185
- return function (argv: Yargs.Arguments) {
186
- const count = options.filter((option) => argv[option]).length;
187
- const lastOption = options.pop();
188
-
189
- if (count === 0) {
190
- throw new CommandLineArgsError(
191
- `Exactly one of the arguments ${options.join(
192
- ", "
193
- )} and ${lastOption} is required`
194
- );
195
- } else if (count > 1) {
196
- throw new CommandLineArgsError(
197
- `Arguments ${options.join(
198
- ", "
199
- )} and ${lastOption} are mutually exclusive`
200
- );
201
- }
202
-
203
- return true;
204
- };
205
- }
206
-
207
- class CommandLineArgsError extends Error {}
208
-
209
- export async function main(argv: string[]): Promise<void> {
210
- const wrangler = makeCLI(argv)
211
- .strict()
212
- // We handle errors ourselves in a try-catch around `yargs.parse`.
213
- // If you want the "help info" to be displayed then throw an instance of `CommandLineArgsError`.
214
- // Otherwise we just log the error that was thrown without any "help info".
215
- .showHelpOnFail(false)
216
- .fail((msg, error) => {
217
- if (!error || error.name === "YError") {
218
- // If there is no error or the error is a "YError", then this came from yargs own validation
219
- // Wrap it in a `CommandLineArgsError` so that we can handle it appropriately further up.
220
- error = new CommandLineArgsError(msg);
221
- }
222
- throw error;
223
- })
224
- .scriptName("wrangler")
225
- .wrap(null);
226
-
227
- // Default help command that supports the subcommands
228
- const subHelp: CommandModule = {
229
- command: ["*"],
230
- handler: async (args) => {
231
- setImmediate(() =>
232
- wrangler.parse([...args._.map((a) => `${a}`), "--help"])
233
- );
234
- },
235
- };
236
- wrangler.command(
237
- ["*"],
238
- false,
239
- () => {},
240
- (args) => {
241
- if (args._.length > 0) {
242
- throw new CommandLineArgsError(`Unknown command: ${args._}.`);
243
- } else {
244
- wrangler.showHelp("log");
245
- }
246
- }
247
- );
248
-
249
- // You will note that we use the form for all commands where we use the builder function
250
- // to define options and subcommands.
251
- // Further we return the result of this builder even though it's not completely necessary.
252
- // The reason is that it's required for type inference of the args in the handle function.
253
- // I wish we could enforce this pattern, but this comment will have to do for now.
254
- // (It's also annoying that choices[] doesn't get inferred as an enum. 🤷‍♂.)
255
-
256
- // [DEPRECATED] generate
257
- wrangler.command(
258
- // we definitely want to move away from us cloning github templates
259
- // we can do something better here, let's see
260
- "generate [name] [template]",
261
- false,
262
- (yargs) => {
263
- return yargs
264
- .positional("name", {
265
- describe: "Name of the Workers project",
266
- default: "worker",
267
- })
268
- .positional("template", {
269
- describe: "The URL of a GitHub template",
270
- default: "https://github.com/cloudflare/worker-template",
271
- });
272
- },
273
- (generateArgs) => {
274
- // "👯 [DEPRECATED]. Scaffold a Cloudflare Workers project from a public GitHub repository.",
275
- throw new DeprecationError(
276
- "`wrangler generate` has been deprecated.\n" +
277
- "Try running `wrangler init` to generate a basic Worker, or cloning the template repository instead:\n\n" +
278
- "```\n" +
279
- `git clone ${generateArgs.template}\n` +
280
- "```\n\n" +
281
- "Please refer to https://developers.cloudflare.com/workers/wrangler/deprecations/#generate for more information."
282
- );
283
- }
284
- );
285
-
286
- // init
287
- wrangler.command(
288
- "init [name]",
289
- "📥 Create a wrangler.toml configuration file",
290
- (yargs) => {
291
- return yargs
292
- .positional("name", {
293
- describe: "The name of your worker",
294
- type: "string",
295
- })
296
- .option("type", {
297
- describe: "The type of worker to create",
298
- type: "string",
299
- choices: ["rust", "javascript", "webpack"],
300
- hidden: true,
301
- deprecated: true,
302
- })
303
- .option("site", {
304
- hidden: true,
305
- type: "boolean",
306
- deprecated: true,
307
- })
308
- .option("yes", {
309
- describe: 'Answer "yes" to any prompts for new projects',
310
- type: "boolean",
311
- alias: "y",
312
- });
313
- },
314
- async (args) => {
315
- await printWranglerBanner();
316
- if (args.type) {
317
- let message = "The --type option is no longer supported.";
318
- if (args.type === "webpack") {
319
- message +=
320
- "\nIf you wish to use webpack then you will need to create a custom build.";
321
- // TODO: Add a link to docs
322
- }
323
- throw new CommandLineArgsError(message);
324
- }
325
-
326
- const creationDirectory = path.resolve(process.cwd(), args.name ?? "");
327
-
328
- if (args.site) {
329
- const gitDirectory =
330
- creationDirectory !== process.cwd()
331
- ? path.basename(creationDirectory)
332
- : "my-site";
333
- const message =
334
- "The --site option is no longer supported.\n" +
335
- "If you wish to create a brand new Worker Sites project then clone the `worker-sites-template` starter repository:\n\n" +
336
- "```\n" +
337
- `git clone --depth=1 --branch=wrangler2 https://github.com/cloudflare/worker-sites-template ${gitDirectory}\n` +
338
- `cd ${gitDirectory}\n` +
339
- "```\n\n" +
340
- "Find out more about how to create and maintain Sites projects at https://developers.cloudflare.com/workers/platform/sites.\n" +
341
- "Have you considered using Cloudflare Pages instead? See https://pages.cloudflare.com/.";
342
- throw new CommandLineArgsError(message);
343
- }
344
-
345
- // TODO: make sure args.name is a valid identifier for a worker name
346
- const workerName = path
347
- .basename(creationDirectory)
348
- .toLowerCase()
349
- .replaceAll(/[^a-z0-9\-_]/gm, "-");
350
-
351
- const packageManager = await getPackageManager(creationDirectory);
352
-
353
- // TODO: ask which directory to make the worker in (defaults to args.name)
354
- // TODO: if args.name isn't provided, ask what to name the worker
355
-
356
- const wranglerTomlDestination = path.join(
357
- creationDirectory,
358
- "./wrangler.toml"
359
- );
360
- let justCreatedWranglerToml = false;
361
-
362
- if (fs.existsSync(wranglerTomlDestination)) {
363
- logger.warn(
364
- `${path.relative(
365
- process.cwd(),
366
- wranglerTomlDestination
367
- )} already exists!`
368
- );
369
- const shouldContinue = await confirm(
370
- "Do you want to continue initializing this project?"
371
- );
372
- if (!shouldContinue) {
373
- return;
374
- }
375
- } else {
376
- await mkdir(creationDirectory, { recursive: true });
377
- const compatibilityDate = new Date().toISOString().substring(0, 10);
378
-
379
- try {
380
- await writeFile(
381
- wranglerTomlDestination,
382
- TOML.stringify({
383
- name: workerName,
384
- compatibility_date: compatibilityDate,
385
- }) + "\n"
386
- );
387
-
388
- logger.log(
389
- `✨ Created ${path.relative(
390
- process.cwd(),
391
- wranglerTomlDestination
392
- )}`
393
- );
394
- justCreatedWranglerToml = true;
395
- } catch (err) {
396
- throw new Error(
397
- `Failed to create ${path.relative(
398
- process.cwd(),
399
- wranglerTomlDestination
400
- )}.\n${(err as Error).message ?? err}`
401
- );
402
- }
403
- }
404
-
405
- const yesFlag = args.yes ?? false;
406
-
407
- const isInsideGitProject = Boolean(
408
- await findUp(".git", { cwd: creationDirectory, type: "directory" })
409
- );
410
- let isGitInstalled;
411
- try {
412
- isGitInstalled = (await execa("git", ["--version"])).exitCode === 0;
413
- } catch (err) {
414
- if ((err as { code: string | undefined }).code !== "ENOENT") {
415
- // only throw if the error is not because git is not installed
416
- throw err;
417
- } else {
418
- isGitInstalled = false;
419
- }
420
- }
421
- if (!isInsideGitProject && isGitInstalled) {
422
- const shouldInitGit =
423
- yesFlag ||
424
- (await confirm("Would you like to use git to manage this Worker?"));
425
- if (shouldInitGit) {
426
- await execa("git", ["init"], { cwd: creationDirectory });
427
- await writeFile(
428
- path.join(creationDirectory, ".gitignore"),
429
- readFileSync(path.join(__dirname, "../templates/gitignore"))
430
- );
431
- logger.log(
432
- args.name && args.name !== "."
433
- ? `✨ Initialized git repository at ${path.relative(
434
- process.cwd(),
435
- creationDirectory
436
- )}`
437
- : `✨ Initialized git repository`
438
- );
439
- }
440
- }
441
-
442
- let pathToPackageJson = await findUp("package.json", {
443
- cwd: creationDirectory,
444
- });
445
- let shouldCreatePackageJson = false;
446
-
447
- if (!pathToPackageJson) {
448
- // If no package.json exists, ask to create one
449
- shouldCreatePackageJson =
450
- yesFlag ||
451
- (await confirm(
452
- "No package.json found. Would you like to create one?"
453
- ));
454
-
455
- if (shouldCreatePackageJson) {
456
- await writeFile(
457
- path.join(creationDirectory, "./package.json"),
458
- JSON.stringify(
459
- {
460
- name: workerName,
461
- version: "0.0.0",
462
- devDependencies: {
463
- wrangler: wranglerVersion,
464
- },
465
- private: true,
466
- },
467
- null,
468
- " "
469
- ) + "\n"
470
- );
471
-
472
- await packageManager.install();
473
- pathToPackageJson = path.join(creationDirectory, "package.json");
474
- logger.log(
475
- `✨ Created ${path.relative(process.cwd(), pathToPackageJson)}`
476
- );
477
- } else {
478
- return;
479
- }
480
- } else {
481
- // If package.json exists and wrangler isn't installed,
482
- // then ask to add wrangler to devDependencies
483
- const packageJson = parseJSON(
484
- readFileSync(pathToPackageJson),
485
- pathToPackageJson
486
- );
487
- if (
488
- !(
489
- packageJson.devDependencies?.wrangler ||
490
- packageJson.dependencies?.wrangler
491
- )
492
- ) {
493
- const shouldInstall =
494
- yesFlag ||
495
- (await confirm(
496
- `Would you like to install wrangler into ${path.relative(
497
- process.cwd(),
498
- pathToPackageJson
499
- )}?`
500
- ));
501
- if (shouldInstall) {
502
- await packageManager.addDevDeps(`wrangler@${wranglerVersion}`);
503
- logger.log(`✨ Installed wrangler`);
504
- }
505
- }
506
- }
507
-
508
- let isTypescriptProject = false;
509
- let pathToTSConfig = await findUp("tsconfig.json", {
510
- cwd: creationDirectory,
511
- });
512
- if (!pathToTSConfig) {
513
- // If there's no tsconfig, offer to create one
514
- // and install @cloudflare/workers-types
515
- if (yesFlag || (await confirm("Would you like to use TypeScript?"))) {
516
- isTypescriptProject = true;
517
- await writeFile(
518
- path.join(creationDirectory, "./tsconfig.json"),
519
- readFileSync(path.join(__dirname, "../templates/tsconfig.json"))
520
- );
521
- await packageManager.addDevDeps(
522
- "@cloudflare/workers-types",
523
- "typescript"
524
- );
525
- pathToTSConfig = path.join(creationDirectory, "tsconfig.json");
526
- logger.log(
527
- `✨ Created ${path.relative(
528
- process.cwd(),
529
- pathToTSConfig
530
- )}, installed @cloudflare/workers-types into devDependencies`
531
- );
532
- }
533
- } else {
534
- isTypescriptProject = true;
535
- // If there's a tsconfig, check if @cloudflare/workers-types
536
- // is already installed, and offer to install it if not
537
- const packageJson = parseJSON(
538
- readFileSync(pathToPackageJson),
539
- pathToPackageJson
540
- );
541
- if (
542
- !(
543
- packageJson.devDependencies?.["@cloudflare/workers-types"] ||
544
- packageJson.dependencies?.["@cloudflare/workers-types"]
545
- )
546
- ) {
547
- const shouldInstall = await confirm(
548
- "Would you like to install the type definitions for Workers into your package.json?"
549
- );
550
- if (shouldInstall) {
551
- await packageManager.addDevDeps("@cloudflare/workers-types");
552
- // We don't update the tsconfig.json because
553
- // it could be complicated in existing projects
554
- // and we don't want to break them. Instead, we simply
555
- // tell the user that they need to update their tsconfig.json
556
- logger.log(
557
- `✨ Installed @cloudflare/workers-types.\nPlease add "@cloudflare/workers-types" to compilerOptions.types in ${path.relative(
558
- process.cwd(),
559
- pathToTSConfig
560
- )}`
561
- );
562
- }
563
- }
564
- }
565
-
566
- const packageJsonContent = parseJSON(
567
- readFileSync(pathToPackageJson),
568
- pathToPackageJson
569
- );
570
- const shouldWritePackageJsonScripts =
571
- !packageJsonContent.scripts?.start &&
572
- !packageJsonContent.scripts?.publish &&
573
- shouldCreatePackageJson;
574
-
575
- async function writePackageJsonScriptsAndUpdateWranglerToml(
576
- isWritingScripts: boolean,
577
- isCreatingWranglerToml: boolean,
578
- packagePath: string,
579
- scriptPath: string
580
- ) {
581
- if (isCreatingWranglerToml) {
582
- // rewrite wrangler.toml with main = "path/to/script"
583
- const parsedWranglerToml = parseTOML(
584
- readFileSync(wranglerTomlDestination)
585
- );
586
- fs.writeFileSync(
587
- wranglerTomlDestination,
588
- TOML.stringify({
589
- name: parsedWranglerToml.name,
590
- main: scriptPath,
591
- compatibility_date: parsedWranglerToml.compatibility_date,
592
- })
593
- );
594
- }
595
- const isNamedWorker =
596
- isCreatingWranglerToml && path.dirname(packagePath) !== process.cwd();
597
-
598
- if (isWritingScripts) {
599
- await writeFile(
600
- packagePath,
601
- JSON.stringify(
602
- {
603
- ...packageJsonContent,
604
- scripts: {
605
- ...packageJsonContent.scripts,
606
- start: isCreatingWranglerToml
607
- ? `wrangler dev`
608
- : `wrangler dev ${scriptPath}`,
609
- publish: isCreatingWranglerToml
610
- ? `wrangler publish`
611
- : `wrangler publish ${scriptPath}`,
612
- },
613
- },
614
- null,
615
- 2
616
- ) + "\n"
617
- );
618
- logger.log(
619
- `\nTo start developing your Worker, run \`${
620
- isNamedWorker ? `cd ${args.name} && ` : ""
621
- }npm start\``
622
- );
623
- logger.log(
624
- `To publish your Worker to the Internet, run \`npm run publish\``
625
- );
626
- } else {
627
- logger.log(
628
- `\nTo start developing your Worker, run \`npx wrangler dev\`${
629
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
630
- }`
631
- );
632
- logger.log(
633
- `To publish your Worker to the Internet, run \`npx wrangler publish\`${
634
- isCreatingWranglerToml ? "" : ` ${scriptPath}`
635
- }`
636
- );
637
- }
638
- }
639
-
640
- if (isTypescriptProject) {
641
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.ts"))) {
642
- const shouldCreateSource =
643
- yesFlag ||
644
- (await confirm(
645
- `Would you like to create a Worker at ${path.relative(
646
- process.cwd(),
647
- path.join(creationDirectory, "./src/index.ts")
648
- )}?`
649
- ));
650
-
651
- if (shouldCreateSource) {
652
- await mkdir(path.join(creationDirectory, "./src"), {
653
- recursive: true,
654
- });
655
- await writeFile(
656
- path.join(creationDirectory, "./src/index.ts"),
657
- readFileSync(path.join(__dirname, "../templates/new-worker.ts"))
658
- );
659
-
660
- logger.log(
661
- `✨ Created ${path.relative(
662
- process.cwd(),
663
- path.join(creationDirectory, "./src/index.ts")
664
- )}`
665
- );
666
-
667
- await writePackageJsonScriptsAndUpdateWranglerToml(
668
- shouldWritePackageJsonScripts,
669
- justCreatedWranglerToml,
670
- pathToPackageJson,
671
- "src/index.ts"
672
- );
673
- }
674
- }
675
- } else {
676
- if (!fs.existsSync(path.join(creationDirectory, "./src/index.js"))) {
677
- const shouldCreateSource =
678
- yesFlag ||
679
- (await confirm(
680
- `Would you like to create a Worker at ${path.relative(
681
- process.cwd(),
682
- path.join(creationDirectory, "./src/index.js")
683
- )}?`
684
- ));
685
-
686
- if (shouldCreateSource) {
687
- await mkdir(path.join(creationDirectory, "./src"), {
688
- recursive: true,
689
- });
690
- await writeFile(
691
- path.join(creationDirectory, "./src/index.js"),
692
- readFileSync(path.join(__dirname, "../templates/new-worker.js"))
693
- );
694
-
695
- logger.log(
696
- `✨ Created ${path.relative(
697
- process.cwd(),
698
- path.join(creationDirectory, "./src/index.js")
699
- )}`
700
- );
701
-
702
- await writePackageJsonScriptsAndUpdateWranglerToml(
703
- shouldWritePackageJsonScripts,
704
- justCreatedWranglerToml,
705
- pathToPackageJson,
706
- "src/index.js"
707
- );
708
- }
709
- }
710
- }
711
- }
712
- );
713
-
714
- // build
715
- wrangler.command(
716
- "build",
717
- false,
718
- (yargs) => {
719
- return yargs.option("env", {
720
- describe: "Perform on a specific environment",
721
- });
722
- },
723
- () => {
724
- // "[DEPRECATED] 🦀 Build your project (if applicable)",
725
- throw new DeprecationError(
726
- "`wrangler build` has been deprecated, please refer to https://github.com/cloudflare/wrangler2/blob/main/docs/deprecations.md#build for alternatives"
727
- );
728
- }
729
- );
730
-
731
- // config
732
- wrangler.command(
733
- "config",
734
- false,
735
- () => {},
736
- () => {
737
- // "🕵️ Authenticate Wrangler with a Cloudflare API Token",
738
- throw new DeprecationError(
739
- "`wrangler config` has been deprecated, please refer to https://github.com/cloudflare/wrangler2/blob/main/docs/deprecations.md#config for alternatives"
740
- );
741
- }
742
- );
743
-
744
- // dev
745
- wrangler.command(
746
- "dev [script]",
747
- "👂 Start a local server for developing your worker",
748
- (yargs) => {
749
- return yargs
750
- .positional("script", {
751
- describe: "The path to an entry point for your worker",
752
- type: "string",
753
- })
754
- .option("name", {
755
- describe: "Name of the worker",
756
- type: "string",
757
- requiresArg: true,
758
- })
759
- .option("format", {
760
- choices: ["modules", "service-worker"] as const,
761
- describe: "Choose an entry type",
762
- deprecated: true,
763
- })
764
- .option("env", {
765
- describe: "Perform on a specific environment",
766
- type: "string",
767
- requiresArg: true,
768
- alias: "e",
769
- })
770
- .option("compatibility-date", {
771
- describe: "Date to use for compatibility checks",
772
- type: "string",
773
- requiresArg: true,
774
- })
775
- .option("compatibility-flags", {
776
- describe: "Flags to use for compatibility checks",
777
- alias: "compatibility-flag",
778
- type: "string",
779
- requiresArg: true,
780
- array: true,
781
- })
782
- .option("latest", {
783
- describe: "Use the latest version of the worker runtime",
784
- type: "boolean",
785
- default: true,
786
- })
787
- .option("ip", {
788
- describe: "IP address to listen on, defaults to `localhost`",
789
- type: "string",
790
- requiresArg: true,
791
- })
792
- .option("port", {
793
- describe: "Port to listen on",
794
- type: "number",
795
- })
796
- .option("inspector-port", {
797
- describe: "Port for devtools to connect to",
798
- type: "number",
799
- })
800
- .option("routes", {
801
- describe: "Routes to upload",
802
- alias: "route",
803
- type: "string",
804
- requiresArg: true,
805
- array: true,
806
- })
807
- .option("host", {
808
- type: "string",
809
- requiresArg: true,
810
- describe:
811
- "Host to forward requests to, defaults to the zone of project",
812
- })
813
- .option("local-protocol", {
814
- describe: "Protocol to listen to requests on, defaults to http.",
815
- choices: ["http", "https"] as const,
816
- })
817
- .option("experimental-public", {
818
- describe: "Static assets to be served",
819
- type: "string",
820
- requiresArg: true,
821
- })
822
- .option("site", {
823
- describe: "Root folder of static assets for Workers Sites",
824
- type: "string",
825
- requiresArg: true,
826
- })
827
- .option("site-include", {
828
- describe:
829
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
830
- type: "string",
831
- requiresArg: true,
832
- array: true,
833
- })
834
- .option("site-exclude", {
835
- describe:
836
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
837
- type: "string",
838
- requiresArg: true,
839
- array: true,
840
- })
841
- .option("upstream-protocol", {
842
- describe:
843
- "Protocol to forward requests to host on, defaults to https.",
844
- choices: ["http", "https"] as const,
845
- })
846
- .option("jsx-factory", {
847
- describe: "The function that is called for each JSX element",
848
- type: "string",
849
- requiresArg: true,
850
- })
851
- .option("jsx-fragment", {
852
- describe: "The function that is called for each JSX fragment",
853
- type: "string",
854
- requiresArg: true,
855
- })
856
- .option("tsconfig", {
857
- describe: "Path to a custom tsconfig.json file",
858
- type: "string",
859
- requiresArg: true,
860
- })
861
- .option("local", {
862
- alias: "l",
863
- describe: "Run on my machine",
864
- type: "boolean",
865
- default: false, // I bet this will a point of contention. We'll revisit it.
866
- })
867
- .option("minify", {
868
- describe: "Minify the script",
869
- type: "boolean",
870
- })
871
- .option("node-compat", {
872
- describe: "Enable node.js compatibility",
873
- type: "boolean",
874
- })
875
- .option("experimental-enable-local-persistence", {
876
- describe: "Enable persistence for this session (only for local mode)",
877
- type: "boolean",
878
- })
879
- .option("inspect", {
880
- describe: "Enable dev tools",
881
- type: "boolean",
882
- deprecated: true,
883
- })
884
- .option("legacy-env", {
885
- type: "boolean",
886
- describe: "Use legacy environments",
887
- hidden: true,
888
- });
889
- },
890
- async (args) => {
891
- await printWranglerBanner();
892
- const configPath =
893
- (args.config as ConfigPath) ||
894
- (args.script && findWranglerToml(path.dirname(args.script)));
895
- const config = readConfig(configPath, args);
896
- const entry = await getEntry(args, config, "dev");
897
-
898
- if (args.inspect) {
899
- logger.warn(
900
- "Passing --inspect is unnecessary, now you can always connect to devtools."
901
- );
902
- }
903
-
904
- if (args["experimental-public"]) {
905
- logger.warn(
906
- "The --experimental-public field is experimental and will change in the future."
907
- );
908
- }
909
-
910
- if (args.public) {
911
- throw new Error(
912
- "The --public field has been renamed to --experimental-public, and will change behaviour in the future."
913
- );
914
- }
915
-
916
- const upstreamProtocol =
917
- args["upstream-protocol"] || config.dev.upstream_protocol;
918
- if (upstreamProtocol === "http") {
919
- logger.warn(
920
- "Setting upstream-protocol to http is not currently implemented.\n" +
921
- "If this is required in your project, please add your use case to the following issue:\n" +
922
- "https://github.com/cloudflare/wrangler2/issues/583."
923
- );
924
- }
925
-
926
- const accountId = !args.local ? await requireAuth(config) : undefined;
927
-
928
- // TODO: if worker_dev = false and no routes, then error (only for dev)
929
-
930
- /**
931
- * Given something that resembles a URL,
932
- * try to extract a host from it
933
- */
934
- function getHost(urlLike: string): string | undefined {
935
- if (
936
- !(urlLike.startsWith("http://") || urlLike.startsWith("https://"))
937
- ) {
938
- urlLike = "http://" + urlLike;
939
- }
940
- return new URL(urlLike).host;
941
- }
942
-
943
- /**
944
- * Given something that resembles a host,
945
- * try to infer a zone id from it
946
- */
947
- async function getZoneId(host: string): Promise<string | undefined> {
948
- const zones = await fetchResult<{ id: string }[]>(
949
- `/zones`,
950
- {},
951
- new URLSearchParams({ name: host })
952
- );
953
- return zones[0]?.id;
954
- }
955
-
956
- // When we're given a host (in one of the above ways), we do 2 things:
957
- // - We try to extract a host from it
958
- // - We try to get a zone id from the host
959
- //
960
- // So it turns out it's particularly hard to get a 'valid' domain
961
- // from a string, so we don't even try to validate TLDs, etc.
962
- // Once we get something that looks like w.x.y.z-ish, we then try to
963
- // get a zone id for it, by lopping off subdomains until we get a hit
964
- // from the API. That's it!
965
-
966
- let zone: { host: string; id: string } | undefined;
967
-
968
- if (!args.local) {
969
- const hostLike =
970
- args.host ||
971
- config.dev.host ||
972
- (args.routes && args.routes[0]) ||
973
- config.route ||
974
- (config.routes && config.routes[0]);
975
-
976
- let zoneId: string | undefined =
977
- typeof hostLike === "object" && "zone_id" in hostLike
978
- ? hostLike.zone_id
979
- : undefined;
980
-
981
- const host =
982
- typeof hostLike === "string"
983
- ? getHost(hostLike)
984
- : typeof hostLike === "object"
985
- ? "zone_name" in hostLike
986
- ? getHost(hostLike.zone_name)
987
- : getHost(hostLike.pattern)
988
- : undefined;
989
-
990
- const hostPieces =
991
- typeof host === "string" ? host.split(".") : undefined;
992
-
993
- while (!zoneId && hostPieces && hostPieces.length > 1) {
994
- zoneId = await getZoneId(hostPieces.join("."));
995
- hostPieces.shift();
996
- }
997
-
998
- if (host && !zoneId) {
999
- throw new Error(`Could not find zone for ${hostLike}`);
1000
- }
1001
-
1002
- zone =
1003
- typeof zoneId === "string" && typeof host === "string"
1004
- ? {
1005
- host,
1006
- id: zoneId,
1007
- }
1008
- : undefined;
1009
- }
1010
-
1011
- const nodeCompat = args.nodeCompat ?? config.node_compat;
1012
- if (nodeCompat) {
1013
- logger.warn(
1014
- "Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
1015
- );
1016
- }
1017
-
1018
- const { waitUntilExit } = render(
1019
- <Dev
1020
- name={getScriptName(args, config)}
1021
- entry={entry}
1022
- env={args.env}
1023
- zone={zone}
1024
- rules={getRules(config)}
1025
- legacyEnv={isLegacyEnv(config)}
1026
- minify={args.minify ?? config.minify}
1027
- nodeCompat={nodeCompat}
1028
- build={config.build || {}}
1029
- initialMode={args.local ? "local" : "remote"}
1030
- jsxFactory={args["jsx-factory"] || config.jsx_factory}
1031
- jsxFragment={args["jsx-fragment"] || config.jsx_fragment}
1032
- tsconfig={args.tsconfig ?? config.tsconfig}
1033
- upstreamProtocol={upstreamProtocol}
1034
- localProtocol={args["local-protocol"] || config.dev.local_protocol}
1035
- enableLocalPersistence={
1036
- args["experimental-enable-local-persistence"] || false
1037
- }
1038
- accountId={accountId}
1039
- assetPaths={getAssetPaths(
1040
- config,
1041
- args.site,
1042
- args.siteInclude,
1043
- args.siteExclude
1044
- )}
1045
- port={
1046
- args.port ||
1047
- config.dev.port ||
1048
- (await getPort({ port: DEFAULT_LOCAL_PORT }))
1049
- }
1050
- ip={args.ip || config.dev.ip}
1051
- inspectorPort={
1052
- args["inspector-port"] ?? (await getPort({ port: 9229 }))
1053
- }
1054
- public={args["experimental-public"]}
1055
- compatibilityDate={getDevCompatibilityDate(
1056
- config,
1057
- args["compatibility-date"]
1058
- )}
1059
- compatibilityFlags={
1060
- args["compatibility-flags"] || config.compatibility_flags
1061
- }
1062
- usageModel={config.usage_model}
1063
- bindings={{
1064
- kv_namespaces: config.kv_namespaces?.map(
1065
- ({ binding, preview_id, id: _id }) => {
1066
- // In `dev`, we make folks use a separate kv namespace called
1067
- // `preview_id` instead of `id` so that they don't
1068
- // break production data. So here we check that a `preview_id`
1069
- // has actually been configured.
1070
- // This whole block of code will be obsoleted in the future
1071
- // when we have copy-on-write for previews on edge workers.
1072
- if (!preview_id) {
1073
- // TODO: This error has to be a _lot_ better, ideally just asking
1074
- // to create a preview namespace for the user automatically
1075
- throw new Error(
1076
- `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
1077
- ); // Ugh, I really don't like this message very much
1078
- }
1079
- return {
1080
- binding,
1081
- id: preview_id,
1082
- };
1083
- }
1084
- ),
1085
- vars: getVarsForDev(config),
1086
- wasm_modules: config.wasm_modules,
1087
- text_blobs: config.text_blobs,
1088
- data_blobs: config.data_blobs,
1089
- durable_objects: config.durable_objects,
1090
- r2_buckets: config.r2_buckets?.map(
1091
- ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
1092
- // same idea as kv namespace preview id,
1093
- // same copy-on-write TODO
1094
- if (!preview_bucket_name) {
1095
- throw new Error(
1096
- `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
1097
- );
1098
- }
1099
- return {
1100
- binding,
1101
- bucket_name: preview_bucket_name,
1102
- };
1103
- }
1104
- ),
1105
- unsafe: config.unsafe?.bindings,
1106
- }}
1107
- crons={config.triggers.crons}
1108
- />
1109
- );
1110
- await waitUntilExit();
1111
- }
1112
- );
1113
-
1114
- // publish
1115
- wrangler.command(
1116
- "publish [script]",
1117
- "🆙 Publish your Worker to Cloudflare.",
1118
- (yargs) => {
1119
- return yargs
1120
- .option("env", {
1121
- type: "string",
1122
- requiresArg: true,
1123
- describe: "Perform on a specific environment",
1124
- alias: "e",
1125
- })
1126
- .positional("script", {
1127
- describe: "The path to an entry point for your worker",
1128
- type: "string",
1129
- requiresArg: true,
1130
- })
1131
- .option("name", {
1132
- describe: "Name of the worker",
1133
- type: "string",
1134
- requiresArg: true,
1135
- })
1136
- .option("outdir", {
1137
- describe: "Output directory for the bundled worker",
1138
- type: "string",
1139
- requiresArg: true,
1140
- })
1141
- .option("format", {
1142
- choices: ["modules", "service-worker"] as const,
1143
- describe: "Choose an entry type",
1144
- deprecated: true,
1145
- })
1146
- .option("compatibility-date", {
1147
- describe: "Date to use for compatibility checks",
1148
- type: "string",
1149
- requiresArg: true,
1150
- })
1151
- .option("compatibility-flags", {
1152
- describe: "Flags to use for compatibility checks",
1153
- alias: "compatibility-flag",
1154
- type: "string",
1155
- requiresArg: true,
1156
- array: true,
1157
- })
1158
- .option("latest", {
1159
- describe: "Use the latest version of the worker runtime",
1160
- type: "boolean",
1161
- default: false,
1162
- })
1163
- .option("experimental-public", {
1164
- describe: "Static assets to be served",
1165
- type: "string",
1166
- requiresArg: true,
1167
- })
1168
- .option("site", {
1169
- describe: "Root folder of static assets for Workers Sites",
1170
- type: "string",
1171
- requiresArg: true,
1172
- })
1173
- .option("site-include", {
1174
- describe:
1175
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
1176
- type: "string",
1177
- requiresArg: true,
1178
- array: true,
1179
- })
1180
- .option("site-exclude", {
1181
- describe:
1182
- "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
1183
- type: "string",
1184
- requiresArg: true,
1185
- array: true,
1186
- })
1187
- .option("triggers", {
1188
- describe: "cron schedules to attach",
1189
- alias: ["schedule", "schedules"],
1190
- type: "string",
1191
- requiresArg: true,
1192
- array: true,
1193
- })
1194
- .option("routes", {
1195
- describe: "Routes to upload",
1196
- alias: "route",
1197
- type: "string",
1198
- requiresArg: true,
1199
- array: true,
1200
- })
1201
- .option("jsx-factory", {
1202
- describe: "The function that is called for each JSX element",
1203
- type: "string",
1204
- requiresArg: true,
1205
- })
1206
- .option("jsx-fragment", {
1207
- describe: "The function that is called for each JSX fragment",
1208
- type: "string",
1209
- requiresArg: true,
1210
- })
1211
- .option("tsconfig", {
1212
- describe: "Path to a custom tsconfig.json file",
1213
- type: "string",
1214
- requiresArg: true,
1215
- })
1216
- .option("minify", {
1217
- describe: "Minify the script",
1218
- type: "boolean",
1219
- })
1220
- .option("node-compat", {
1221
- describe: "Enable node.js compatibility",
1222
- type: "boolean",
1223
- })
1224
- .option("dry-run", {
1225
- describe: "Don't actually publish",
1226
- type: "boolean",
1227
- })
1228
- .option("legacy-env", {
1229
- type: "boolean",
1230
- describe: "Use legacy environments",
1231
- hidden: true,
1232
- });
1233
- },
1234
- async (args) => {
1235
- await printWranglerBanner();
1236
- if (args["experimental-public"]) {
1237
- logger.warn(
1238
- "The --experimental-public field is experimental and will change in the future."
1239
- );
1240
- }
1241
- if (args.public) {
1242
- throw new Error(
1243
- "The --public field has been renamed to --experimental-public, and will change behaviour in the future."
1244
- );
1245
- }
1246
-
1247
- const configPath =
1248
- (args.config as ConfigPath) ||
1249
- (args.script && findWranglerToml(path.dirname(args.script)));
1250
- const config = readConfig(configPath, args);
1251
- const entry = await getEntry(args, config, "publish");
1252
-
1253
- if (args.latest) {
1254
- logger.warn(
1255
- "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"
1256
- );
1257
- }
1258
-
1259
- const accountId = await requireAuth(config);
1260
-
1261
- const assetPaths = getAssetPaths(
1262
- config,
1263
- args["experimental-public"] || args.site,
1264
- args.siteInclude,
1265
- args.siteExclude
1266
- );
1267
- await publish({
1268
- config,
1269
- accountId,
1270
- name: getScriptName(args, config),
1271
- rules: getRules(config),
1272
- entry,
1273
- env: args.env,
1274
- compatibilityDate: args.latest
1275
- ? new Date().toISOString().substring(0, 10)
1276
- : args["compatibility-date"],
1277
- compatibilityFlags: args["compatibility-flags"],
1278
- triggers: args.triggers,
1279
- jsxFactory: args["jsx-factory"],
1280
- jsxFragment: args["jsx-fragment"],
1281
- tsconfig: args.tsconfig,
1282
- routes: args.routes,
1283
- assetPaths,
1284
- legacyEnv: isLegacyEnv(config),
1285
- minify: args.minify,
1286
- nodeCompat: args.nodeCompat,
1287
- experimentalPublic: args["experimental-public"] !== undefined,
1288
- outDir: args.outdir,
1289
- dryRun: args.dryRun,
1290
- });
1291
- }
1292
- );
1293
-
1294
- // tail
1295
- wrangler.command(
1296
- "tail [name]",
1297
- "🦚 Starts a log tailing session for a published Worker.",
1298
- (yargs) => {
1299
- return yargs
1300
- .positional("name", {
1301
- describe: "Name of the worker",
1302
- type: "string",
1303
- })
1304
- .option("format", {
1305
- default: process.stdout.isTTY ? "pretty" : "json",
1306
- choices: ["json", "pretty"],
1307
- describe: "The format of log entries",
1308
- })
1309
- .option("status", {
1310
- choices: ["ok", "error", "canceled"],
1311
- describe: "Filter by invocation status",
1312
- array: true,
1313
- })
1314
- .option("header", {
1315
- type: "string",
1316
- requiresArg: true,
1317
- describe: "Filter by HTTP header",
1318
- })
1319
- .option("method", {
1320
- type: "string",
1321
- requiresArg: true,
1322
- describe: "Filter by HTTP method",
1323
- array: true,
1324
- })
1325
- .option("sampling-rate", {
1326
- type: "number",
1327
- describe: "Adds a percentage of requests to log sampling rate",
1328
- })
1329
- .option("search", {
1330
- type: "string",
1331
- requiresArg: true,
1332
- describe: "Filter by a text match in console.log messages",
1333
- })
1334
- .option("ip", {
1335
- type: "string",
1336
- requiresArg: true,
1337
- describe:
1338
- 'Filter by the IP address the request originates from. Use "self" to filter for your own IP',
1339
- array: true,
1340
- })
1341
- .option("env", {
1342
- type: "string",
1343
- requiresArg: true,
1344
- describe: "Perform on a specific environment",
1345
- alias: "e",
1346
- })
1347
- .option("debug", {
1348
- type: "boolean",
1349
- hidden: true,
1350
- default: false,
1351
- describe:
1352
- "If a log would have been filtered out, send it through anyway alongside the filter which would have blocked it.",
1353
- })
1354
- .option("legacy-env", {
1355
- type: "boolean",
1356
- describe: "Use legacy environments",
1357
- hidden: true,
1358
- });
1359
- },
1360
- async (args) => {
1361
- if (args.format === "pretty") {
1362
- await printWranglerBanner();
1363
- }
1364
- const config = readConfig(args.config as ConfigPath, args);
1365
-
1366
- const scriptName = getLegacyScriptName(args, config);
1367
-
1368
- if (!scriptName) {
1369
- throw new Error("Missing script name");
1370
- }
1371
-
1372
- const accountId = await requireAuth(config);
1373
-
1374
- const cliFilters: TailCLIFilters = {
1375
- status: args.status as ("ok" | "error" | "canceled")[] | undefined,
1376
- header: args.header,
1377
- method: args.method,
1378
- samplingRate: args["sampling-rate"],
1379
- search: args.search,
1380
- clientIp: args.ip,
1381
- };
1382
-
1383
- const filters = translateCLICommandToFilterMessage(
1384
- cliFilters,
1385
- args.debug
1386
- );
1387
-
1388
- const { tail, expiration, deleteTail } = await createTail(
1389
- accountId,
1390
- scriptName,
1391
- filters,
1392
- !isLegacyEnv(config) ? args.env : undefined
1393
- );
1394
-
1395
- const scriptDisplayName = `${scriptName}${
1396
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1397
- }`;
1398
-
1399
- if (args.format === "pretty") {
1400
- logger.log(
1401
- `Successfully created tail, expires at ${expiration.toLocaleString()}`
1402
- );
1403
- }
1404
-
1405
- onExit(async () => {
1406
- tail.terminate();
1407
- await deleteTail();
1408
- });
1409
-
1410
- const printLog: (data: RawData) => void =
1411
- args.format === "pretty" ? prettyPrintLogs : jsonPrintLogs;
1412
-
1413
- tail.on("message", printLog);
1414
-
1415
- while (tail.readyState !== tail.OPEN) {
1416
- switch (tail.readyState) {
1417
- case tail.CONNECTING:
1418
- await setTimeout(100);
1419
- break;
1420
- case tail.CLOSING:
1421
- await setTimeout(100);
1422
- break;
1423
- case tail.CLOSED:
1424
- throw new Error(
1425
- `Connection to ${scriptDisplayName} closed unexpectedly.`
1426
- );
1427
- }
1428
- }
1429
-
1430
- if (args.format === "pretty") {
1431
- logger.log(`Connected to ${scriptDisplayName}, waiting for logs...`);
1432
- }
1433
-
1434
- tail.on("close", async () => {
1435
- tail.terminate();
1436
- await deleteTail();
1437
- });
1438
- }
1439
- );
1440
-
1441
- // preview
1442
- wrangler.command(
1443
- "preview [method] [body]",
1444
- false,
1445
- (yargs) => {
1446
- return yargs
1447
- .positional("method", {
1448
- type: "string",
1449
- describe: "Type of request to preview your worker",
1450
- })
1451
- .positional("body", {
1452
- type: "string",
1453
- describe: "Body string to post to your preview worker request.",
1454
- })
1455
- .option("env", {
1456
- type: "string",
1457
- requiresArg: true,
1458
- describe: "Perform on a specific environment",
1459
- })
1460
- .option("watch", {
1461
- default: true,
1462
- describe: "Enable live preview",
1463
- type: "boolean",
1464
- });
1465
- },
1466
- async (args) => {
1467
- if (args.method || args.body) {
1468
- throw new DeprecationError(
1469
- "The `wrangler preview` command has been deprecated.\n" +
1470
- "Try using `wrangler dev` to to try out a worker during development.\n"
1471
- );
1472
- }
1473
-
1474
- // Delegate to `wrangler dev`
1475
- logger.warn(
1476
- "***************************************************\n" +
1477
- "The `wrangler preview` command has been deprecated.\n" +
1478
- "Attempting to run `wrangler dev` instead.\n" +
1479
- "***************************************************\n"
1480
- );
1481
-
1482
- const config = readConfig(args.config as ConfigPath, args);
1483
- const entry = await getEntry({}, config, "dev");
1484
-
1485
- const accountId = await requireAuth(config);
1486
-
1487
- const { waitUntilExit } = render(
1488
- <Dev
1489
- name={config.name}
1490
- entry={entry}
1491
- rules={getRules(config)}
1492
- env={args.env}
1493
- zone={undefined}
1494
- legacyEnv={isLegacyEnv(config)}
1495
- build={config.build || {}}
1496
- minify={undefined}
1497
- nodeCompat={config.node_compat}
1498
- initialMode={args.local ? "local" : "remote"}
1499
- jsxFactory={config.jsx_factory}
1500
- jsxFragment={config.jsx_fragment}
1501
- tsconfig={config.tsconfig}
1502
- upstreamProtocol={config.dev.upstream_protocol}
1503
- localProtocol={config.dev.local_protocol}
1504
- enableLocalPersistence={false}
1505
- accountId={accountId}
1506
- assetPaths={undefined}
1507
- port={
1508
- config.dev.port || (await getPort({ port: DEFAULT_LOCAL_PORT }))
1509
- }
1510
- ip={config.dev.ip}
1511
- public={undefined}
1512
- compatibilityDate={getDevCompatibilityDate(config)}
1513
- compatibilityFlags={config.compatibility_flags}
1514
- usageModel={config.usage_model}
1515
- bindings={{
1516
- kv_namespaces: config.kv_namespaces?.map(
1517
- ({ binding, preview_id, id: _id }) => {
1518
- // In `dev`, we make folks use a separate kv namespace called
1519
- // `preview_id` instead of `id` so that they don't
1520
- // break production data. So here we check that a `preview_id`
1521
- // has actually been configured.
1522
- // This whole block of code will be obsoleted in the future
1523
- // when we have copy-on-write for previews on edge workers.
1524
- if (!preview_id) {
1525
- // TODO: This error has to be a _lot_ better, ideally just asking
1526
- // to create a preview namespace for the user automatically
1527
- throw new Error(
1528
- `In development, you should use a separate kv namespace than the one you'd use in production. Please create a new kv namespace with "wrangler kv:namespace create <name> --preview" and add its id as preview_id to the kv_namespace "${binding}" in your wrangler.toml`
1529
- ); // Ugh, I really don't like this message very much
1530
- }
1531
- return {
1532
- binding,
1533
- id: preview_id,
1534
- };
1535
- }
1536
- ),
1537
- vars: config.vars,
1538
- wasm_modules: config.wasm_modules,
1539
- text_blobs: config.text_blobs,
1540
- data_blobs: config.data_blobs,
1541
- durable_objects: config.durable_objects,
1542
- r2_buckets: config.r2_buckets?.map(
1543
- ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
1544
- // same idea as kv namespace preview id,
1545
- // same copy-on-write TODO
1546
- if (!preview_bucket_name) {
1547
- throw new Error(
1548
- `In development, you should use a separate r2 bucket than the one you'd use in production. Please create a new r2 bucket with "wrangler r2 bucket create <name>" and add its name as preview_bucket_name to the r2_buckets "${binding}" in your wrangler.toml`
1549
- );
1550
- }
1551
- return {
1552
- binding,
1553
- bucket_name: preview_bucket_name,
1554
- };
1555
- }
1556
- ),
1557
- unsafe: config.unsafe?.bindings,
1558
- }}
1559
- crons={config.triggers.crons}
1560
- inspectorPort={await getPort({ port: 9229 })}
1561
- />
1562
- );
1563
- await waitUntilExit();
1564
- }
1565
- );
1566
-
1567
- // [DEPRECATED] route
1568
- wrangler.command(
1569
- "route",
1570
- false, // I think we want to hide this command
1571
- // "➡️ List or delete worker routes",
1572
- (routeYargs) => {
1573
- return routeYargs
1574
- .command(
1575
- "list",
1576
- "List the routes associated with a zone",
1577
- (yargs) => {
1578
- return yargs
1579
- .option("env", {
1580
- type: "string",
1581
- requiresArg: true,
1582
- describe: "Perform on a specific environment",
1583
- })
1584
- .option("zone", {
1585
- type: "string",
1586
- requiresArg: true,
1587
- describe: "Zone id",
1588
- })
1589
- .positional("zone", {
1590
- describe: "Zone id",
1591
- type: "string",
1592
- });
1593
- },
1594
- () => {
1595
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1596
- const deprecationNotice =
1597
- "`wrangler route list` has been deprecated.";
1598
- const futureRoutes =
1599
- "Refer to wrangler.toml for a list of routes the worker will be deployed to upon publishing.";
1600
- const presentRoutes =
1601
- "Refer to the Cloudflare Dashboard to see the routes this worker is currently running on.";
1602
- throw new DeprecationError(
1603
- `${deprecationNotice}\n${futureRoutes}\n${presentRoutes}`
1604
- );
1605
- }
1606
- )
1607
- .command(
1608
- "delete [id]",
1609
- "Delete a route associated with a zone",
1610
- (yargs) => {
1611
- return yargs
1612
- .positional("id", {
1613
- describe: "The hash of the route ID to delete.",
1614
- type: "string",
1615
- })
1616
- .option("zone", {
1617
- type: "string",
1618
- requiresArg: true,
1619
- describe: "zone id",
1620
- })
1621
- .option("env", {
1622
- type: "string",
1623
- requiresArg: true,
1624
- describe: "Perform on a specific environment",
1625
- });
1626
- },
1627
- () => {
1628
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1629
- const deprecationNotice =
1630
- "`wrangler route delete` has been deprecated.";
1631
- const shouldDo =
1632
- "Remove the unwanted route(s) from wrangler.toml and run `wrangler publish` to remove your worker from those routes.";
1633
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1634
- }
1635
- );
1636
- },
1637
- () => {
1638
- // "👯 [DEPRECATED]. Use wrangler.toml to manage routes.
1639
- const deprecationNotice = "`wrangler route` has been deprecated.";
1640
- const shouldDo =
1641
- "Please use wrangler.toml and/or `wrangler publish --routes` to modify routes";
1642
- throw new DeprecationError(`${deprecationNotice}\n${shouldDo}`);
1643
- }
1644
- );
1645
-
1646
- // subdomain
1647
- wrangler.command(
1648
- "subdomain [name]",
1649
- false,
1650
- // "👷 Create or change your workers.dev subdomain.",
1651
- (yargs) => {
1652
- return yargs.positional("name", { type: "string" });
1653
- },
1654
- () => {
1655
- throw new DeprecationError(
1656
- "`wrangler subdomain` has been deprecated, please refer to https://github.com/cloudflare/wrangler2/blob/main/docs/deprecations.md#subdomain for alternatives"
1657
- );
1658
- }
1659
- );
1660
-
1661
- // secret
1662
- wrangler.command(
1663
- "secret",
1664
- "🤫 Generate a secret that can be referenced in the worker script",
1665
- (secretYargs) => {
1666
- return secretYargs
1667
- .command(subHelp)
1668
- .option("legacy-env", {
1669
- type: "boolean",
1670
- describe: "Use legacy environments",
1671
- hidden: true,
1672
- })
1673
- .command(
1674
- "put <key>",
1675
- "Create or update a secret variable for a script",
1676
- (yargs) => {
1677
- return yargs
1678
- .positional("key", {
1679
- describe: "The variable name to be accessible in the script",
1680
- type: "string",
1681
- })
1682
- .option("name", {
1683
- describe: "Name of the worker",
1684
- type: "string",
1685
- requiresArg: true,
1686
- })
1687
- .option("env", {
1688
- type: "string",
1689
- requiresArg: true,
1690
- describe:
1691
- "Binds the secret to the Worker of the specific environment",
1692
- alias: "e",
1693
- });
1694
- },
1695
- async (args) => {
1696
- await printWranglerBanner();
1697
- const config = readConfig(args.config as ConfigPath, args);
1698
-
1699
- const scriptName = getLegacyScriptName(args, config);
1700
- if (!scriptName) {
1701
- throw new Error("Missing script name");
1702
- }
1703
-
1704
- const accountId = await requireAuth(config);
1705
-
1706
- const isInteractive = process.stdin.isTTY;
1707
- const secretValue = isInteractive
1708
- ? await prompt("Enter a secret value:", "password")
1709
- : await readFromStdin();
1710
-
1711
- logger.log(
1712
- `🌀 Creating the secret for script ${scriptName} ${
1713
- args.env && !isLegacyEnv(config) ? `(${args.env})` : ""
1714
- }`
1715
- );
1716
-
1717
- async function submitSecret() {
1718
- const url =
1719
- !args.env || isLegacyEnv(config)
1720
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1721
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1722
-
1723
- return await fetchResult(url, {
1724
- method: "PUT",
1725
- headers: { "Content-Type": "application/json" },
1726
- body: JSON.stringify({
1727
- name: args.key,
1728
- text: secretValue,
1729
- type: "secret_text",
1730
- }),
1731
- });
1732
- }
1733
-
1734
- const createDraftWorker = async () => {
1735
- // TODO: log a warning
1736
- await fetchResult(
1737
- !isLegacyEnv(config) && args.env
1738
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}`
1739
- : `/accounts/${accountId}/workers/scripts/${scriptName}`,
1740
- {
1741
- method: "PUT",
1742
- body: createWorkerUploadForm({
1743
- name: scriptName,
1744
- main: {
1745
- name: scriptName,
1746
- content: `export default { fetch() {} }`,
1747
- type: "esm",
1748
- },
1749
- bindings: {
1750
- kv_namespaces: [],
1751
- vars: {},
1752
- durable_objects: { bindings: [] },
1753
- r2_buckets: [],
1754
- wasm_modules: {},
1755
- text_blobs: {},
1756
- data_blobs: {},
1757
- unsafe: [],
1758
- },
1759
- modules: [],
1760
- migrations: undefined,
1761
- compatibility_date: undefined,
1762
- compatibility_flags: undefined,
1763
- usage_model: undefined,
1764
- }),
1765
- }
1766
- );
1767
- };
1768
-
1769
- function isMissingWorkerError(e: unknown): e is { code: 10007 } {
1770
- return (
1771
- typeof e === "object" &&
1772
- e !== null &&
1773
- (e as { code: number }).code === 10007
1774
- );
1775
- }
1776
-
1777
- try {
1778
- await submitSecret();
1779
- } catch (e) {
1780
- if (isMissingWorkerError(e)) {
1781
- // create a draft worker and try again
1782
- await createDraftWorker();
1783
- await submitSecret();
1784
- // TODO: delete the draft worker if this failed too?
1785
- } else {
1786
- throw e;
1787
- }
1788
- }
1789
-
1790
- logger.log(`✨ Success! Uploaded secret ${args.key}`);
1791
- }
1792
- )
1793
- .command(
1794
- "delete <key>",
1795
- "Delete a secret variable from a script",
1796
- async (yargs) => {
1797
- await printWranglerBanner();
1798
- return yargs
1799
- .positional("key", {
1800
- describe: "The variable name to be accessible in the script",
1801
- type: "string",
1802
- })
1803
- .option("name", {
1804
- describe: "Name of the worker",
1805
- type: "string",
1806
- requiresArg: true,
1807
- })
1808
- .option("env", {
1809
- type: "string",
1810
- requiresArg: true,
1811
- describe:
1812
- "Binds the secret to the Worker of the specific environment",
1813
- alias: "e",
1814
- });
1815
- },
1816
- async (args) => {
1817
- const config = readConfig(args.config as ConfigPath, args);
1818
-
1819
- const scriptName = getLegacyScriptName(args, config);
1820
- if (!scriptName) {
1821
- throw new Error("Missing script name");
1822
- }
1823
-
1824
- const accountId = await requireAuth(config);
1825
-
1826
- if (
1827
- await confirm(
1828
- `Are you sure you want to permanently delete the variable ${
1829
- args.key
1830
- } on the script ${scriptName}${
1831
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1832
- }?`
1833
- )
1834
- ) {
1835
- logger.log(
1836
- `🌀 Deleting the secret ${args.key} on script ${scriptName}${
1837
- args.env && !isLegacyEnv(config) ? ` (${args.env})` : ""
1838
- }`
1839
- );
1840
-
1841
- const url =
1842
- !args.env || isLegacyEnv(config)
1843
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1844
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1845
-
1846
- await fetchResult(`${url}/${args.key}`, { method: "DELETE" });
1847
- logger.log(`✨ Success! Deleted secret ${args.key}`);
1848
- }
1849
- }
1850
- )
1851
- .command(
1852
- "list",
1853
- "List all secrets for a script",
1854
- (yargs) => {
1855
- return yargs
1856
- .option("name", {
1857
- describe: "Name of the worker",
1858
- type: "string",
1859
- requiresArg: true,
1860
- })
1861
- .option("env", {
1862
- type: "string",
1863
- requiresArg: true,
1864
- describe:
1865
- "Binds the secret to the Worker of the specific environment.",
1866
- alias: "e",
1867
- });
1868
- },
1869
- async (args) => {
1870
- const config = readConfig(args.config as ConfigPath, args);
1871
-
1872
- const scriptName = getLegacyScriptName(args, config);
1873
- if (!scriptName) {
1874
- throw new Error("Missing script name");
1875
- }
1876
-
1877
- const accountId = await requireAuth(config);
1878
-
1879
- const url =
1880
- !args.env || isLegacyEnv(config)
1881
- ? `/accounts/${accountId}/workers/scripts/${scriptName}/secrets`
1882
- : `/accounts/${accountId}/workers/services/${scriptName}/environments/${args.env}/secrets`;
1883
-
1884
- logger.log(JSON.stringify(await fetchResult(url), null, " "));
1885
- }
1886
- );
1887
- }
1888
- );
1889
-
1890
- // kv
1891
- // :namespace
1892
- wrangler.command(
1893
- "kv:namespace",
1894
- "🗂️ Interact with your Workers KV Namespaces",
1895
- (namespaceYargs) => {
1896
- return namespaceYargs
1897
- .command(subHelp)
1898
- .command(
1899
- "create <namespace>",
1900
- "Create a new namespace",
1901
- (yargs) => {
1902
- return yargs
1903
- .positional("namespace", {
1904
- describe: "The name of the new namespace",
1905
- type: "string",
1906
- demandOption: true,
1907
- })
1908
- .option("env", {
1909
- type: "string",
1910
- requiresArg: true,
1911
- describe: "Perform on a specific environment",
1912
- alias: "e",
1913
- })
1914
- .option("preview", {
1915
- type: "boolean",
1916
- describe: "Interact with a preview namespace",
1917
- });
1918
- },
1919
- async (args) => {
1920
- await printWranglerBanner();
1921
-
1922
- if (!isValidNamespaceBinding(args.namespace)) {
1923
- throw new CommandLineArgsError(
1924
- `The namespace binding name "${args.namespace}" is invalid. It can only have alphanumeric and _ characters, and cannot begin with a number.`
1925
- );
1926
- }
1927
-
1928
- const config = readConfig(args.config as ConfigPath, args);
1929
- if (!config.name) {
1930
- logger.warn(
1931
- "No configured name present, using `worker` as a prefix for the title"
1932
- );
1933
- }
1934
-
1935
- const name = config.name || "worker";
1936
- const environment = args.env ? `-${args.env}` : "";
1937
- const preview = args.preview ? "_preview" : "";
1938
- const title = `${name}${environment}-${args.namespace}${preview}`;
1939
-
1940
- const accountId = await requireAuth(config);
1941
-
1942
- // TODO: generate a binding name stripping non alphanumeric chars
1943
-
1944
- logger.log(`🌀 Creating namespace with title "${title}"`);
1945
- const namespaceId = await createNamespace(accountId, title);
1946
-
1947
- logger.log("✨ Success!");
1948
- const envString = args.env ? ` under [env.${args.env}]` : "";
1949
- const previewString = args.preview ? "preview_" : "";
1950
- logger.log(
1951
- `Add the following to your configuration file in your kv_namespaces array${envString}:`
1952
- );
1953
- logger.log(
1954
- `{ binding = "${args.namespace}", ${previewString}id = "${namespaceId}" }`
1955
- );
1956
-
1957
- // TODO: automatically write this block to the wrangler.toml config file??
1958
- }
1959
- )
1960
- .command(
1961
- "list",
1962
- "Outputs a list of all KV namespaces associated with your account id.",
1963
- {},
1964
- async (args) => {
1965
- const config = readConfig(args.config as ConfigPath, args);
1966
-
1967
- const accountId = await requireAuth(config);
1968
-
1969
- // TODO: we should show bindings if they exist for given ids
1970
-
1971
- logger.log(
1972
- JSON.stringify(await listNamespaces(accountId), null, " ")
1973
- );
1974
- }
1975
- )
1976
- .command(
1977
- "delete",
1978
- "Deletes a given namespace.",
1979
- (yargs) => {
1980
- return yargs
1981
- .option("binding", {
1982
- type: "string",
1983
- requiresArg: true,
1984
- describe: "The name of the namespace to delete",
1985
- })
1986
- .option("namespace-id", {
1987
- type: "string",
1988
- requiresArg: true,
1989
- describe: "The id of the namespace to delete",
1990
- })
1991
- .check(demandOneOfOption("binding", "namespace-id"))
1992
- .option("env", {
1993
- type: "string",
1994
- requiresArg: true,
1995
- describe: "Perform on a specific environment",
1996
- alias: "e",
1997
- })
1998
- .option("preview", {
1999
- type: "boolean",
2000
- describe: "Interact with a preview namespace",
2001
- });
2002
- },
2003
- async (args) => {
2004
- await printWranglerBanner();
2005
- const config = readConfig(args.config as ConfigPath, args);
2006
-
2007
- let id;
2008
- try {
2009
- id = getNamespaceId(args, config);
2010
- } catch (e) {
2011
- throw new CommandLineArgsError(
2012
- "Not able to delete namespace.\n" + ((e as Error).message ?? e)
2013
- );
2014
- }
2015
-
2016
- const accountId = await requireAuth(config);
2017
-
2018
- await fetchResult<{ id: string }>(
2019
- `/accounts/${accountId}/storage/kv/namespaces/${id}`,
2020
- { method: "DELETE" }
2021
- );
2022
-
2023
- // TODO: recommend they remove it from wrangler.toml
2024
-
2025
- // test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
2026
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
2027
- // n
2028
- // 💁 Not deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
2029
- // ➜ test-mf wrangler kv:namespace delete --namespace-id 2a7d3d8b23fc4159b5afa489d6cfd388
2030
- // Are you sure you want to delete namespace 2a7d3d8b23fc4159b5afa489d6cfd388? [y/n]
2031
- // y
2032
- // 🌀 Deleting namespace 2a7d3d8b23fc4159b5afa489d6cfd388
2033
- // ✨ Success
2034
- // ⚠️ Make sure to remove this "kv-namespace" entry from your configuration file!
2035
- // ➜ test-mf
2036
-
2037
- // TODO: do it automatically
2038
-
2039
- // TODO: delete the preview namespace as well?
2040
- }
2041
- );
2042
- }
2043
- );
2044
-
2045
- // :key
2046
- wrangler.command(
2047
- "kv:key",
2048
- "🔑 Individually manage Workers KV key-value pairs",
2049
- (kvKeyYargs) => {
2050
- return kvKeyYargs
2051
- .command(subHelp)
2052
- .command(
2053
- "put <key> [value]",
2054
- "Writes a single key/value pair to the given namespace.",
2055
- (yargs) => {
2056
- return yargs
2057
- .positional("key", {
2058
- type: "string",
2059
- describe: "The key to write to",
2060
- demandOption: true,
2061
- })
2062
- .positional("value", {
2063
- type: "string",
2064
- describe: "The value to write",
2065
- })
2066
- .option("binding", {
2067
- type: "string",
2068
- requiresArg: true,
2069
- describe: "The binding of the namespace to write to",
2070
- })
2071
- .option("namespace-id", {
2072
- type: "string",
2073
- requiresArg: true,
2074
- describe: "The id of the namespace to write to",
2075
- })
2076
- .check(demandOneOfOption("binding", "namespace-id"))
2077
- .option("env", {
2078
- type: "string",
2079
- requiresArg: true,
2080
- describe: "Perform on a specific environment",
2081
- alias: "e",
2082
- })
2083
- .option("preview", {
2084
- type: "boolean",
2085
- describe: "Interact with a preview namespace",
2086
- })
2087
- .option("ttl", {
2088
- type: "number",
2089
- describe: "Time for which the entries should be visible",
2090
- })
2091
- .option("expiration", {
2092
- type: "number",
2093
- describe:
2094
- "Time since the UNIX epoch after which the entry expires",
2095
- })
2096
- .option("path", {
2097
- type: "string",
2098
- requiresArg: true,
2099
- describe: "Read value from the file at a given path",
2100
- })
2101
- .check(demandOneOfOption("value", "path"));
2102
- },
2103
- async ({ key, ttl, expiration, ...args }) => {
2104
- await printWranglerBanner();
2105
- const config = readConfig(args.config as ConfigPath, args);
2106
- const namespaceId = getNamespaceId(args, config);
2107
- // One of `args.path` and `args.value` must be defined
2108
- const value = args.path
2109
- ? readFileSync(args.path)
2110
- : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2111
- args.value!;
2112
-
2113
- if (args.path) {
2114
- logger.log(
2115
- `Writing the contents of ${args.path} to the key "${key}" on namespace ${namespaceId}.`
2116
- );
2117
- } else {
2118
- logger.log(
2119
- `Writing the value "${value}" to key "${key}" on namespace ${namespaceId}.`
2120
- );
2121
- }
2122
-
2123
- const accountId = await requireAuth(config);
2124
-
2125
- await putKeyValue(accountId, namespaceId, {
2126
- key,
2127
- value,
2128
- expiration,
2129
- expiration_ttl: ttl,
2130
- });
2131
- }
2132
- )
2133
- .command(
2134
- "list",
2135
- "Outputs a list of all keys in a given namespace.",
2136
- (yargs) => {
2137
- return yargs
2138
- .option("binding", {
2139
- type: "string",
2140
- requiresArg: true,
2141
- describe: "The name of the namespace to list",
2142
- })
2143
- .option("namespace-id", {
2144
- type: "string",
2145
- requiresArg: true,
2146
- describe: "The id of the namespace to list",
2147
- })
2148
- .check(demandOneOfOption("binding", "namespace-id"))
2149
- .option("env", {
2150
- type: "string",
2151
- requiresArg: true,
2152
- describe: "Perform on a specific environment",
2153
- alias: "e",
2154
- })
2155
- .option("preview", {
2156
- type: "boolean",
2157
- // In the case of listing keys we will default to non-preview mode
2158
- default: false,
2159
- describe: "Interact with a preview namespace",
2160
- })
2161
- .option("prefix", {
2162
- type: "string",
2163
- requiresArg: true,
2164
- describe: "A prefix to filter listed keys",
2165
- });
2166
- },
2167
- async ({ prefix, ...args }) => {
2168
- // TODO: support for limit+cursor (pagination)
2169
- const config = readConfig(args.config as ConfigPath, args);
2170
- const namespaceId = getNamespaceId(args, config);
2171
-
2172
- const accountId = await requireAuth(config);
2173
-
2174
- const results = await listNamespaceKeys(
2175
- accountId,
2176
- namespaceId,
2177
- prefix
2178
- );
2179
- logger.log(JSON.stringify(results, undefined, 2));
2180
- }
2181
- )
2182
- .command(
2183
- "get <key>",
2184
- "Reads a single value by key from the given namespace.",
2185
- (yargs) => {
2186
- return yargs
2187
- .positional("key", {
2188
- describe: "The key value to get.",
2189
- type: "string",
2190
- demandOption: true,
2191
- })
2192
- .option("binding", {
2193
- type: "string",
2194
- requiresArg: true,
2195
- describe: "The name of the namespace to get from",
2196
- })
2197
- .option("namespace-id", {
2198
- type: "string",
2199
- requiresArg: true,
2200
- describe: "The id of the namespace to get from",
2201
- })
2202
- .check(demandOneOfOption("binding", "namespace-id"))
2203
- .option("env", {
2204
- type: "string",
2205
- requiresArg: true,
2206
- describe: "Perform on a specific environment",
2207
- alias: "e",
2208
- })
2209
- .option("preview", {
2210
- type: "boolean",
2211
- describe: "Interact with a preview namespace",
2212
- })
2213
- .option("preview", {
2214
- type: "boolean",
2215
- // In the case of getting key values we will default to non-preview mode
2216
- default: false,
2217
- describe: "Interact with a preview namespace",
2218
- });
2219
- },
2220
- async ({ key, ...args }) => {
2221
- const config = readConfig(args.config as ConfigPath, args);
2222
- const namespaceId = getNamespaceId(args, config);
2223
-
2224
- const accountId = await requireAuth(config);
2225
-
2226
- logger.log(await getKeyValue(accountId, namespaceId, key));
2227
- }
2228
- )
2229
- .command(
2230
- "delete <key>",
2231
- "Removes a single key value pair from the given namespace.",
2232
- (yargs) => {
2233
- return yargs
2234
- .positional("key", {
2235
- describe: "The key value to delete",
2236
- type: "string",
2237
- demandOption: true,
2238
- })
2239
- .option("binding", {
2240
- type: "string",
2241
- requiresArg: true,
2242
- describe: "The name of the namespace to delete from",
2243
- })
2244
- .option("namespace-id", {
2245
- type: "string",
2246
- requiresArg: true,
2247
- describe: "The id of the namespace to delete from",
2248
- })
2249
- .check(demandOneOfOption("binding", "namespace-id"))
2250
- .option("env", {
2251
- type: "string",
2252
- requiresArg: true,
2253
- describe: "Perform on a specific environment",
2254
- alias: "e",
2255
- })
2256
- .option("preview", {
2257
- type: "boolean",
2258
- describe: "Interact with a preview namespace",
2259
- });
2260
- },
2261
- async ({ key, ...args }) => {
2262
- await printWranglerBanner();
2263
- const config = readConfig(args.config as ConfigPath, args);
2264
- const namespaceId = getNamespaceId(args, config);
2265
-
2266
- logger.log(
2267
- `Deleting the key "${key}" on namespace ${namespaceId}.`
2268
- );
2269
-
2270
- const accountId = await requireAuth(config);
2271
-
2272
- await fetchResult(
2273
- `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`,
2274
- { method: "DELETE" }
2275
- );
2276
- }
2277
- );
2278
- }
2279
- );
2280
-
2281
- // :bulk
2282
- wrangler.command(
2283
- "kv:bulk",
2284
- "💪 Interact with multiple Workers KV key-value pairs at once",
2285
- (kvBulkYargs) => {
2286
- return kvBulkYargs
2287
- .command(subHelp)
2288
- .command(
2289
- "put <filename>",
2290
- "Upload multiple key-value pairs to a namespace",
2291
- (yargs) => {
2292
- return yargs
2293
- .positional("filename", {
2294
- describe: `The JSON file of key-value pairs to upload, in form [{"key":..., "value":...}"...]`,
2295
- type: "string",
2296
- demandOption: true,
2297
- })
2298
- .option("binding", {
2299
- type: "string",
2300
- requiresArg: true,
2301
- describe: "The name of the namespace to insert values into",
2302
- })
2303
- .option("namespace-id", {
2304
- type: "string",
2305
- requiresArg: true,
2306
- describe: "The id of the namespace to insert values into",
2307
- })
2308
- .check(demandOneOfOption("binding", "namespace-id"))
2309
- .option("env", {
2310
- type: "string",
2311
- requiresArg: true,
2312
- describe: "Perform on a specific environment",
2313
- alias: "e",
2314
- })
2315
- .option("preview", {
2316
- type: "boolean",
2317
- describe: "Interact with a preview namespace",
2318
- });
2319
- },
2320
- async ({ filename, ...args }) => {
2321
- await printWranglerBanner();
2322
- // The simplest implementation I could think of.
2323
- // This could be made more efficient with a streaming parser/uploader
2324
- // but we'll do that in the future if needed.
2325
-
2326
- const config = readConfig(args.config as ConfigPath, args);
2327
- const namespaceId = getNamespaceId(args, config);
2328
- const content = parseJSON(readFileSync(filename), filename);
2329
-
2330
- if (!Array.isArray(content)) {
2331
- throw new Error(
2332
- `Unexpected JSON input from "${filename}".\n` +
2333
- `Expected an array of key-value objects but got type "${typeof content}".`
2334
- );
2335
- }
2336
-
2337
- const errors: string[] = [];
2338
- const warnings: string[] = [];
2339
- for (let i = 0; i < content.length; i++) {
2340
- const keyValue = content[i];
2341
- if (typeof keyValue !== "object") {
2342
- errors.push(
2343
- `The item at index ${i} is type: "${typeof keyValue}" - ${JSON.stringify(
2344
- keyValue
2345
- )}`
2346
- );
2347
- } else if (!isKeyValue(keyValue)) {
2348
- errors.push(
2349
- `The item at index ${i} is ${JSON.stringify(keyValue)}`
2350
- );
2351
- } else {
2352
- const props = unexpectedKeyValueProps(keyValue);
2353
- if (props.length > 0) {
2354
- warnings.push(
2355
- `The item at index ${i} contains unexpected properties: ${JSON.stringify(
2356
- props
2357
- )}.`
2358
- );
2359
- }
2360
- }
2361
- }
2362
- if (warnings.length > 0) {
2363
- logger.warn(
2364
- `Unexpected key-value properties in "${filename}".\n` +
2365
- warnings.join("\n")
2366
- );
2367
- }
2368
- if (errors.length > 0) {
2369
- throw new Error(
2370
- `Unexpected JSON input from "${filename}".\n` +
2371
- `Each item in the array should be an object that matches:\n\n` +
2372
- `interface KeyValue {\n` +
2373
- ` key: string;\n` +
2374
- ` value: string;\n` +
2375
- ` expiration?: number;\n` +
2376
- ` expiration_ttl?: number;\n` +
2377
- ` metadata?: object;\n` +
2378
- ` base64?: boolean;\n` +
2379
- `}\n\n` +
2380
- errors.join("\n")
2381
- );
2382
- }
2383
-
2384
- const accountId = await requireAuth(config);
2385
- await putBulkKeyValue(
2386
- accountId,
2387
- namespaceId,
2388
- content,
2389
- (index, total) => {
2390
- logger.log(`Uploaded ${index} of ${total}.`);
2391
- }
2392
- );
2393
-
2394
- logger.log("Success!");
2395
- }
2396
- )
2397
- .command(
2398
- "delete <filename>",
2399
- "Delete multiple key-value pairs from a namespace",
2400
- (yargs) => {
2401
- return yargs
2402
- .positional("filename", {
2403
- describe: `The JSON file of keys to delete, in the form ["key1", "key2", ...]`,
2404
- type: "string",
2405
- demandOption: true,
2406
- })
2407
- .option("binding", {
2408
- type: "string",
2409
- requiresArg: true,
2410
- describe: "The name of the namespace to delete from",
2411
- })
2412
- .option("namespace-id", {
2413
- type: "string",
2414
- requiresArg: true,
2415
- describe: "The id of the namespace to delete from",
2416
- })
2417
- .check(demandOneOfOption("binding", "namespace-id"))
2418
- .option("env", {
2419
- type: "string",
2420
- requiresArg: true,
2421
- describe: "Perform on a specific environment",
2422
- alias: "e",
2423
- })
2424
- .option("preview", {
2425
- type: "boolean",
2426
- describe: "Interact with a preview namespace",
2427
- })
2428
- .option("force", {
2429
- type: "boolean",
2430
- alias: "f",
2431
- describe: "Do not ask for confirmation before deleting",
2432
- });
2433
- },
2434
- async ({ filename, ...args }) => {
2435
- await printWranglerBanner();
2436
- const config = readConfig(args.config as ConfigPath, args);
2437
- const namespaceId = getNamespaceId(args, config);
2438
-
2439
- if (!args.force) {
2440
- const result = await confirm(
2441
- `Are you sure you want to delete all the keys read from "${filename}" from kv-namespace with id "${namespaceId}"?`
2442
- );
2443
- if (!result) {
2444
- logger.log(`Not deleting keys read from "${filename}".`);
2445
- return;
2446
- }
2447
- }
2448
-
2449
- const content = parseJSON(
2450
- readFileSync(filename),
2451
- filename
2452
- ) as string[];
2453
-
2454
- if (!Array.isArray(content)) {
2455
- throw new Error(
2456
- `Unexpected JSON input from "${filename}".\n` +
2457
- `Expected an array of strings but got:\n${content}`
2458
- );
2459
- }
2460
-
2461
- const errors: string[] = [];
2462
- for (let i = 0; i < content.length; i++) {
2463
- const key = content[i];
2464
- if (typeof key !== "string") {
2465
- errors.push(
2466
- `The item at index ${i} is type: "${typeof key}" - ${JSON.stringify(
2467
- key
2468
- )}`
2469
- );
2470
- }
2471
- }
2472
- if (errors.length > 0) {
2473
- throw new Error(
2474
- `Unexpected JSON input from "${filename}".\n` +
2475
- `Expected an array of strings.\n` +
2476
- errors.join("\n")
2477
- );
2478
- }
2479
-
2480
- const accountId = await requireAuth(config);
2481
-
2482
- await deleteBulkKeyValue(
2483
- accountId,
2484
- namespaceId,
2485
- content,
2486
- (index, total) => {
2487
- logger.log(`Deleted ${index} of ${total}.`);
2488
- }
2489
- );
2490
-
2491
- logger.log("Success!");
2492
- }
2493
- );
2494
- }
2495
- );
2496
-
2497
- wrangler.command(
2498
- "pages",
2499
- "⚡️ Configure Cloudflare Pages",
2500
- async (pagesYargs) => {
2501
- await pages(pagesYargs.command(subHelp).epilogue(pagesBetaWarning));
2502
- }
2503
- );
2504
-
2505
- wrangler.command("r2", "📦 Interact with an R2 store", (r2Yargs) => {
2506
- return r2Yargs
2507
- .command(subHelp)
2508
- .command("bucket", "Manage R2 buckets", (r2BucketYargs) => {
2509
- r2BucketYargs.command(
2510
- "create <name>",
2511
- "Create a new R2 bucket",
2512
- (yargs) => {
2513
- return yargs.positional("name", {
2514
- describe: "The name of the new bucket",
2515
- type: "string",
2516
- demandOption: true,
2517
- });
2518
- },
2519
- async (args) => {
2520
- await printWranglerBanner();
2521
-
2522
- const config = readConfig(args.config as ConfigPath, args);
2523
-
2524
- const accountId = await requireAuth(config);
2525
-
2526
- logger.log(`Creating bucket ${args.name}.`);
2527
- await createR2Bucket(accountId, args.name);
2528
- logger.log(`Created bucket ${args.name}.`);
2529
- }
2530
- );
2531
-
2532
- r2BucketYargs.command("list", "List R2 buckets", {}, async (args) => {
2533
- const config = readConfig(args.config as ConfigPath, args);
2534
-
2535
- const accountId = await requireAuth(config);
2536
-
2537
- logger.log(JSON.stringify(await listR2Buckets(accountId), null, 2));
2538
- });
2539
-
2540
- r2BucketYargs.command(
2541
- "delete <name>",
2542
- "Delete an R2 bucket",
2543
- (yargs) => {
2544
- return yargs.positional("name", {
2545
- describe: "The name of the bucket to delete",
2546
- type: "string",
2547
- demandOption: true,
2548
- });
2549
- },
2550
- async (args) => {
2551
- await printWranglerBanner();
2552
-
2553
- const config = readConfig(args.config as ConfigPath, args);
2554
-
2555
- const accountId = await requireAuth(config);
2556
-
2557
- logger.log(`Deleting bucket ${args.name}.`);
2558
- await deleteR2Bucket(accountId, args.name);
2559
- logger.log(`Deleted bucket ${args.name}.`);
2560
- }
2561
- );
2562
- return r2BucketYargs;
2563
- });
2564
- });
2565
-
2566
- /**
2567
- * User Group: login, logout, and whoami
2568
- * TODO: group commands into User group similar to .group() for flags in yargs
2569
- */
2570
- // login
2571
- wrangler.command(
2572
- // this needs scopes as an option?
2573
- "login",
2574
- "🔓 Login to Cloudflare",
2575
- (yargs) => {
2576
- // TODO: This needs some copy editing
2577
- // I mean, this entire app does, but this too.
2578
- return yargs
2579
- .option("scopes-list", {
2580
- describe: "List all the available OAuth scopes with descriptions",
2581
- })
2582
- .option("scopes", {
2583
- describe: "Pick the set of applicable OAuth scopes when logging in",
2584
- array: true,
2585
- type: "string",
2586
- requiresArg: true,
2587
- });
2588
-
2589
- // TODO: scopes
2590
- },
2591
- async (args) => {
2592
- await printWranglerBanner();
2593
- if (args["scopes-list"]) {
2594
- listScopes();
2595
- return;
2596
- }
2597
- if (args.scopes) {
2598
- if (args.scopes.length === 0) {
2599
- // don't allow no scopes to be passed, that would be weird
2600
- listScopes();
2601
- return;
2602
- }
2603
- if (!validateScopeKeys(args.scopes)) {
2604
- throw new CommandLineArgsError(
2605
- `One of ${args.scopes} is not a valid authentication scope. Run "wrangler login --list-scopes" to see the valid scopes.`
2606
- );
2607
- }
2608
- await login({ scopes: args.scopes });
2609
- return;
2610
- }
2611
- await login();
2612
-
2613
- // TODO: would be nice if it optionally saved login
2614
- // credentials inside node_modules/.cache or something
2615
- // this way you could have multiple users on a single machine
2616
- }
2617
- );
2618
-
2619
- // logout
2620
- wrangler.command(
2621
- // this needs scopes as an option?
2622
- "logout",
2623
- "🚪 Logout from Cloudflare",
2624
- () => {},
2625
- async () => {
2626
- await printWranglerBanner();
2627
- await logout();
2628
- }
2629
- );
2630
-
2631
- // whoami
2632
- wrangler.command(
2633
- "whoami",
2634
- "🕵️ Retrieve your user info and test your auth config",
2635
- () => {},
2636
- async () => {
2637
- await printWranglerBanner();
2638
- await whoami();
2639
- }
2640
- );
2641
-
2642
- wrangler.option("config", {
2643
- alias: "c",
2644
- describe: "Path to .toml configuration file",
2645
- type: "string",
2646
- requiresArg: true,
2647
- });
2648
-
2649
- wrangler.group(["config", "help", "version"], "Flags:");
2650
- wrangler.help().alias("h", "help");
2651
- wrangler.version(wranglerVersion).alias("v", "version");
2652
- wrangler.exitProcess(false);
2653
-
2654
- try {
2655
- await wrangler.parse();
2656
- } catch (e) {
2657
- logger.log(""); // Just adds a bit of space
2658
- if (e instanceof CommandLineArgsError) {
2659
- wrangler.showHelp("error");
2660
- logger.log(""); // Add a bit of space.
2661
- logger.error(e.message);
2662
- } else if (e instanceof ParseError) {
2663
- e.notes.push({
2664
- text: "\nIf you think this is a bug, please open an issue at: https://github.com/cloudflare/wrangler2/issues/new",
2665
- });
2666
- logger.error(formatMessage(e));
2667
- } else {
2668
- logger.error(e instanceof Error ? e.message : e);
2669
- logger.log(
2670
- `${fgGreenColor}%s${resetColor}`,
2671
- "If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
2672
- );
2673
- }
2674
- throw e;
2675
- }
2676
- }
2677
-
2678
- function getDevCompatibilityDate(
2679
- config: Config,
2680
- compatibilityDate = config.compatibility_date
2681
- ) {
2682
- const currentDate = new Date().toISOString().substring(0, 10);
2683
- if (config.configPath !== undefined && compatibilityDate === undefined) {
2684
- logger.warn(
2685
- `No compatibility_date was specified. Using today's date: ${currentDate}.\n` +
2686
- "Add one to your wrangler.toml file:\n" +
2687
- "```\n" +
2688
- `compatibility_date = "${currentDate}"\n` +
2689
- "```\n" +
2690
- "or pass it in your terminal:\n" +
2691
- "```\n" +
2692
- `--compatibility-date=${currentDate}\n` +
2693
- "```\n" +
2694
- "See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
2695
- );
2696
- }
2697
- return compatibilityDate ?? currentDate;
2698
- }