wrangler 0.0.0-e2b7352 → 0.0.0-e305903a

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 (264) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +51 -14
  3. package/bin/wrangler.js +154 -31
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +6244 -21
  6. package/package.json +185 -141
  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 +42 -0
  12. package/src/__tests__/configuration.test.ts +4122 -2810
  13. package/src/__tests__/dev.test.tsx +1341 -527
  14. package/src/__tests__/dialogs.test.tsx +40 -0
  15. package/src/__tests__/generate.test.ts +91 -0
  16. package/src/__tests__/guess-worker-format.test.ts +74 -57
  17. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  18. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  19. package/src/__tests__/helpers/mock-bin.ts +20 -20
  20. package/src/__tests__/helpers/mock-cfetch.ts +202 -93
  21. package/src/__tests__/helpers/mock-console.ts +68 -32
  22. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  23. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  24. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  25. package/src/__tests__/helpers/mock-istty.ts +74 -0
  26. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  27. package/src/__tests__/helpers/mock-kv.ts +26 -26
  28. package/src/__tests__/helpers/mock-oauth-flow.ts +252 -0
  29. package/src/__tests__/helpers/mock-process.ts +39 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  31. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  32. package/src/__tests__/helpers/msw/handlers/index.ts +13 -0
  33. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  34. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  35. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  36. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  37. package/src/__tests__/helpers/msw/index.ts +4 -0
  38. package/src/__tests__/helpers/run-in-tmp.ts +28 -22
  39. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  40. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  41. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  42. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  43. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  44. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  45. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  46. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  47. package/src/__tests__/https-options.test.ts +144 -108
  48. package/src/__tests__/index.test.ts +233 -967
  49. package/src/__tests__/init.test.ts +2717 -0
  50. package/src/__tests__/jest.setup.ts +151 -34
  51. package/src/__tests__/kv.test.ts +1376 -1085
  52. package/src/__tests__/logger.test.ts +141 -0
  53. package/src/__tests__/metrics.test.ts +450 -0
  54. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  55. package/src/__tests__/middleware.test.ts +726 -0
  56. package/src/__tests__/package-manager.test.ts +312 -165
  57. package/src/__tests__/pages.test.ts +1990 -77
  58. package/src/__tests__/parse.test.ts +253 -245
  59. package/src/__tests__/paths.test.ts +39 -0
  60. package/src/__tests__/publish.test.ts +6989 -3411
  61. package/src/__tests__/pubsub.test.ts +367 -0
  62. package/src/__tests__/r2.test.ts +363 -190
  63. package/src/__tests__/route.test.ts +22 -22
  64. package/src/__tests__/secret.test.ts +626 -407
  65. package/src/__tests__/tail.test.ts +653 -516
  66. package/src/__tests__/test-old-node-version.js +31 -0
  67. package/src/__tests__/user.test.ts +155 -0
  68. package/src/__tests__/validate-dev-props.test.ts +56 -0
  69. package/src/__tests__/version.test.ts +35 -0
  70. package/src/__tests__/whoami.test.tsx +261 -88
  71. package/src/__tests__/worker-namespace.test.ts +319 -0
  72. package/src/abort.d.ts +3 -0
  73. package/src/api/dev.ts +206 -0
  74. package/src/api/index.ts +2 -0
  75. package/src/bundle-reporter.tsx +29 -0
  76. package/src/bundle.ts +723 -122
  77. package/src/cfetch/index.ts +83 -66
  78. package/src/cfetch/internal.ts +267 -92
  79. package/src/cli.ts +24 -14
  80. package/src/config/README.md +1 -1
  81. package/src/config/config.ts +236 -179
  82. package/src/config/diagnostics.ts +61 -61
  83. package/src/config/environment.ts +450 -316
  84. package/src/config/index.ts +259 -38
  85. package/src/config/validation-helpers.ts +385 -342
  86. package/src/config/validation.ts +1797 -1099
  87. package/src/config-cache.ts +85 -0
  88. package/src/create-worker-preview.ts +233 -124
  89. package/src/create-worker-upload-form.ts +285 -201
  90. package/src/d1/backups.tsx +212 -0
  91. package/src/d1/create.tsx +54 -0
  92. package/src/d1/delete.tsx +56 -0
  93. package/src/d1/execute.tsx +294 -0
  94. package/src/d1/formatTimeAgo.ts +14 -0
  95. package/src/d1/index.ts +75 -0
  96. package/src/d1/list.tsx +48 -0
  97. package/src/d1/options.ts +12 -0
  98. package/src/d1/types.tsx +14 -0
  99. package/src/d1/utils.ts +39 -0
  100. package/src/dev/dev-vars.ts +36 -0
  101. package/src/dev/dev.tsx +501 -328
  102. package/src/dev/get-local-persistence-path.tsx +31 -0
  103. package/src/dev/local.tsx +629 -211
  104. package/src/dev/remote.tsx +398 -188
  105. package/src/dev/start-server.ts +443 -0
  106. package/src/dev/use-esbuild.ts +175 -82
  107. package/src/dev/validate-dev-props.ts +31 -0
  108. package/src/dev-registry.tsx +190 -0
  109. package/src/dev.tsx +869 -0
  110. package/src/dialogs.tsx +138 -57
  111. package/src/dispatch-namespace.ts +206 -0
  112. package/src/durable.ts +102 -0
  113. package/src/entry.ts +260 -171
  114. package/src/environment-variables.ts +40 -23
  115. package/src/errors.ts +11 -0
  116. package/src/faye-websocket.d.ts +6 -0
  117. package/src/generate.ts +131 -0
  118. package/src/git-client.ts +42 -0
  119. package/src/global-wrangler-config-path.ts +26 -0
  120. package/src/https-options.ts +85 -80
  121. package/src/index.tsx +2295 -2315
  122. package/src/init.ts +967 -0
  123. package/src/inspect.ts +687 -557
  124. package/src/intl-polyfill.d.ts +123 -123
  125. package/src/is-ci.ts +14 -0
  126. package/src/is-interactive.ts +12 -0
  127. package/src/kv.ts +353 -242
  128. package/src/logger.ts +80 -0
  129. package/src/metrics/index.ts +5 -0
  130. package/src/metrics/metrics-config.ts +239 -0
  131. package/src/metrics/metrics-dispatcher.ts +96 -0
  132. package/src/metrics/metrics-usage-headers.ts +24 -0
  133. package/src/metrics/send-event.ts +93 -0
  134. package/src/miniflare-cli/assets.ts +215 -0
  135. package/src/miniflare-cli/index.ts +201 -30
  136. package/src/miniflare-cli/request-context.ts +40 -0
  137. package/src/module-collection.ts +213 -213
  138. package/src/open-in-browser.ts +8 -16
  139. package/src/package-manager.ts +183 -90
  140. package/src/pages/build.tsx +238 -0
  141. package/src/pages/constants.ts +16 -0
  142. package/src/pages/deployments.tsx +106 -0
  143. package/src/pages/dev.tsx +684 -0
  144. package/src/pages/errors.ts +66 -0
  145. package/src/pages/functions/buildPlugin.ts +110 -0
  146. package/src/pages/functions/buildWorker.ts +156 -0
  147. package/src/pages/functions/filepath-routing.test.ts +234 -0
  148. package/src/pages/functions/filepath-routing.ts +189 -0
  149. package/src/pages/functions/identifiers.ts +78 -0
  150. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  151. package/src/pages/functions/routes-consolidation.ts +73 -0
  152. package/src/pages/functions/routes-transformation.test.ts +282 -0
  153. package/src/pages/functions/routes-transformation.ts +115 -0
  154. package/src/pages/functions/routes-validation.test.ts +403 -0
  155. package/src/pages/functions/routes-validation.ts +202 -0
  156. package/src/pages/functions/routes.ts +151 -0
  157. package/src/pages/functions.tsx +82 -0
  158. package/src/pages/hash.tsx +13 -0
  159. package/src/pages/index.tsx +94 -0
  160. package/src/pages/projects.tsx +169 -0
  161. package/src/pages/publish.tsx +419 -0
  162. package/src/pages/types.ts +49 -0
  163. package/src/pages/upload.tsx +398 -0
  164. package/src/pages/utils.ts +12 -0
  165. package/src/parse.ts +224 -121
  166. package/src/paths.ts +53 -8
  167. package/src/preview.ts +31 -0
  168. package/src/proxy.ts +436 -370
  169. package/src/publish.ts +839 -324
  170. package/src/pubsub/index.ts +286 -0
  171. package/src/pubsub/pubsub-commands.tsx +623 -0
  172. package/src/r2.ts +100 -19
  173. package/src/selfsigned.d.ts +23 -23
  174. package/src/sites.tsx +281 -189
  175. package/src/tail/filters.ts +108 -110
  176. package/src/tail/index.ts +234 -218
  177. package/src/tail/printing.ts +92 -47
  178. package/src/update-check.ts +19 -0
  179. package/src/user/choose-account.tsx +69 -0
  180. package/src/user/env-vars.ts +46 -0
  181. package/src/user/generate-auth-url.ts +33 -0
  182. package/src/user/generate-random-state.ts +16 -0
  183. package/src/user/index.ts +3 -0
  184. package/src/user/user.tsx +1192 -0
  185. package/src/whoami.tsx +142 -42
  186. package/src/worker.ts +171 -100
  187. package/src/zones.ts +167 -0
  188. package/templates/checked-fetch.js +17 -0
  189. package/templates/d1-beta-facade.js +174 -0
  190. package/templates/experimental-local-cache-stubs.js +27 -0
  191. package/templates/first-party-worker-module-facade.ts +18 -0
  192. package/templates/format-dev-errors.ts +32 -0
  193. package/templates/gitignore +171 -0
  194. package/templates/init-tests/test-jest-new-worker.js +25 -0
  195. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  196. package/templates/middleware/common.ts +62 -0
  197. package/templates/middleware/loader-modules.ts +84 -0
  198. package/templates/middleware/loader-sw.ts +213 -0
  199. package/templates/middleware/middleware-pretty-error.ts +40 -0
  200. package/templates/middleware/middleware-scheduled.ts +15 -0
  201. package/templates/new-worker-scheduled.js +17 -0
  202. package/templates/new-worker-scheduled.ts +32 -0
  203. package/templates/new-worker.js +3 -3
  204. package/templates/new-worker.ts +18 -3
  205. package/templates/no-op-worker.js +10 -0
  206. package/templates/pages-dev-pipeline.ts +35 -0
  207. package/templates/pages-shim.ts +9 -0
  208. package/templates/pages-template-plugin.ts +167 -0
  209. package/templates/pages-template-worker.ts +172 -0
  210. package/templates/serve-static-assets.ts +63 -0
  211. package/templates/service-bindings-module-facade.js +54 -0
  212. package/templates/service-bindings-sw-facade.js +42 -0
  213. package/templates/tsconfig.json +95 -95
  214. package/wrangler-dist/cli.d.ts +841 -0
  215. package/wrangler-dist/cli.js +129492 -108210
  216. package/miniflare-dist/index.mjs.map +0 -7
  217. package/pages/functions/buildWorker.ts +0 -62
  218. package/pages/functions/filepath-routing.test.ts +0 -223
  219. package/pages/functions/filepath-routing.ts +0 -181
  220. package/pages/functions/identifiers.ts +0 -78
  221. package/pages/functions/routes.ts +0 -151
  222. package/pages/functions/template-worker.ts +0 -130
  223. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  224. package/src/__tests__/logout.test.ts +0 -52
  225. package/src/__tests__/sentry.test.ts +0 -146
  226. package/src/miniflare-cli/enum-keys.ts +0 -17
  227. package/src/pages.tsx +0 -1061
  228. package/src/reporting.ts +0 -131
  229. package/src/user.tsx +0 -1127
  230. package/templates/static-asset-facade.js +0 -47
  231. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  232. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  233. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  234. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  235. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  236. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  237. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  238. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  239. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  240. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  241. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  242. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  243. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  244. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  245. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  246. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  247. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  248. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  249. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  250. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  251. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  252. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  253. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  254. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  255. package/vendor/wrangler-mime/LICENSE +0 -21
  256. package/vendor/wrangler-mime/Mime.js +0 -97
  257. package/vendor/wrangler-mime/README.md +0 -187
  258. package/vendor/wrangler-mime/cli.js +0 -46
  259. package/vendor/wrangler-mime/index.js +0 -4
  260. package/vendor/wrangler-mime/lite.js +0 -4
  261. package/vendor/wrangler-mime/package.json +0 -52
  262. package/vendor/wrangler-mime/types/other.js +0 -1
  263. package/vendor/wrangler-mime/types/standard.js +0 -1
  264. package/wrangler-dist/cli.js.map +0 -7
package/src/dev.tsx ADDED
@@ -0,0 +1,869 @@
1
+ import path from "node:path";
2
+ import { watch } from "chokidar";
3
+ import getPort from "get-port";
4
+ import { render } from "ink";
5
+ import React from "react";
6
+ import { findWranglerToml, printBindings, readConfig } from "./config";
7
+ import Dev from "./dev/dev";
8
+ import { getVarsForDev } from "./dev/dev-vars";
9
+ import { getLocalPersistencePath } from "./dev/get-local-persistence-path";
10
+
11
+ import { startDevServer } from "./dev/start-server";
12
+ import { getEntry } from "./entry";
13
+ import { logger } from "./logger";
14
+ import * as metrics from "./metrics";
15
+ import { getAssetPaths, getSiteAssetPaths } from "./sites";
16
+ import { getAccountFromCache } from "./user";
17
+ import { identifyD1BindingsAsBeta } from "./worker";
18
+ import { getHostFromRoute, getZoneForRoute, getZoneIdFromHost } from "./zones";
19
+ import {
20
+ type ConfigPath,
21
+ DEFAULT_INSPECTOR_PORT,
22
+ DEFAULT_LOCAL_PORT,
23
+ getDevCompatibilityDate,
24
+ getRules,
25
+ getScriptName,
26
+ isLegacyEnv,
27
+ printWranglerBanner,
28
+ } from "./index";
29
+ import type { Config, Environment } from "./config";
30
+ import type { Route } from "./config/environment";
31
+ import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli";
32
+ import type { CfWorkerInit } from "./worker";
33
+ import type { Argv, ArgumentsCamelCase } from "yargs";
34
+
35
+ interface DevArgs {
36
+ config?: string;
37
+ script?: string;
38
+ name?: string;
39
+ bundle?: boolean;
40
+ build?: boolean;
41
+ format?: string;
42
+ env?: string;
43
+ "compatibility-date"?: string;
44
+ "compatibility-flags"?: string[];
45
+ latest?: boolean;
46
+ ip?: string;
47
+ inspect?: boolean;
48
+ port?: number;
49
+ "inspector-port"?: number;
50
+ routes?: string[];
51
+ host?: string;
52
+ "local-protocol"?: "http" | "https";
53
+ "local-upstream"?: string | undefined;
54
+ "experimental-public"?: string;
55
+ public?: string;
56
+ assets?: string;
57
+ site?: string;
58
+ "site-include"?: string[];
59
+ "site-exclude"?: string[];
60
+ "upstream-protocol"?: "http" | "https";
61
+ "jsx-factory"?: string;
62
+ "jsx-fragment"?: string;
63
+ tsconfig?: string;
64
+ local?: boolean;
65
+ "experimental-local"?: boolean;
66
+ minify?: boolean;
67
+ var?: string[];
68
+ define?: string[];
69
+ "node-compat"?: boolean;
70
+ "experimental-enable-local-persistence"?: boolean;
71
+ persist?: boolean;
72
+ "persist-to"?: string;
73
+ "live-reload"?: boolean;
74
+ onReady?: (ip: string, port: number) => void;
75
+ logLevel?: "none" | "info" | "error" | "log" | "warn" | "debug";
76
+ logPrefix?: string;
77
+ showInteractiveDevSession?: boolean;
78
+ "test-scheduled"?: boolean;
79
+ }
80
+
81
+ export function devOptions(yargs: Argv): Argv<DevArgs> {
82
+ return (
83
+ yargs
84
+ .positional("script", {
85
+ describe: "The path to an entry point for your worker",
86
+ type: "string",
87
+ })
88
+ .option("name", {
89
+ describe: "Name of the worker",
90
+ type: "string",
91
+ requiresArg: true,
92
+ })
93
+ // We want to have a --no-bundle flag, but yargs requires that
94
+ // we also have a --bundle flag (that it adds the --no to by itself)
95
+ // So we make a --bundle flag, but hide it, and then add a --no-bundle flag
96
+ // that's visible to the user but doesn't "do" anything.
97
+ .option("bundle", {
98
+ describe: "Run wrangler's compilation step before publishing",
99
+ type: "boolean",
100
+ hidden: true,
101
+ })
102
+ .option("no-bundle", {
103
+ describe: "Skip internal build steps and directly publish script",
104
+ type: "boolean",
105
+ default: false,
106
+ })
107
+ .option("format", {
108
+ choices: ["modules", "service-worker"] as const,
109
+ describe: "Choose an entry type",
110
+ deprecated: true,
111
+ })
112
+ .option("env", {
113
+ describe: "Perform on a specific environment",
114
+ type: "string",
115
+ requiresArg: true,
116
+ alias: "e",
117
+ })
118
+ .option("compatibility-date", {
119
+ describe: "Date to use for compatibility checks",
120
+ type: "string",
121
+ requiresArg: true,
122
+ })
123
+ .option("compatibility-flags", {
124
+ describe: "Flags to use for compatibility checks",
125
+ alias: "compatibility-flag",
126
+ type: "string",
127
+ requiresArg: true,
128
+ array: true,
129
+ })
130
+ .option("latest", {
131
+ describe: "Use the latest version of the worker runtime",
132
+ type: "boolean",
133
+ default: true,
134
+ })
135
+ .option("ip", {
136
+ describe: "IP address to listen on",
137
+ type: "string",
138
+ })
139
+ .option("port", {
140
+ describe: "Port to listen on",
141
+ type: "number",
142
+ })
143
+ .option("inspector-port", {
144
+ describe: "Port for devtools to connect to",
145
+ type: "number",
146
+ })
147
+ .option("routes", {
148
+ describe: "Routes to upload",
149
+ alias: "route",
150
+ type: "string",
151
+ requiresArg: true,
152
+ array: true,
153
+ })
154
+ .option("host", {
155
+ type: "string",
156
+ requiresArg: true,
157
+ describe:
158
+ "Host to forward requests to, defaults to the zone of project",
159
+ })
160
+ .option("local-protocol", {
161
+ describe: "Protocol to listen to requests on, defaults to http.",
162
+ choices: ["http", "https"] as const,
163
+ })
164
+ .options("local-upstream", {
165
+ type: "string",
166
+ describe:
167
+ "Host to act as origin in local mode, defaults to dev.host or route",
168
+ })
169
+ .option("experimental-public", {
170
+ describe: "Static assets to be served",
171
+ type: "string",
172
+ requiresArg: true,
173
+ deprecated: true,
174
+ hidden: true,
175
+ })
176
+ .option("assets", {
177
+ describe: "Static assets to be served",
178
+ type: "string",
179
+ requiresArg: true,
180
+ })
181
+ .option("site", {
182
+ describe: "Root folder of static assets for Workers Sites",
183
+ type: "string",
184
+ requiresArg: true,
185
+ })
186
+ .option("site-include", {
187
+ describe:
188
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
189
+ type: "string",
190
+ requiresArg: true,
191
+ array: true,
192
+ })
193
+ .option("site-exclude", {
194
+ describe:
195
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
196
+ type: "string",
197
+ requiresArg: true,
198
+ array: true,
199
+ })
200
+ .option("upstream-protocol", {
201
+ describe: "Protocol to forward requests to host on, defaults to https.",
202
+ choices: ["http", "https"] as const,
203
+ })
204
+ .option("var", {
205
+ describe:
206
+ "A key-value pair to be injected into the script as a variable",
207
+ type: "string",
208
+ requiresArg: true,
209
+ array: true,
210
+ })
211
+ .option("define", {
212
+ describe: "A key-value pair to be substituted in the script",
213
+ type: "string",
214
+ requiresArg: true,
215
+ array: true,
216
+ })
217
+ .option("jsx-factory", {
218
+ describe: "The function that is called for each JSX element",
219
+ type: "string",
220
+ requiresArg: true,
221
+ })
222
+ .option("jsx-fragment", {
223
+ describe: "The function that is called for each JSX fragment",
224
+ type: "string",
225
+ requiresArg: true,
226
+ })
227
+ .option("tsconfig", {
228
+ describe: "Path to a custom tsconfig.json file",
229
+ type: "string",
230
+ requiresArg: true,
231
+ })
232
+ .option("local", {
233
+ alias: "l",
234
+ describe: "Run on my machine",
235
+ type: "boolean",
236
+ default: false, // I bet this will a point of contention. We'll revisit it.
237
+ })
238
+ .option("experimental-local", {
239
+ describe: "Run on my machine using the Cloudflare Workers runtime",
240
+ type: "boolean",
241
+ default: false,
242
+ })
243
+ .check((argv) => {
244
+ if (argv.local && argv["experimental-local"]) {
245
+ throw new Error(
246
+ "--local and --experimental-local are mutually exclusive. " +
247
+ "Please select one or the other."
248
+ );
249
+ }
250
+ return true;
251
+ })
252
+ .option("minify", {
253
+ describe: "Minify the script",
254
+ type: "boolean",
255
+ })
256
+ .option("node-compat", {
257
+ describe: "Enable node.js compatibility",
258
+ type: "boolean",
259
+ })
260
+ .option("experimental-enable-local-persistence", {
261
+ describe:
262
+ "Enable persistence for local mode (deprecated, use --persist)",
263
+ type: "boolean",
264
+ deprecated: true,
265
+ hidden: true,
266
+ })
267
+ .option("persist", {
268
+ describe:
269
+ "Enable persistence for local mode, using default path: .wrangler/state",
270
+ type: "boolean",
271
+ })
272
+ .option("persist-to", {
273
+ describe:
274
+ "Specify directory to use for local persistence (implies --persist)",
275
+ type: "string",
276
+ requiresArg: true,
277
+ })
278
+ .option("live-reload", {
279
+ // TODO: Add back in once we have remote `--live-reload`
280
+ hidden: true,
281
+ // describe: "Auto reload HTML pages when change is detected",
282
+ type: "boolean",
283
+ })
284
+ .option("inspect", {
285
+ describe: "Enable dev tools",
286
+ type: "boolean",
287
+ deprecated: true,
288
+ })
289
+ .option("legacy-env", {
290
+ type: "boolean",
291
+ describe: "Use legacy environments",
292
+ hidden: true,
293
+ })
294
+ .option("test-scheduled", {
295
+ describe: "Test scheduled events by visiting /__scheduled in browser",
296
+ type: "boolean",
297
+ default: false,
298
+ })
299
+ .option("log-level", {
300
+ choices: ["debug", "info", "log", "warn", "error", "none"] as const,
301
+ describe: "Specify logging level",
302
+ default: "log",
303
+ })
304
+ );
305
+ }
306
+
307
+ export async function devHandler(args: ArgumentsCamelCase<DevArgs>) {
308
+ let watcher;
309
+ try {
310
+ const devInstance = await startDev(args);
311
+ watcher = devInstance.watcher;
312
+ const { waitUntilExit } = devInstance.devReactElement;
313
+ await waitUntilExit();
314
+ } finally {
315
+ await watcher?.close();
316
+ }
317
+ }
318
+
319
+ export type AdditionalDevProps = {
320
+ vars?: {
321
+ [key: string]: unknown;
322
+ };
323
+ kv?: {
324
+ binding: string;
325
+ id: string;
326
+ preview_id?: string;
327
+ }[];
328
+ durableObjects?: {
329
+ name: string;
330
+ class_name: string;
331
+ script_name?: string | undefined;
332
+ environment?: string | undefined;
333
+ }[];
334
+ r2?: {
335
+ binding: string;
336
+ bucket_name: string;
337
+ preview_bucket_name?: string;
338
+ }[];
339
+ d1Databases?: Environment["d1_databases"];
340
+ };
341
+
342
+ type StartDevOptions = ArgumentsCamelCase<DevArgs> &
343
+ // These options can be passed in directly when called with the `wrangler.dev()` API.
344
+ // They aren't exposed as CLI arguments.
345
+ AdditionalDevProps & {
346
+ forceLocal?: boolean;
347
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
348
+ };
349
+
350
+ export async function startDev(args: StartDevOptions) {
351
+ let watcher: ReturnType<typeof watch> | undefined;
352
+ let rerender: (node: React.ReactNode) => void | undefined;
353
+ try {
354
+ if (args.logLevel) {
355
+ logger.loggerLevel = args.logLevel;
356
+ }
357
+ await printWranglerBanner();
358
+
359
+ const configPath =
360
+ (args.config as ConfigPath) ||
361
+ ((args.script &&
362
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
363
+ let config = readConfig(configPath, args);
364
+
365
+ if (config.configPath) {
366
+ watcher = watch(config.configPath, {
367
+ persistent: true,
368
+ }).on("change", async (_event) => {
369
+ // TODO: Do we need to handle different `_event` types differently?
370
+ // e.g. what if the file is deleted, or added?
371
+ config = readConfig(configPath, args);
372
+ if (config.configPath) {
373
+ logger.log(`${path.basename(config.configPath)} changed...`);
374
+ rerender(await getDevReactElement(config));
375
+ }
376
+ });
377
+ }
378
+
379
+ const {
380
+ entry,
381
+ nodeCompat,
382
+ upstreamProtocol,
383
+ zoneId,
384
+ host,
385
+ routes,
386
+ getLocalPort,
387
+ getInspectorPort,
388
+ cliDefines,
389
+ localPersistencePath,
390
+ } = await validateDevServerSettings(args, config);
391
+
392
+ await metrics.sendMetricsEvent(
393
+ "run dev",
394
+ {
395
+ local: args.local,
396
+ usesTypeScript: /\.tsx?$/.test(entry.file),
397
+ },
398
+ { sendMetrics: config.send_metrics, offline: args.local }
399
+ );
400
+
401
+ // eslint-disable-next-line no-inner-declarations
402
+ async function getDevReactElement(configParam: Config) {
403
+ const { assetPaths, bindings } = await getBindingsAndAssetPaths(
404
+ args,
405
+ configParam
406
+ );
407
+
408
+ return (
409
+ <Dev
410
+ name={getScriptName({ name: args.name, env: args.env }, configParam)}
411
+ noBundle={!(args.bundle ?? !configParam.no_bundle)}
412
+ entry={entry}
413
+ env={args.env}
414
+ zone={zoneId}
415
+ host={host}
416
+ routes={routes}
417
+ rules={getRules(configParam)}
418
+ legacyEnv={isLegacyEnv(configParam)}
419
+ minify={args.minify ?? configParam.minify}
420
+ nodeCompat={nodeCompat}
421
+ build={configParam.build || {}}
422
+ define={{ ...configParam.define, ...cliDefines }}
423
+ initialMode={
424
+ args.local || args.experimentalLocal ? "local" : "remote"
425
+ }
426
+ jsxFactory={args["jsx-factory"] || configParam.jsx_factory}
427
+ jsxFragment={args["jsx-fragment"] || configParam.jsx_fragment}
428
+ tsconfig={args.tsconfig ?? configParam.tsconfig}
429
+ upstreamProtocol={upstreamProtocol}
430
+ localProtocol={args.localProtocol || configParam.dev.local_protocol}
431
+ localUpstream={args["local-upstream"] || host}
432
+ localPersistencePath={localPersistencePath}
433
+ liveReload={args.liveReload || false}
434
+ accountId={configParam.account_id || getAccountFromCache()?.id}
435
+ assetPaths={assetPaths}
436
+ assetsConfig={configParam.assets}
437
+ port={args.port || configParam.dev.port || (await getLocalPort())}
438
+ ip={args.ip || configParam.dev.ip}
439
+ inspectorPort={
440
+ args.inspectorPort ||
441
+ configParam.dev.inspector_port ||
442
+ (await getInspectorPort())
443
+ }
444
+ isWorkersSite={Boolean(args.site || configParam.site)}
445
+ compatibilityDate={getDevCompatibilityDate(
446
+ configParam,
447
+ args.compatibilityDate
448
+ )}
449
+ compatibilityFlags={
450
+ args.compatibilityFlags || configParam.compatibility_flags
451
+ }
452
+ usageModel={configParam.usage_model}
453
+ bindings={bindings}
454
+ crons={configParam.triggers.crons}
455
+ logPrefix={args.logPrefix}
456
+ onReady={args.onReady}
457
+ inspect={args.inspect ?? true}
458
+ showInteractiveDevSession={args.showInteractiveDevSession}
459
+ forceLocal={args.forceLocal}
460
+ enablePagesAssetsServiceBinding={args.enablePagesAssetsServiceBinding}
461
+ firstPartyWorker={configParam.first_party_worker}
462
+ sendMetrics={configParam.send_metrics}
463
+ testScheduled={args["test-scheduled"]}
464
+ experimentalLocal={args.experimentalLocal}
465
+ />
466
+ );
467
+ }
468
+ const devReactElement = render(await getDevReactElement(config));
469
+ rerender = devReactElement.rerender;
470
+ return {
471
+ devReactElement,
472
+ watcher,
473
+ stop: async () => {
474
+ devReactElement.unmount();
475
+ await watcher?.close();
476
+ },
477
+ };
478
+ } finally {
479
+ await watcher?.close();
480
+ }
481
+ }
482
+
483
+ export async function startApiDev(args: StartDevOptions) {
484
+ if (args.logLevel) {
485
+ logger.loggerLevel = args.logLevel;
486
+ }
487
+ await printWranglerBanner();
488
+
489
+ const configPath =
490
+ (args.config as ConfigPath) ||
491
+ ((args.script &&
492
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
493
+ const config = readConfig(configPath, args);
494
+
495
+ const {
496
+ entry,
497
+ nodeCompat,
498
+ upstreamProtocol,
499
+ zoneId,
500
+ host,
501
+ routes,
502
+ getLocalPort,
503
+ getInspectorPort,
504
+ cliDefines,
505
+ localPersistencePath,
506
+ } = await validateDevServerSettings(args, config);
507
+
508
+ await metrics.sendMetricsEvent(
509
+ "run dev (api)",
510
+ { local: args.local },
511
+ { sendMetrics: config.send_metrics, offline: args.local }
512
+ );
513
+
514
+ // eslint-disable-next-line no-inner-declarations
515
+ async function getDevServer(configParam: Config) {
516
+ const { assetPaths, bindings } = await getBindingsAndAssetPaths(
517
+ args,
518
+ configParam
519
+ );
520
+
521
+ //if args.bundle is on, don't disable bundling
522
+ //if there's no args.bundle, and configParam.no_bundle is on, disable bundling
523
+ //otherwise, enable bundling
524
+ const enableBundling = args.bundle ?? !configParam.no_bundle;
525
+ return await startDevServer({
526
+ name: getScriptName({ name: args.name, env: args.env }, configParam),
527
+ noBundle: !enableBundling,
528
+ entry: entry,
529
+ env: args.env,
530
+ zone: zoneId,
531
+ host: host,
532
+ routes: routes,
533
+ rules: getRules(configParam),
534
+ legacyEnv: isLegacyEnv(configParam),
535
+ minify: args.minify ?? configParam.minify,
536
+ nodeCompat: nodeCompat,
537
+ build: configParam.build || {},
538
+ define: { ...config.define, ...cliDefines },
539
+ initialMode: args.local ? "local" : "remote",
540
+ jsxFactory: args["jsx-factory"] || configParam.jsx_factory,
541
+ jsxFragment: args["jsx-fragment"] || configParam.jsx_fragment,
542
+ tsconfig: args.tsconfig ?? configParam.tsconfig,
543
+ upstreamProtocol: upstreamProtocol,
544
+ localProtocol: args.localProtocol || configParam.dev.local_protocol,
545
+ localUpstream: args["local-upstream"] || host,
546
+ localPersistencePath,
547
+ liveReload: args.liveReload || false,
548
+ accountId: configParam.account_id || getAccountFromCache()?.id,
549
+ assetPaths: assetPaths,
550
+ assetsConfig: configParam.assets,
551
+ //port can be 0, which means to use a random port
552
+ port:
553
+ args.port === 0
554
+ ? args.port
555
+ : args.port || configParam.dev.port || (await getLocalPort()),
556
+ ip: args.ip || configParam.dev.ip,
557
+ inspectorPort:
558
+ args["inspector-port"] ||
559
+ configParam.dev.inspector_port ||
560
+ (await getInspectorPort()),
561
+ isWorkersSite: Boolean(args.site || configParam.site),
562
+ compatibilityDate: getDevCompatibilityDate(
563
+ config,
564
+ args["compatibility-date"]
565
+ ),
566
+ compatibilityFlags:
567
+ args["compatibility-flags"] || configParam.compatibility_flags,
568
+ usageModel: configParam.usage_model,
569
+ bindings: bindings,
570
+ crons: configParam.triggers.crons,
571
+ logPrefix: args.logPrefix,
572
+ onReady: args.onReady,
573
+ inspect: args.inspect ?? true,
574
+ showInteractiveDevSession: args.showInteractiveDevSession,
575
+ forceLocal: args.forceLocal,
576
+ enablePagesAssetsServiceBinding: args.enablePagesAssetsServiceBinding,
577
+ local: true,
578
+ firstPartyWorker: configParam.first_party_worker,
579
+ sendMetrics: configParam.send_metrics,
580
+ testScheduled: args.testScheduled,
581
+ experimentalLocal: undefined,
582
+ });
583
+ }
584
+
585
+ const devServer = await getDevServer(config);
586
+ if (!devServer) {
587
+ throw logger.error("Failed to start dev server.");
588
+ }
589
+
590
+ return {
591
+ stop: async () => {
592
+ await devServer.stop();
593
+ },
594
+ };
595
+ }
596
+ /**
597
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
598
+ */
599
+ function memoizeGetPort(defaultPort: number) {
600
+ let portValue: number;
601
+ return async () => {
602
+ return portValue || (portValue = await getPort({ port: defaultPort }));
603
+ };
604
+ }
605
+ /**
606
+ * mask anything that was overridden in .dev.vars
607
+ * so that we don't log potential secrets into the terminal
608
+ */
609
+ function maskVars(bindings: CfWorkerInit["bindings"], configParam: Config) {
610
+ const maskedVars = { ...bindings.vars };
611
+ for (const key of Object.keys(maskedVars)) {
612
+ if (maskedVars[key] !== configParam.vars[key]) {
613
+ // This means it was overridden in .dev.vars
614
+ // so let's mask it
615
+ maskedVars[key] = "(hidden)";
616
+ }
617
+ }
618
+ return maskedVars;
619
+ }
620
+
621
+ async function getZoneIdHostAndRoutes(args: StartDevOptions, config: Config) {
622
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
623
+ // Compute zone info from the `host` and `route` args and config;
624
+ let host = args.host || config.dev.host;
625
+ let zoneId: string | undefined;
626
+ const routes: Route[] | undefined =
627
+ args.routes || (config.route && [config.route]) || config.routes;
628
+
629
+ if (args.forceLocal) {
630
+ args.local = true;
631
+ }
632
+
633
+ if (!args.local) {
634
+ if (host) {
635
+ zoneId = await getZoneIdFromHost(host);
636
+ }
637
+ if (!zoneId && routes) {
638
+ const firstRoute = routes[0];
639
+ const zone = await getZoneForRoute(firstRoute);
640
+ if (zone) {
641
+ zoneId = zone.id;
642
+ host = zone.host;
643
+ }
644
+ }
645
+ } else if (!host) {
646
+ if (routes) {
647
+ const firstRoute = routes[0];
648
+ host = getHostFromRoute(firstRoute);
649
+ }
650
+ }
651
+ return { host, routes, zoneId };
652
+ }
653
+
654
+ async function validateDevServerSettings(
655
+ args: StartDevOptions,
656
+ config: Config
657
+ ) {
658
+ const entry = await getEntry(
659
+ { assets: args.assets, script: args.script },
660
+ config,
661
+ "dev"
662
+ );
663
+
664
+ const { zoneId, host, routes } = await getZoneIdHostAndRoutes(args, config);
665
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
666
+ const getInspectorPort = memoizeGetPort(DEFAULT_INSPECTOR_PORT);
667
+
668
+ if (config.services && config.services.length > 0) {
669
+ logger.warn(
670
+ `This worker is bound to live services: ${config.services
671
+ .map(
672
+ (service) =>
673
+ `${service.binding} (${service.service}${
674
+ service.environment ? `@${service.environment}` : ""
675
+ })`
676
+ )
677
+ .join(", ")}`
678
+ );
679
+ }
680
+
681
+ if (args.inspect) {
682
+ //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
683
+ logger.warn(
684
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
685
+ );
686
+ }
687
+
688
+ if (args["experimental-public"]) {
689
+ throw new Error(
690
+ "The --experimental-public field has been renamed to --assets"
691
+ );
692
+ }
693
+
694
+ if (args.public) {
695
+ throw new Error("The --public field has been renamed to --assets");
696
+ }
697
+
698
+ if ((args.assets || config.assets) && (args.site || config.site)) {
699
+ throw new Error("Cannot use Assets and Workers Sites in the same Worker.");
700
+ }
701
+
702
+ if (args.assets) {
703
+ logger.warn(
704
+ "The --assets argument is experimental and may change or break at any time"
705
+ );
706
+ }
707
+ const upstreamProtocol =
708
+ args["upstream-protocol"] || config.dev.upstream_protocol;
709
+ if (upstreamProtocol === "http") {
710
+ logger.warn(
711
+ "Setting upstream-protocol to http is not currently implemented.\n" +
712
+ "If this is required in your project, please add your use case to the following issue:\n" +
713
+ "https://github.com/cloudflare/wrangler2/issues/583."
714
+ );
715
+ }
716
+ const nodeCompat = args.nodeCompat ?? config.node_compat;
717
+ if (nodeCompat) {
718
+ logger.warn(
719
+ "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."
720
+ );
721
+ }
722
+
723
+ if (args.experimentalEnableLocalPersistence) {
724
+ logger.warn(
725
+ `--experimental-enable-local-persistence is deprecated.\n` +
726
+ `Move any existing data to .wrangler/state and use --persist, or\n` +
727
+ `use --persist-to=./wrangler-local-state to keep using the old path.`
728
+ );
729
+ }
730
+
731
+ const localPersistencePath = getLocalPersistencePath(
732
+ args.persistTo,
733
+ Boolean(args.persist),
734
+ config.configPath
735
+ );
736
+
737
+ const cliDefines =
738
+ args.define?.reduce<Record<string, string>>((collectDefines, d) => {
739
+ const [key, ...value] = d.split(":");
740
+ collectDefines[key] = value.join("");
741
+ return collectDefines;
742
+ }, {}) || {};
743
+
744
+ return {
745
+ entry,
746
+ upstreamProtocol,
747
+ nodeCompat,
748
+ getLocalPort,
749
+ getInspectorPort,
750
+ zoneId,
751
+ host,
752
+ routes,
753
+ cliDefines,
754
+ localPersistencePath,
755
+ };
756
+ }
757
+
758
+ async function getBindingsAndAssetPaths(
759
+ args: StartDevOptions,
760
+ configParam: Config
761
+ ) {
762
+ const cliVars =
763
+ args.var?.reduce<Record<string, string>>((collectVars, v) => {
764
+ const [key, ...value] = v.split(":");
765
+ collectVars[key] = value.join("");
766
+ return collectVars;
767
+ }, {}) || {};
768
+
769
+ // now log all available bindings into the terminal
770
+ const bindings = await getBindings(configParam, {
771
+ kv: args.kv,
772
+ vars: { ...args.vars, ...cliVars },
773
+ durableObjects: args.durableObjects,
774
+ r2: args.r2,
775
+ d1Databases: args.d1Databases,
776
+ });
777
+
778
+ const maskedVars = maskVars(bindings, configParam);
779
+
780
+ printBindings({
781
+ ...bindings,
782
+ vars: maskedVars,
783
+ });
784
+
785
+ const assetPaths =
786
+ args.assets || configParam.assets
787
+ ? getAssetPaths(configParam, args.assets)
788
+ : getSiteAssetPaths(
789
+ configParam,
790
+ args.site,
791
+ args.siteInclude,
792
+ args.siteExclude
793
+ );
794
+ return { assetPaths, bindings };
795
+ }
796
+
797
+ async function getBindings(
798
+ configParam: Config,
799
+ args: AdditionalDevProps
800
+ ): Promise<CfWorkerInit["bindings"]> {
801
+ const bindings = {
802
+ kv_namespaces: [
803
+ ...(configParam.kv_namespaces || []).map(
804
+ ({ binding, preview_id, id: _id }) => {
805
+ // In `dev`, we make folks use a separate kv namespace called
806
+ // `preview_id` instead of `id` so that they don't
807
+ // break production data. So here we check that a `preview_id`
808
+ // has actually been configured.
809
+ // This whole block of code will be obsoleted in the future
810
+ // when we have copy-on-write for previews on edge workers.
811
+ if (!preview_id) {
812
+ // TODO: This error has to be a _lot_ better, ideally just asking
813
+ // to create a preview namespace for the user automatically
814
+ throw new Error(
815
+ `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`
816
+ ); // Ugh, I really don't like this message very much
817
+ }
818
+ return {
819
+ binding,
820
+ id: preview_id,
821
+ };
822
+ }
823
+ ),
824
+ ...(args.kv || []),
825
+ ],
826
+ // Use a copy of combinedVars since we're modifying it later
827
+ vars: {
828
+ ...getVarsForDev(configParam),
829
+ ...args.vars,
830
+ },
831
+ wasm_modules: configParam.wasm_modules,
832
+ text_blobs: configParam.text_blobs,
833
+ data_blobs: configParam.data_blobs,
834
+ durable_objects: {
835
+ bindings: [
836
+ ...(configParam.durable_objects || { bindings: [] }).bindings,
837
+ ...(args.durableObjects || []),
838
+ ],
839
+ },
840
+ r2_buckets: [
841
+ ...(configParam.r2_buckets?.map(
842
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
843
+ // same idea as kv namespace preview id,
844
+ // same copy-on-write TODO
845
+ if (!preview_bucket_name) {
846
+ throw new Error(
847
+ `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`
848
+ );
849
+ }
850
+ return {
851
+ binding,
852
+ bucket_name: preview_bucket_name,
853
+ };
854
+ }
855
+ ) || []),
856
+ ...(args.r2 || []),
857
+ ],
858
+ dispatch_namespaces: configParam.dispatch_namespaces,
859
+ services: configParam.services,
860
+ unsafe: configParam.unsafe?.bindings,
861
+ logfwdr: configParam.logfwdr,
862
+ d1_databases: identifyD1BindingsAsBeta([
863
+ ...configParam.d1_databases,
864
+ ...(args.d1Databases || []),
865
+ ]),
866
+ };
867
+
868
+ return bindings;
869
+ }