wrangler 0.0.0-ecc8b172 → 0.0.0-ecded1af1

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