wrangler 0.0.0-e88a54e → 0.0.0-e8e684c7

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