wrangler 0.0.0-e3ce82b → 0.0.0-e4047cab

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