wrangler 0.0.0-e322475 → 0.0.0-e33294b0

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