wrangler 0.0.0-e6733a3 → 0.0.0-e9307365

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