wrangler 0.0.0-e043479 → 0.0.0-e0621809

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 (365) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -14
  3. package/bin/wrangler.js +181 -29
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +6368 -0
  6. package/package.json +198 -136
  7. package/src/__tests__/access.test.ts +25 -0
  8. package/src/__tests__/api-dev.test.ts +238 -0
  9. package/src/__tests__/api-devregistry.test.js +64 -0
  10. package/src/__tests__/api.test.ts +80 -0
  11. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  12. package/src/__tests__/config-cache.test.ts +42 -0
  13. package/src/__tests__/configuration.test.ts +4456 -2178
  14. package/src/__tests__/d1/d1.test.ts +82 -0
  15. package/src/__tests__/d1/execute.test.ts +66 -0
  16. package/src/__tests__/d1/migrate.test.ts +157 -0
  17. package/src/__tests__/d1/splitter.test.ts +255 -0
  18. package/src/__tests__/delete.test.ts +272 -0
  19. package/src/__tests__/deployments.test.ts +369 -0
  20. package/src/__tests__/dev.test.tsx +1605 -235
  21. package/src/__tests__/generate.test.ts +238 -0
  22. package/src/__tests__/get-host-from-url.test.ts +16 -0
  23. package/src/__tests__/guess-worker-format.test.ts +111 -57
  24. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  25. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  26. package/src/__tests__/helpers/mock-account-id.ts +26 -22
  27. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  28. package/src/__tests__/helpers/mock-bin.ts +20 -20
  29. package/src/__tests__/helpers/mock-console.ts +74 -32
  30. package/src/__tests__/helpers/mock-dialogs.ts +107 -33
  31. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  32. package/src/__tests__/helpers/mock-get-zone-from-host.ts +11 -0
  33. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  34. package/src/__tests__/helpers/mock-istty.ts +74 -0
  35. package/src/__tests__/helpers/mock-known-routes.ts +12 -0
  36. package/src/__tests__/helpers/mock-kv.ts +42 -36
  37. package/src/__tests__/helpers/mock-oauth-flow.ts +263 -0
  38. package/src/__tests__/helpers/mock-process.ts +34 -0
  39. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  40. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  41. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  42. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  43. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  44. package/src/__tests__/helpers/msw/handlers/deployments.ts +160 -0
  45. package/src/__tests__/helpers/msw/handlers/namespaces.ts +81 -0
  46. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  47. package/src/__tests__/helpers/msw/handlers/r2.ts +60 -0
  48. package/src/__tests__/helpers/msw/handlers/script.ts +56 -0
  49. package/src/__tests__/helpers/msw/handlers/user.ts +52 -0
  50. package/src/__tests__/helpers/msw/handlers/zones.ts +20 -0
  51. package/src/__tests__/helpers/msw/index.ts +52 -0
  52. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  53. package/src/__tests__/helpers/run-in-tmp.ts +29 -20
  54. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  55. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  56. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  57. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  58. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  59. package/src/__tests__/helpers/worker-scripts/parent-worker.js +11 -0
  60. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  61. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  62. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  63. package/src/__tests__/https-options.test.ts +163 -0
  64. package/src/__tests__/index.test.ts +264 -850
  65. package/src/__tests__/init.test.ts +3196 -0
  66. package/src/__tests__/jest.setup.ts +158 -48
  67. package/src/__tests__/kv.test.ts +1789 -1398
  68. package/src/__tests__/logger.test.ts +141 -0
  69. package/src/__tests__/logout.test.ts +41 -44
  70. package/src/__tests__/metrics.test.ts +493 -0
  71. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  72. package/src/__tests__/middleware.test.ts +816 -0
  73. package/src/__tests__/mtls-certificates.test.ts +588 -0
  74. package/src/__tests__/package-manager.test.ts +312 -165
  75. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  76. package/src/__tests__/pages/functions-build.test.ts +452 -0
  77. package/src/__tests__/pages/pages.test.ts +81 -0
  78. package/src/__tests__/pages/project-create.test.ts +63 -0
  79. package/src/__tests__/pages/project-list.test.ts +110 -0
  80. package/src/__tests__/pages/project-upload.test.ts +500 -0
  81. package/src/__tests__/pages/publish.test.ts +2820 -0
  82. package/src/__tests__/pages-deployment-tail.test.ts +955 -0
  83. package/src/__tests__/parse.test.ts +359 -245
  84. package/src/__tests__/paths.test.ts +39 -0
  85. package/src/__tests__/publish.test.ts +8373 -2089
  86. package/src/__tests__/pubsub.test.ts +496 -0
  87. package/src/__tests__/queues.test.ts +532 -0
  88. package/src/__tests__/r2.test.ts +369 -193
  89. package/src/__tests__/route.test.ts +45 -0
  90. package/src/__tests__/secret.test.ts +683 -415
  91. package/src/__tests__/tail.test.ts +838 -444
  92. package/src/__tests__/test-old-node-version.js +31 -0
  93. package/src/__tests__/tsconfig-sanity.ts +12 -0
  94. package/src/__tests__/tsconfig.json +8 -0
  95. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  96. package/src/__tests__/type-generation.test.ts +234 -0
  97. package/src/__tests__/user.test.ts +118 -0
  98. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  99. package/src/__tests__/validate-dev-props.test.ts +56 -0
  100. package/src/__tests__/version.test.ts +35 -0
  101. package/src/__tests__/whoami.test.tsx +167 -81
  102. package/src/__tests__/worker-namespace.test.ts +340 -0
  103. package/src/abort.d.ts +3 -0
  104. package/src/api/dev.ts +327 -0
  105. package/src/api/index.ts +11 -0
  106. package/src/api/mtls-certificate.ts +148 -0
  107. package/src/api/pages/create-worker-bundle-contents.ts +75 -0
  108. package/src/api/pages/index.ts +5 -0
  109. package/src/api/pages/publish.tsx +355 -0
  110. package/src/bundle-reporter.ts +68 -0
  111. package/src/bundle.ts +874 -103
  112. package/src/cfetch/index.ts +123 -69
  113. package/src/cfetch/internal.ts +217 -92
  114. package/src/cli.ts +23 -14
  115. package/src/config/README.md +7 -7
  116. package/src/config/config.ts +236 -224
  117. package/src/config/diagnostics.ts +61 -61
  118. package/src/config/environment.ts +545 -256
  119. package/src/config/index.ts +367 -34
  120. package/src/config/validation-helpers.ts +449 -222
  121. package/src/config/validation.ts +2142 -907
  122. package/src/config-cache.ts +85 -0
  123. package/src/create-worker-preview.ts +293 -0
  124. package/src/create-worker-upload-form.ts +342 -0
  125. package/src/d1/backups.tsx +219 -0
  126. package/src/d1/constants.ts +2 -0
  127. package/src/d1/create.tsx +68 -0
  128. package/src/d1/delete.ts +53 -0
  129. package/src/d1/execute.tsx +357 -0
  130. package/src/d1/formatTimeAgo.ts +14 -0
  131. package/src/d1/index.ts +100 -0
  132. package/src/d1/list.tsx +60 -0
  133. package/src/d1/migrations/apply.tsx +212 -0
  134. package/src/d1/migrations/create.tsx +79 -0
  135. package/src/d1/migrations/helpers.ts +172 -0
  136. package/src/d1/migrations/index.ts +3 -0
  137. package/src/d1/migrations/list.tsx +95 -0
  138. package/src/d1/migrations/options.ts +23 -0
  139. package/src/d1/options.ts +22 -0
  140. package/src/d1/splitter.ts +161 -0
  141. package/src/d1/types.ts +25 -0
  142. package/src/d1/utils.ts +49 -0
  143. package/src/delete.ts +100 -0
  144. package/src/deployments.ts +368 -0
  145. package/src/deprecated/index.ts +144 -0
  146. package/src/dev/dev-vars.ts +39 -0
  147. package/src/dev/dev.tsx +600 -0
  148. package/src/dev/get-local-persistence-path.ts +31 -0
  149. package/src/dev/local.tsx +920 -0
  150. package/src/dev/remote.tsx +632 -0
  151. package/src/dev/start-server.ts +540 -0
  152. package/src/dev/use-esbuild.ts +209 -0
  153. package/src/dev/validate-dev-props.ts +40 -0
  154. package/src/dev-registry.ts +201 -0
  155. package/src/dev.tsx +907 -939
  156. package/src/dialogs.ts +136 -0
  157. package/src/dispatch-namespace.ts +211 -0
  158. package/src/docs/index.ts +97 -0
  159. package/src/durable.ts +102 -0
  160. package/src/entry.ts +307 -37
  161. package/src/environment-variables/factory.ts +88 -0
  162. package/src/environment-variables/misc-variables.ts +30 -0
  163. package/src/errors.ts +11 -0
  164. package/src/generate/index.ts +298 -0
  165. package/src/git-client.ts +135 -0
  166. package/src/global-wrangler-config-path.ts +26 -0
  167. package/src/https-options.ts +127 -0
  168. package/src/index.ts +758 -0
  169. package/src/init.ts +1032 -0
  170. package/src/inspect.ts +723 -550
  171. package/src/intl-polyfill.d.ts +139 -0
  172. package/src/is-ci.ts +14 -0
  173. package/src/is-interactive.ts +16 -0
  174. package/src/jest.d.ts +4 -0
  175. package/src/kv/helpers.ts +430 -0
  176. package/src/kv/index.ts +594 -0
  177. package/src/logger.ts +104 -0
  178. package/src/metrics/index.ts +5 -0
  179. package/src/metrics/metrics-config.ts +239 -0
  180. package/src/metrics/metrics-dispatcher.ts +96 -0
  181. package/src/metrics/metrics-usage-headers.ts +24 -0
  182. package/src/metrics/send-event.ts +99 -0
  183. package/src/miniflare-cli/README.md +30 -0
  184. package/src/miniflare-cli/assets.ts +251 -0
  185. package/src/miniflare-cli/index.ts +210 -0
  186. package/src/miniflare-cli/request-context.ts +40 -0
  187. package/src/miniflare-cli/tsconfig.json +9 -0
  188. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  189. package/src/miniflare-cli/types.ts +11 -0
  190. package/src/module-collection.ts +243 -146
  191. package/src/mtls-certificate/cli.ts +155 -0
  192. package/src/open-in-browser.ts +10 -6
  193. package/src/package-manager.ts +183 -90
  194. package/src/pages/build.ts +410 -0
  195. package/src/pages/buildFunctions.ts +140 -0
  196. package/src/pages/constants.ts +18 -0
  197. package/src/pages/deployment-tails.ts +281 -0
  198. package/src/pages/deployments.tsx +84 -0
  199. package/src/pages/dev.ts +716 -0
  200. package/src/pages/errors.ts +67 -0
  201. package/src/pages/functions/buildPlugin.ts +112 -0
  202. package/src/pages/functions/buildWorker.ts +297 -0
  203. package/src/pages/functions/filepath-routing.test.ts +234 -0
  204. package/src/pages/functions/filepath-routing.ts +189 -0
  205. package/src/pages/functions/identifiers.ts +78 -0
  206. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  207. package/src/pages/functions/routes-consolidation.ts +73 -0
  208. package/src/pages/functions/routes-transformation.test.ts +282 -0
  209. package/src/pages/functions/routes-transformation.ts +115 -0
  210. package/src/pages/functions/routes-validation.test.ts +403 -0
  211. package/src/pages/functions/routes-validation.ts +202 -0
  212. package/src/pages/functions/routes.ts +151 -0
  213. package/src/pages/functions/tsconfig.json +8 -0
  214. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  215. package/src/pages/functions.ts +86 -0
  216. package/src/pages/hash.ts +13 -0
  217. package/src/pages/index.ts +102 -0
  218. package/src/pages/projects.tsx +159 -0
  219. package/src/pages/prompt-select-project.tsx +31 -0
  220. package/src/pages/publish.tsx +267 -0
  221. package/src/pages/types.ts +46 -0
  222. package/src/pages/upload.tsx +469 -0
  223. package/src/pages/utils.ts +23 -0
  224. package/src/parse.ts +247 -122
  225. package/src/paths.ts +53 -8
  226. package/src/proxy.ts +636 -318
  227. package/src/publish/index.ts +274 -0
  228. package/src/publish/publish.ts +1065 -0
  229. package/src/pubsub/index.ts +286 -0
  230. package/src/pubsub/pubsub-commands.ts +623 -0
  231. package/src/queues/cli/commands/consumer/add.ts +71 -0
  232. package/src/queues/cli/commands/consumer/index.ts +19 -0
  233. package/src/queues/cli/commands/consumer/remove.ts +31 -0
  234. package/src/queues/cli/commands/create.ts +25 -0
  235. package/src/queues/cli/commands/delete.ts +26 -0
  236. package/src/queues/cli/commands/index.ts +35 -0
  237. package/src/queues/cli/commands/list.ts +25 -0
  238. package/src/queues/client.ts +136 -0
  239. package/src/queues/utils.ts +18 -0
  240. package/src/r2/constants.ts +4 -0
  241. package/src/r2/helpers.ts +132 -0
  242. package/src/r2/index.ts +289 -0
  243. package/src/routes.ts +140 -0
  244. package/src/secret/index.ts +375 -0
  245. package/src/selfsigned.d.ts +29 -0
  246. package/src/sites.ts +372 -0
  247. package/src/tail/createTail.ts +406 -0
  248. package/src/tail/filters.ts +109 -111
  249. package/src/tail/index.ts +208 -296
  250. package/src/tail/printing.ts +107 -47
  251. package/src/tsconfig-sanity.ts +16 -0
  252. package/src/type-generation.ts +181 -0
  253. package/src/update-check.ts +19 -0
  254. package/src/user/access.ts +68 -0
  255. package/src/user/auth-variables.ts +113 -0
  256. package/src/user/choose-account.tsx +39 -0
  257. package/src/user/generate-auth-url.ts +33 -0
  258. package/src/user/generate-random-state.ts +16 -0
  259. package/src/user/index.ts +2 -0
  260. package/src/user/user.ts +1233 -0
  261. package/src/utils/collectKeyValues.ts +14 -0
  262. package/src/utils/render.ts +93 -0
  263. package/src/whoami.ts +135 -0
  264. package/src/worker.ts +264 -0
  265. package/src/yargs-types.ts +37 -0
  266. package/src/zones.ts +191 -0
  267. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  268. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  269. package/templates/__tests__/tsconfig.json +8 -0
  270. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  271. package/templates/checked-fetch.js +23 -0
  272. package/templates/d1-beta-facade.js +244 -0
  273. package/templates/facade.d.ts +14 -0
  274. package/templates/first-party-worker-module-facade.ts +19 -0
  275. package/templates/format-dev-errors.ts +34 -0
  276. package/templates/gitignore +172 -0
  277. package/templates/init-tests/test-jest-new-worker.js +23 -0
  278. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  279. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  280. package/templates/middleware/common.ts +62 -0
  281. package/templates/middleware/loader-modules.ts +84 -0
  282. package/templates/middleware/loader-sw.ts +233 -0
  283. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  284. package/templates/middleware/middleware-pretty-error.ts +40 -0
  285. package/templates/middleware/middleware-scheduled.ts +15 -0
  286. package/templates/new-worker-scheduled.js +17 -0
  287. package/templates/new-worker-scheduled.ts +32 -0
  288. package/templates/new-worker.js +3 -3
  289. package/templates/new-worker.ts +21 -3
  290. package/templates/no-op-worker.js +10 -0
  291. package/templates/pages-dev-pipeline.ts +31 -0
  292. package/templates/pages-dev-util.ts +52 -0
  293. package/templates/pages-shim.ts +12 -0
  294. package/templates/pages-template-plugin.ts +180 -0
  295. package/templates/pages-template-worker.ts +189 -0
  296. package/templates/serve-static-assets.ts +66 -0
  297. package/templates/service-bindings-module-facade.js +55 -0
  298. package/templates/service-bindings-sw-facade.js +42 -0
  299. package/templates/tsconfig-sanity.ts +11 -0
  300. package/templates/tsconfig.init.json +105 -0
  301. package/templates/tsconfig.json +6 -103
  302. package/templates/tsconfig.tsbuildinfo +1 -0
  303. package/wrangler-dist/cli.d.ts +1619 -0
  304. package/wrangler-dist/cli.js +141446 -128789
  305. package/wrangler-dist/wasm-sync.wasm +0 -0
  306. package/pages/functions/buildWorker.ts +0 -62
  307. package/pages/functions/filepath-routing.test.ts +0 -123
  308. package/pages/functions/filepath-routing.ts +0 -178
  309. package/pages/functions/identifiers.ts +0 -78
  310. package/pages/functions/routes.ts +0 -151
  311. package/pages/functions/template-worker.ts +0 -130
  312. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  313. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  314. package/src/__tests__/helpers/mock-user.ts +0 -27
  315. package/src/__tests__/sentry.test.ts +0 -146
  316. package/src/api/form_data.ts +0 -217
  317. package/src/api/preview.ts +0 -147
  318. package/src/api/worker.ts +0 -186
  319. package/src/dialogs.tsx +0 -77
  320. package/src/environment-variables.ts +0 -33
  321. package/src/guess-worker-format.ts +0 -68
  322. package/src/index.tsx +0 -2302
  323. package/src/kv.tsx +0 -339
  324. package/src/pages.tsx +0 -1045
  325. package/src/publish.ts +0 -363
  326. package/src/r2.ts +0 -50
  327. package/src/reporting.ts +0 -115
  328. package/src/sites.tsx +0 -238
  329. package/src/user.tsx +0 -1063
  330. package/src/whoami.tsx +0 -69
  331. package/templates/static-asset-facade.js +0 -47
  332. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  333. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  334. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  335. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  336. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  337. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  338. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  339. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  340. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  341. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  342. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  343. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  344. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  345. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  346. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  347. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  348. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  349. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  350. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  351. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  352. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  353. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  354. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  355. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  356. package/vendor/wrangler-mime/LICENSE +0 -21
  357. package/vendor/wrangler-mime/Mime.js +0 -97
  358. package/vendor/wrangler-mime/README.md +0 -187
  359. package/vendor/wrangler-mime/cli.js +0 -46
  360. package/vendor/wrangler-mime/index.js +0 -4
  361. package/vendor/wrangler-mime/lite.js +0 -4
  362. package/vendor/wrangler-mime/package.json +0 -52
  363. package/vendor/wrangler-mime/types/other.js +0 -1
  364. package/vendor/wrangler-mime/types/standard.js +0 -1
  365. package/wrangler-dist/cli.js.map +0 -7
package/src/dev.tsx CHANGED
@@ -1,960 +1,928 @@
1
- import assert from "node:assert";
2
- import { spawn } from "node:child_process";
3
- import { existsSync, realpathSync } from "node:fs";
4
- import { readFile, writeFile } from "node:fs/promises";
5
1
  import path from "node:path";
2
+ import chalk from "chalk";
6
3
  import { watch } from "chokidar";
7
- import clipboardy from "clipboardy";
8
- import commandExists from "command-exists";
9
- import { execaCommand } from "execa";
10
- import { Box, Text, useApp, useInput } from "ink";
11
- import React, { useState, useEffect, useRef } from "react";
12
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
13
- import onExit from "signal-exit";
14
- import tmp from "tmp-promise";
15
- import { fetch } from "undici";
16
- import { createWorker } from "./api/worker";
17
- import { bundleWorker } from "./bundle";
18
- import guessWorkerFormat from "./guess-worker-format";
19
- import useInspector from "./inspect";
20
- import { DEFAULT_MODULE_RULES } from "./module-collection";
21
- import openInBrowser from "./open-in-browser";
22
- import { usePreviewServer, waitForPortToBeAvailable } from "./proxy";
23
- import { syncAssets } from "./sites";
24
- import { getAPIToken } from "./user";
25
- import type { CfPreviewToken } from "./api/preview";
26
- import type { CfModule, CfWorkerInit, CfScriptFormat } from "./api/worker";
27
- import type { Config } from "./config";
28
- import type { Entry } from "./entry";
29
- import type { AssetPaths } from "./sites";
30
- import type { WatchMode } from "esbuild";
31
- import type { ExecaChildProcess } from "execa";
32
- import type { DirectoryResult } from "tmp-promise";
33
-
34
- export type DevProps = {
35
- name?: string;
36
- entry: Entry;
37
- port?: number;
38
- inspectorPort: number;
39
- format: CfScriptFormat | undefined;
40
- rules: Config["rules"];
41
- accountId: undefined | string;
42
- initialMode: "local" | "remote";
43
- jsxFactory: undefined | string;
44
- jsxFragment: undefined | string;
45
- enableLocalPersistence: boolean;
46
- bindings: CfWorkerInit["bindings"];
47
- public: undefined | string;
48
- assetPaths: undefined | AssetPaths;
49
- compatibilityDate: undefined | string;
50
- compatibilityFlags: undefined | string[];
51
- usageModel: undefined | "bundled" | "unbound";
52
- buildCommand: {
53
- command?: undefined | string;
54
- cwd?: undefined | string;
55
- watch_dir?: undefined | string;
56
- };
57
- env: string | undefined;
58
- legacyEnv: boolean;
59
- zone:
60
- | {
61
- id: string;
62
- host: string;
63
- }
64
- | undefined;
65
- };
66
-
67
- function Dev(props: DevProps): JSX.Element {
68
- const port = props.port ?? 8787;
69
- const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
70
- const directory = useTmpDir();
71
-
72
- // if there isn't a build command, we just return the entry immediately
73
- // ideally there would be a conditional here, but the rules of hooks
74
- // kinda forbid that, so we thread the entry through useCustomBuild
75
- const entry = useCustomBuild(props.entry, props.buildCommand);
76
-
77
- const format = useWorkerFormat({ entry: props.entry, format: props.format });
78
- if (format && props.public && format === "service-worker") {
79
- throw new Error(
80
- "You cannot use the service worker format with a `public` directory."
81
- );
82
- }
83
-
84
- if (props.bindings.wasm_modules && format === "modules") {
85
- throw new Error(
86
- "You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
87
- );
88
- }
89
-
90
- if (props.bindings.text_blobs && format === "modules") {
91
- throw new Error(
92
- "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[build.upload.rules]` in your wrangler.toml"
93
- );
94
- }
95
-
96
- const bundle = useEsbuild({
97
- entry,
98
- format,
99
- destination: directory,
100
- staticRoot: props.public,
101
- jsxFactory: props.jsxFactory,
102
- rules: props.rules,
103
- jsxFragment: props.jsxFragment,
104
- serveAssetsFromWorker: !!props.public,
105
- });
106
-
107
- const toggles = useHotkeys(
108
- {
109
- local: props.initialMode === "local",
110
- tunnel: false,
111
- },
112
- port,
113
- props.inspectorPort
114
- );
115
-
116
- useTunnel(toggles.tunnel);
117
-
118
- return (
119
- <>
120
- {toggles.local ? (
121
- <Local
122
- name={props.name}
123
- bundle={bundle}
124
- format={format}
125
- bindings={props.bindings}
126
- assetPaths={props.assetPaths}
127
- public={props.public}
128
- port={port}
129
- rules={props.rules}
130
- inspectorPort={props.inspectorPort}
131
- enableLocalPersistence={props.enableLocalPersistence}
132
- />
133
- ) : (
134
- <Remote
135
- name={props.name}
136
- bundle={bundle}
137
- format={format}
138
- accountId={props.accountId}
139
- apiToken={apiToken}
140
- bindings={props.bindings}
141
- assetPaths={props.assetPaths}
142
- public={props.public}
143
- port={port}
144
- inspectorPort={props.inspectorPort}
145
- compatibilityDate={props.compatibilityDate}
146
- compatibilityFlags={props.compatibilityFlags}
147
- usageModel={props.usageModel}
148
- env={props.env}
149
- legacyEnv={props.legacyEnv}
150
- zone={props.zone}
151
- />
152
- )}
153
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
154
- <Text>
155
- {`B to open a browser, D to open Devtools, L to ${
156
- toggles.local ? "turn off" : "turn on"
157
- } local mode, X to exit`}
158
- </Text>
159
- </Box>
160
- </>
161
- );
162
- }
163
-
164
- function useWorkerFormat(props: {
165
- entry: Entry | undefined;
166
- format: undefined | CfScriptFormat;
167
- }): CfScriptFormat | undefined {
168
- const [format, setFormat] = useState<CfScriptFormat | undefined>();
169
- useEffect(() => {
170
- async function validateFormat() {
171
- if (!props.entry || format) {
172
- return;
173
- }
174
- setFormat(await guessWorkerFormat(props.entry, props.format));
175
- }
176
- validateFormat().catch((err) => {
177
- console.error("Failed to validate worker format:", err);
178
- });
179
- }, [props.entry, props.format, format]);
180
- return format;
181
- }
182
-
183
- function Remote(props: {
184
- name: string | undefined;
185
- bundle: EsbuildBundle | undefined;
186
- format: CfScriptFormat | undefined;
187
- public: undefined | string;
188
- assetPaths: undefined | AssetPaths;
189
- port: number;
190
- inspectorPort: number;
191
- accountId: undefined | string;
192
- apiToken: undefined | string;
193
- bindings: CfWorkerInit["bindings"];
194
- compatibilityDate: string | undefined;
195
- compatibilityFlags: undefined | string[];
196
- usageModel: undefined | "bundled" | "unbound";
197
- env: string | undefined;
198
- legacyEnv: boolean | undefined;
199
- zone: { id: string; host: string } | undefined;
200
- }) {
201
- assert(props.accountId, "accountId is required");
202
- assert(props.apiToken, "apiToken is required");
203
- const previewToken = useWorker({
204
- name: props.name,
205
- bundle: props.bundle,
206
- format: props.format,
207
- modules: props.bundle ? props.bundle.modules : [],
208
- accountId: props.accountId,
209
- apiToken: props.apiToken,
210
- bindings: props.bindings,
211
- assetPaths: props.assetPaths,
212
- port: props.port,
213
- compatibilityDate: props.compatibilityDate,
214
- compatibilityFlags: props.compatibilityFlags,
215
- usageModel: props.usageModel,
216
- env: props.env,
217
- legacyEnv: props.legacyEnv,
218
- zone: props.zone,
219
- });
220
-
221
- usePreviewServer({
222
- previewToken,
223
- publicRoot: props.public,
224
- port: props.port,
225
- });
226
-
227
- useInspector({
228
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
229
- port: props.inspectorPort,
230
- logToTerminal: true,
231
- });
232
- return null;
233
- }
234
- function Local(props: {
235
- name: undefined | string;
236
- bundle: EsbuildBundle | undefined;
237
- format: CfScriptFormat | undefined;
238
- bindings: CfWorkerInit["bindings"];
239
- assetPaths: undefined | AssetPaths;
240
- public: undefined | string;
241
- port: number;
242
- rules: Config["rules"];
243
- inspectorPort: number;
244
- enableLocalPersistence: boolean;
245
- }) {
246
- const { inspectorUrl } = useLocalWorker({
247
- name: props.name,
248
- bundle: props.bundle,
249
- format: props.format,
250
- bindings: props.bindings,
251
- assetPaths: props.assetPaths,
252
- public: props.public,
253
- port: props.port,
254
- rules: props.rules,
255
- inspectorPort: props.port,
256
- enableLocalPersistence: props.enableLocalPersistence,
257
- });
258
- useInspector({
259
- inspectorUrl,
260
- port: props.inspectorPort,
261
- logToTerminal: false,
262
- });
263
- return null;
264
- }
265
-
266
- function useLocalWorker(props: {
267
- name: undefined | string;
268
- bundle: EsbuildBundle | undefined;
269
- rules: Config["rules"];
270
- format: CfScriptFormat | undefined;
271
- bindings: CfWorkerInit["bindings"];
272
- assetPaths: undefined | AssetPaths;
273
- public: undefined | string;
274
- port: number;
275
- inspectorPort: number;
276
- enableLocalPersistence: boolean;
277
- }) {
278
- // TODO: pass vars via command line
279
- const { bundle, format, bindings, port, assetPaths, inspectorPort } = props;
280
- const local = useRef<ReturnType<typeof spawn>>();
281
- const removeSignalExitListener = useRef<() => void>();
282
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
283
- useEffect(() => {
284
- async function startLocalWorker() {
285
- if (!bundle || !format) return;
286
-
287
- // port for the worker
288
- await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
289
- // port for inspector
290
- await waitForPortToBeAvailable(inspectorPort, {
291
- retryPeriod: 200,
292
- timeout: 2000,
293
- });
294
-
295
- if (props.public) {
296
- throw new Error(
297
- 'āŽ” A "public" folder is not yet supported in local mode.'
298
- );
299
- }
300
-
301
- // In local mode, we want to copy all referenced modules into
302
- // the output bundle directory before starting up
303
- for (const module of bundle.modules) {
304
- await writeFile(
305
- path.join(path.dirname(bundle.path), module.name),
306
- module.content
307
- );
308
- }
309
-
310
- console.log("āŽ” Starting a local server...");
311
- // TODO: just use execa for this
312
- local.current = spawn(
313
- "node",
314
- [
315
- "--experimental-vm-modules",
316
- "--inspect",
317
- require.resolve("miniflare/cli"),
318
- realpathSync(bundle.path),
319
- "--watch",
320
- "--wrangler-config",
321
- path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
322
- "--env",
323
- path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
324
- "--package",
325
- path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
326
- "--port",
327
- port.toString(),
328
- ...(assetPaths
329
- ? [
330
- "--site",
331
- path.join(process.cwd(), assetPaths.baseDirectory),
332
- ...assetPaths.includePatterns.map((pattern) => [
333
- "--site-include",
334
- pattern,
335
- ]),
336
- ...assetPaths.excludePatterns.map((pattern) => [
337
- "--site-exclude",
338
- pattern,
339
- ]),
340
- ].flatMap((x) => x)
341
- : []),
342
- ...(props.enableLocalPersistence
343
- ? ["--kv-persist", "--cache-persist", "--do-persist"]
344
- : []),
345
- ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
346
- return ["--binding", `${key}=${value}`];
347
- }),
348
- ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
349
- return ["--kv", binding];
350
- }),
351
- ...(bindings.durable_objects?.bindings || []).flatMap(
352
- ({ name, class_name }) => {
353
- return ["--do", `${name}=${class_name}`];
354
- }
355
- ),
356
- ...Object.entries(bindings.wasm_modules || {}).flatMap(
357
- ([name, filePath]) => {
358
- return [
359
- "--wasm",
360
- `${name}=${path.join(process.cwd(), filePath)}`,
361
- ];
362
- }
363
- ),
364
- ...bundle.modules.reduce<string[]>((cmd, { name, type }) => {
365
- if (format === "service-worker") {
366
- if (type === "compiled-wasm") {
367
- // In service-worker format, .wasm modules are referenced
368
- // by global identifiers, so we convert it here.
369
- // This identifier has to be a valid JS identifier,
370
- // so we replace all non alphanumeric characters
371
- // with an underscore.
372
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
373
- return cmd.concat([`--wasm`, `${identifier}=${name}`]);
374
- } else {
375
- // TODO: we should actually support this
376
- throw new Error(
377
- `āŽ” Unsupported module type ${type} for file ${name} in service-worker format`
378
- );
379
- }
380
- }
381
- return cmd;
382
- }, []),
383
- "--modules",
384
- String(format === "modules"),
385
- ...(props.rules || [])
386
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
387
- .concat(DEFAULT_MODULE_RULES!)
388
- .flatMap((rule) =>
389
- rule.globs.flatMap((glob) => [
390
- "--modules-rule",
391
- `${rule.type}=${glob}`,
392
- ])
393
- ),
394
- ],
395
- {
396
- cwd: path.dirname(realpathSync(bundle.path)),
397
- }
398
- );
399
- console.log(`⬣ Listening at http://localhost:${port}`);
400
-
401
- local.current.on("close", (code) => {
402
- if (code !== null) {
403
- console.log(`miniflare process exited with code ${code}`);
404
- }
405
- });
406
-
407
- local.current.stdout?.on("data", (data: Buffer) => {
408
- console.log(`${data.toString()}`);
409
- });
410
-
411
- local.current.stderr?.on("data", (data: Buffer) => {
412
- console.error(`${data.toString()}`);
413
- const matches =
414
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
415
- data.toString()
416
- );
417
- if (matches) {
418
- setInspectorUrl(matches[1]);
419
- }
420
- });
421
-
422
- local.current.on("exit", (code) => {
423
- if (code !== 0) {
424
- console.error(`miniflare process exited with code ${code}`);
425
- }
426
- });
427
-
428
- local.current.on("error", (error: Error) => {
429
- console.error(`miniflare process failed to spawn`);
430
- console.error(error);
431
- });
432
-
433
- removeSignalExitListener.current = onExit((_code, _signal) => {
434
- console.log("āŽ” Shutting down local server.");
435
- local.current?.kill();
436
- local.current = undefined;
437
- });
438
- }
439
-
440
- startLocalWorker().catch((err) => {
441
- console.error("local worker:", err);
442
- });
443
-
444
- return () => {
445
- if (local.current) {
446
- console.log("āŽ” Shutting down local server.");
447
- local.current?.kill();
448
- local.current = undefined;
449
- removeSignalExitListener.current && removeSignalExitListener.current();
450
- removeSignalExitListener.current = undefined;
451
- }
452
- };
453
- }, [
454
- bundle,
455
- format,
456
- port,
457
- inspectorPort,
458
- bindings.durable_objects?.bindings,
459
- bindings.kv_namespaces,
460
- bindings.vars,
461
- props.enableLocalPersistence,
462
- assetPaths,
463
- props.public,
464
- props.rules,
465
- bindings.wasm_modules,
466
- ]);
467
- return { inspectorUrl };
468
- }
469
-
470
- function useTmpDir(): string | undefined {
471
- const [directory, setDirectory] = useState<DirectoryResult>();
472
- const handleError = useErrorHandler();
473
- useEffect(() => {
474
- let dir: DirectoryResult;
475
- async function create() {
476
- try {
477
- dir = await tmp.dir({ unsafeCleanup: true });
478
- setDirectory(dir);
479
- return;
480
- } catch (err) {
481
- console.error("failed to create tmp dir");
482
- throw err;
483
- }
484
- }
485
- create().catch((err) => {
486
- // we want to break here
487
- // we can't do much without a temp dir anyway
488
- handleError(err);
489
- });
490
- return () => {
491
- dir.cleanup().catch(() => {
492
- // extremely unlikely,
493
- // but it's 2022 after all
494
- console.error("failed to cleanup tmp dir");
495
- });
496
- };
497
- }, [handleError]);
498
- return directory?.path;
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
+ );
499
291
  }
500
292
 
501
- function useCustomBuild(
502
- expectedEntry: Entry,
503
- props: {
504
- command?: undefined | string;
505
- cwd?: undefined | string;
506
- watch_dir?: undefined | string;
507
- }
508
- ): undefined | Entry {
509
- const [entry, setEntry] = useState<Entry | undefined>(
510
- // if there's no build command, just return the expected entry
511
- !props.command ? expectedEntry : undefined
512
- );
513
- const { command, cwd, watch_dir } = props;
514
- useEffect(() => {
515
- if (!command) return;
516
- let cmd: ExecaChildProcess<string> | undefined,
517
- interval: NodeJS.Timeout | undefined;
518
- console.log("running:", command);
519
- cmd = execaCommand(command, {
520
- ...(cwd && { cwd }),
521
- shell: true,
522
- stderr: "inherit",
523
- stdout: "inherit",
524
- });
525
- if (watch_dir) {
526
- watch(watch_dir, { persistent: true, ignoreInitial: true }).on(
527
- "all",
528
- (_event, filePath) => {
529
- console.log(`The file ${filePath} changed, restarting build...`);
530
- cmd?.kill();
531
- cmd = execaCommand(command, {
532
- ...(cwd && { cwd }),
533
- shell: true,
534
- stderr: "inherit",
535
- stdout: "inherit",
536
- });
537
- }
538
- );
539
- }
540
-
541
- // check every so often whether `expectedEntry` exists
542
- // if it does, we're done
543
- const startedAt = Date.now();
544
- interval = setInterval(() => {
545
- let fileExists = false;
546
- try {
547
- // Use require.resolve to use node's resolution algorithm,
548
- // this lets us use paths without explicit .js extension
549
- // TODO: we should probably remove this, because it doesn't
550
- // take into consideration other extensions like .tsx, .ts, .jsx, etc
551
- fileExists = existsSync(require.resolve(expectedEntry.file));
552
- } catch (e) {
553
- // fail silently, usually means require.resolve threw MODULE_NOT_FOUND
554
- }
555
-
556
- if (fileExists === true) {
557
- interval && clearInterval(interval);
558
- setEntry(expectedEntry);
559
- } else {
560
- const elapsed = Date.now() - startedAt;
561
- // timeout after 30 seconds of waiting
562
- if (elapsed > 1000 * 30) {
563
- console.error(
564
- `āŽ” Build timed out, Could not resolve ${expectedEntry.file}`
565
- );
566
- interval && clearInterval(interval);
567
- cmd?.kill();
568
- }
569
- }
570
- }, 200);
571
-
572
- return () => {
573
- if (cmd) {
574
- cmd.kill();
575
- cmd = undefined;
576
- }
577
- interval && clearInterval(interval);
578
- interval = undefined;
579
- };
580
- }, [command, cwd, expectedEntry, watch_dir]);
581
- return entry;
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
+ }
582
314
  }
583
315
 
584
- type EsbuildBundle = {
585
- id: number;
586
- path: string;
587
- entry: Entry;
588
- type: "esm" | "commonjs";
589
- modules: CfModule[];
590
- serveAssetsFromWorker: boolean;
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"];
591
337
  };
592
338
 
593
- function useEsbuild({
594
- entry,
595
- destination,
596
- staticRoot,
597
- jsxFactory,
598
- jsxFragment,
599
- format,
600
- rules,
601
- serveAssetsFromWorker,
602
- }: {
603
- entry: undefined | Entry;
604
- destination: string | undefined;
605
- format: CfScriptFormat | undefined;
606
- staticRoot: undefined | string;
607
- jsxFactory: string | undefined;
608
- jsxFragment: string | undefined;
609
- rules: Config["rules"];
610
- serveAssetsFromWorker: boolean;
611
- }): EsbuildBundle | undefined {
612
- const [bundle, setBundle] = useState<EsbuildBundle>();
613
- useEffect(() => {
614
- let stopWatching: (() => void) | undefined = undefined;
615
-
616
- const watchMode: WatchMode = {
617
- async onRebuild(error) {
618
- if (error) console.error("watch build failed:", error);
619
- else {
620
- // nothing really changes here, so let's increment the id
621
- // to change the return object's identity
622
- setBundle((previousBundle) => {
623
- assert(
624
- previousBundle,
625
- "Rebuild triggered with no previous build available"
626
- );
627
- return { ...previousBundle, id: previousBundle.id + 1 };
628
- });
629
- }
630
- },
631
- };
632
-
633
- async function build() {
634
- if (!destination || !entry || !format) return;
635
-
636
- const { resolvedEntryPointPath, bundleType, modules, stop } =
637
- await bundleWorker(entry, destination, {
638
- // In dev, we serve assets from the local proxy before we send the request to the worker.
639
- serveAssetsFromWorker: false,
640
- jsxFactory,
641
- jsxFragment,
642
- format,
643
- rules,
644
- watch: watchMode,
645
- });
646
-
647
- // Capture the `stop()` method to use as the `useEffect()` destructor.
648
- stopWatching = stop;
649
-
650
- setBundle({
651
- id: 0,
652
- entry,
653
- path: resolvedEntryPointPath,
654
- type: bundleType,
655
- modules,
656
- serveAssetsFromWorker,
657
- });
658
- }
659
-
660
- build().catch(() => {
661
- // esbuild already logs errors to stderr and we don't want to end the process
662
- // on build errors anyway so this is a no-op error handler
663
- });
664
-
665
- return stopWatching;
666
- }, [
667
- entry,
668
- destination,
669
- staticRoot,
670
- jsxFactory,
671
- jsxFragment,
672
- format,
673
- serveAssetsFromWorker,
674
- rules,
675
- ]);
676
- return bundle;
677
- }
678
-
679
- function useWorker(props: {
680
- name: string | undefined;
681
- bundle: EsbuildBundle | undefined;
682
- format: CfScriptFormat | undefined;
683
- modules: CfModule[];
684
- accountId: string;
685
- apiToken: string;
686
- bindings: CfWorkerInit["bindings"];
687
- assetPaths: undefined | AssetPaths;
688
- port: number;
689
- compatibilityDate: string | undefined;
690
- compatibilityFlags: string[] | undefined;
691
- usageModel: undefined | "bundled" | "unbound";
692
- env: string | undefined;
693
- legacyEnv: boolean | undefined;
694
- zone: { id: string; host: string } | undefined;
695
- }): CfPreviewToken | undefined {
696
- const {
697
- name,
698
- bundle,
699
- format,
700
- modules,
701
- accountId,
702
- apiToken,
703
- bindings,
704
- assetPaths,
705
- compatibilityDate,
706
- compatibilityFlags,
707
- usageModel,
708
- port,
709
- } = props;
710
- const [token, setToken] = useState<CfPreviewToken | undefined>();
711
-
712
- // This is the most reliable way to detect whether
713
- // something's "happened" in our system; We make a ref and
714
- // mark it once we log our initial message. Refs are vars!
715
- const startedRef = useRef(false);
716
-
717
- useEffect(() => {
718
- async function start() {
719
- setToken(undefined); // reset token in case we're re-running
720
-
721
- if (!bundle || !format) return;
722
-
723
- if (!startedRef.current) {
724
- startedRef.current = true;
725
- } else {
726
- console.log("āŽ” Detected changes, restarted server.");
727
- }
728
-
729
- const assets = await syncAssets(
730
- accountId,
731
- // When we're using the newer service environments, we wouldn't
732
- // have added the env name on to the script name. However, we must
733
- // include it in the kv namespace name regardless (since there's no
734
- // concept of service environments for kv namespaces yet).
735
- name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
736
- assetPaths,
737
- true
738
- ); // TODO: cancellable?
739
-
740
- const content = await readFile(bundle.path, "utf-8");
741
-
742
- const init: CfWorkerInit = {
743
- name,
744
- main: {
745
- name: path.basename(bundle.path),
746
- type: format === "modules" ? "esm" : "commonjs",
747
- content,
748
- },
749
- modules: modules.concat(
750
- assets.manifest
751
- ? {
752
- name: "__STATIC_CONTENT_MANIFEST",
753
- content: JSON.stringify(assets.manifest),
754
- type: "text",
755
- }
756
- : []
757
- ),
758
- bindings: {
759
- ...bindings,
760
- kv_namespaces: (bindings.kv_namespaces || []).concat(
761
- assets.namespace
762
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
763
- : []
764
- ),
765
- text_blobs: {
766
- ...bindings.text_blobs,
767
- ...(assets.manifest &&
768
- format === "service-worker" && {
769
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
770
- }),
771
- },
772
- },
773
- migrations: undefined, // no migrations in dev
774
- compatibility_date: compatibilityDate,
775
- compatibility_flags: compatibilityFlags,
776
- usage_model: usageModel,
777
- };
778
- setToken(
779
- await createWorker(
780
- init,
781
- {
782
- accountId,
783
- apiToken,
784
- },
785
- { env: props.env, legacyEnv: props.legacyEnv, zone: props.zone }
786
- )
787
- );
788
- }
789
- start().catch((err) => {
790
- // we want to log the error, but not end the process
791
- // since it could recover after the developer fixes whatever's wrong
792
- console.error("remote worker:", err);
793
- });
794
- }, [
795
- name,
796
- bundle,
797
- format,
798
- accountId,
799
- apiToken,
800
- port,
801
- assetPaths,
802
- compatibilityDate,
803
- compatibilityFlags,
804
- usageModel,
805
- bindings,
806
- modules,
807
- props.env,
808
- props.legacyEnv,
809
- props.zone,
810
- ]);
811
- return token;
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
+ showInteractiveDevSession?: boolean;
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
+ if (args.local && process.platform !== "win32") {
360
+ logger.info(
361
+ chalk.magenta(
362
+ `Want to try out the next version of local mode using the open-source Workers runtime?\nSwitch out --local for ${chalk.bold(
363
+ "--experimental-local"
364
+ )} and let us know what you think at https://discord.gg/cloudflaredev !`
365
+ )
366
+ );
367
+ }
368
+
369
+ const configPath =
370
+ args.config ||
371
+ (args.script && findWranglerToml(path.dirname(args.script)));
372
+ let config = readConfig(configPath, args);
373
+
374
+ if (config.configPath) {
375
+ watcher = watch(config.configPath, {
376
+ persistent: true,
377
+ }).on("change", async (_event) => {
378
+ // TODO: Do we need to handle different `_event` types differently?
379
+ // e.g. what if the file is deleted, or added?
380
+ config = readConfig(configPath, args);
381
+ if (config.configPath) {
382
+ logger.log(`${path.basename(config.configPath)} changed...`);
383
+ rerender(await getDevReactElement(config));
384
+ }
385
+ });
386
+ }
387
+
388
+ const {
389
+ entry,
390
+ legacyNodeCompat,
391
+ nodejsCompat,
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
+ legacyNodeCompat={legacyNodeCompat}
431
+ nodejsCompat={nodejsCompat}
432
+ build={configParam.build || {}}
433
+ define={{ ...configParam.define, ...cliDefines }}
434
+ initialMode={
435
+ args.local || args.experimentalLocal ? "local" : "remote"
436
+ }
437
+ jsxFactory={args.jsxFactory || configParam.jsx_factory}
438
+ jsxFragment={args.jsxFragment || configParam.jsx_fragment}
439
+ tsconfig={args.tsconfig ?? configParam.tsconfig}
440
+ upstreamProtocol={upstreamProtocol}
441
+ localProtocol={args.localProtocol || configParam.dev.local_protocol}
442
+ localUpstream={args.localUpstream ?? host}
443
+ localPersistencePath={localPersistencePath}
444
+ liveReload={args.liveReload || false}
445
+ accountId={configParam.account_id || getAccountFromCache()?.id}
446
+ assetPaths={assetPaths}
447
+ assetsConfig={configParam.assets}
448
+ initialPort={
449
+ args.port ?? configParam.dev.port ?? (await getLocalPort())
450
+ }
451
+ initialIp={args.ip || configParam.dev.ip}
452
+ inspectorPort={
453
+ args.inspectorPort ??
454
+ configParam.dev.inspector_port ??
455
+ (await getInspectorPort())
456
+ }
457
+ isWorkersSite={Boolean(args.site || configParam.site)}
458
+ compatibilityDate={getDevCompatibilityDate(
459
+ configParam,
460
+ args.compatibilityDate
461
+ )}
462
+ compatibilityFlags={
463
+ args.compatibilityFlags || configParam.compatibility_flags
464
+ }
465
+ usageModel={configParam.usage_model}
466
+ bindings={bindings}
467
+ crons={configParam.triggers.crons}
468
+ queueConsumers={configParam.queues.consumers}
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
+ }
812
512
  }
813
513
 
814
- function sleep(period: number) {
815
- return new Promise((resolve) => setTimeout(resolve, period));
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
+ legacyNodeCompat,
527
+ nodejsCompat,
528
+ upstreamProtocol,
529
+ zoneId,
530
+ host,
531
+ routes,
532
+ getLocalPort,
533
+ getInspectorPort,
534
+ cliDefines,
535
+ localPersistencePath,
536
+ } = await validateDevServerSettings(args, config);
537
+
538
+ await metrics.sendMetricsEvent(
539
+ "run dev (api)",
540
+ { local: args.local },
541
+ { sendMetrics: config.send_metrics, offline: args.local }
542
+ );
543
+
544
+ // eslint-disable-next-line no-inner-declarations
545
+ async function getDevServer(configParam: Config) {
546
+ const { assetPaths, bindings } = getBindingsAndAssetPaths(
547
+ args,
548
+ configParam
549
+ );
550
+
551
+ //if args.bundle is on, don't disable bundling
552
+ //if there's no args.bundle, and configParam.no_bundle is on, disable bundling
553
+ //otherwise, enable bundling
554
+ const enableBundling = args.bundle ?? !configParam.no_bundle;
555
+ return await startDevServer({
556
+ name: getScriptName({ name: args.name, env: args.env }, configParam),
557
+ noBundle: !enableBundling,
558
+ entry: entry,
559
+ env: args.env,
560
+ zone: zoneId,
561
+ host: host,
562
+ routes: routes,
563
+ rules: getRules(configParam),
564
+ legacyEnv: isLegacyEnv(configParam),
565
+ minify: args.minify ?? configParam.minify,
566
+ legacyNodeCompat,
567
+ nodejsCompat,
568
+ build: configParam.build || {},
569
+ define: { ...config.define, ...cliDefines },
570
+ initialMode: args.local ? "local" : "remote",
571
+ jsxFactory: args.jsxFactory ?? configParam.jsx_factory,
572
+ jsxFragment: args.jsxFragment ?? configParam.jsx_fragment,
573
+ tsconfig: args.tsconfig ?? configParam.tsconfig,
574
+ upstreamProtocol: upstreamProtocol,
575
+ localProtocol: args.localProtocol ?? configParam.dev.local_protocol,
576
+ localUpstream: args.localUpstream ?? host,
577
+ localPersistencePath,
578
+ liveReload: args.liveReload ?? false,
579
+ accountId: configParam.account_id ?? getAccountFromCache()?.id,
580
+ assetPaths: assetPaths,
581
+ assetsConfig: configParam.assets,
582
+ //port can be 0, which means to use a random port
583
+ initialPort: args.port ?? configParam.dev.port ?? (await getLocalPort()),
584
+ initialIp: args.ip ?? configParam.dev.ip,
585
+ inspectorPort:
586
+ args.inspectorPort ??
587
+ configParam.dev.inspector_port ??
588
+ (await getInspectorPort()),
589
+ isWorkersSite: Boolean(args.site || configParam.site),
590
+ compatibilityDate: getDevCompatibilityDate(
591
+ config,
592
+ // Only `compatibilityDate` will be set when using `unstable_dev`
593
+ args.compatibilityDate
594
+ ),
595
+ compatibilityFlags:
596
+ args.compatibilityFlags ?? configParam.compatibility_flags,
597
+ usageModel: configParam.usage_model,
598
+ bindings: bindings,
599
+ crons: configParam.triggers.crons,
600
+ queueConsumers: configParam.queues.consumers,
601
+ onReady: args.onReady,
602
+ inspect: args.inspect ?? true,
603
+ showInteractiveDevSession: args.showInteractiveDevSession,
604
+ forceLocal: args.forceLocal,
605
+ enablePagesAssetsServiceBinding: args.enablePagesAssetsServiceBinding,
606
+ local: args.local ?? true,
607
+ firstPartyWorker: configParam.first_party_worker,
608
+ sendMetrics: configParam.send_metrics,
609
+ testScheduled: args.testScheduled,
610
+ experimentalLocal: args.experimentalLocal,
611
+ experimentalLocalRemoteKv: args.experimentalLocalRemoteKv,
612
+ disableDevRegistry: args.disableDevRegistry ?? false,
613
+ });
614
+ }
615
+
616
+ const devServer = await getDevServer(config);
617
+ if (!devServer) {
618
+ throw logger.error("Failed to start dev server.");
619
+ }
620
+
621
+ return {
622
+ stop: async () => {
623
+ await devServer.stop();
624
+ },
625
+ };
816
626
  }
817
- const SLEEP_DURATION = 2000;
818
- // really need a first class api for this
819
- const hostNameRegex = /userHostname="(.*)"/g;
820
- async function findTunnelHostname() {
821
- let hostName: string | undefined;
822
- while (!hostName) {
823
- try {
824
- const resp = await fetch("http://localhost:8789/metrics");
825
- const data = await resp.text();
826
- const matches = Array.from(data.matchAll(hostNameRegex));
827
- hostName = matches[0][1];
828
- } catch (err) {
829
- await sleep(SLEEP_DURATION);
830
- }
831
- }
832
- return hostName;
627
+ /**
628
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
629
+ */
630
+ function memoizeGetPort(defaultPort: number) {
631
+ let portValue: number;
632
+ return async () => {
633
+ return portValue || (portValue = await getPort({ port: defaultPort }));
634
+ };
833
635
  }
834
-
835
636
  /**
836
- * Create a tunnel to the remote worker.
837
- * We've disabled this for now until we figure out a better user experience.
637
+ * mask anything that was overridden in .dev.vars
638
+ * so that we don't log potential secrets into the terminal
838
639
  */
839
- function useTunnel(toggle: boolean) {
840
- const tunnel = useRef<ReturnType<typeof spawn>>();
841
- const removeSignalExitListener = useRef<() => void>();
842
- // TODO: test if cloudflared is available, if not
843
- // point them to a url where they can get docs to install it
844
- useEffect(() => {
845
- async function startTunnel() {
846
- if (toggle) {
847
- try {
848
- await commandExists("cloudflared");
849
- } catch (e) {
850
- console.error(
851
- "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
852
- );
853
- return;
854
- }
855
- console.log("āŽ” Starting a tunnel...");
856
- tunnel.current = spawn("cloudflared", [
857
- "tunnel",
858
- "--url",
859
- "http://localhost:8787",
860
- "--metrics",
861
- "localhost:8789",
862
- ]);
863
-
864
- tunnel.current.on("close", (code) => {
865
- if (code !== 0) {
866
- console.log(`Tunnel process exited with code ${code}`);
867
- }
868
- });
869
-
870
- removeSignalExitListener.current = onExit((_code, _signal) => {
871
- console.log("āŽ” Shutting down local tunnel.");
872
- tunnel.current?.kill();
873
- tunnel.current = undefined;
874
- });
875
-
876
- const hostName = await findTunnelHostname();
877
- await clipboardy.write(hostName);
878
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
879
- }
880
- }
881
-
882
- startTunnel().catch((err) => {
883
- console.error("tunnel:", err);
884
- });
885
-
886
- return () => {
887
- if (tunnel.current) {
888
- console.log("āŽ” Shutting down tunnel.");
889
- tunnel.current?.kill();
890
- tunnel.current = undefined;
891
- removeSignalExitListener.current && removeSignalExitListener.current();
892
- removeSignalExitListener.current = undefined;
893
- }
894
- };
895
- }, [toggle]);
640
+ function maskVars(bindings: CfWorkerInit["bindings"], configParam: Config) {
641
+ const maskedVars = { ...bindings.vars };
642
+ for (const key of Object.keys(maskedVars)) {
643
+ if (maskedVars[key] !== configParam.vars[key]) {
644
+ // This means it was overridden in .dev.vars
645
+ // so let's mask it
646
+ maskedVars[key] = "(hidden)";
647
+ }
648
+ }
649
+ return maskedVars;
896
650
  }
897
651
 
898
- type useHotkeysInitialState = {
899
- local: boolean;
900
- tunnel: boolean;
901
- };
902
- function useHotkeys(
903
- initial: useHotkeysInitialState,
904
- port: number,
905
- inspectorPort: number
652
+ async function getZoneIdHostAndRoutes(args: StartDevOptions, config: Config) {
653
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
654
+ // Compute zone info from the `host` and `route` args and config;
655
+ let host = args.host || config.dev.host;
656
+ let zoneId: string | undefined;
657
+ const routes: Route[] | undefined =
658
+ args.routes || (config.route && [config.route]) || config.routes;
659
+
660
+ if (args.forceLocal) {
661
+ args.local = true;
662
+ }
663
+
664
+ if (!args.local) {
665
+ if (host) {
666
+ zoneId = await getZoneIdFromHost(host);
667
+ }
668
+ if (!zoneId && routes) {
669
+ const firstRoute = routes[0];
670
+ const zone = await getZoneForRoute(firstRoute);
671
+ if (zone) {
672
+ zoneId = zone.id;
673
+ host = zone.host;
674
+ }
675
+ }
676
+ } else if (!host) {
677
+ if (routes) {
678
+ const firstRoute = routes[0];
679
+ host = getHostFromRoute(firstRoute);
680
+ }
681
+ }
682
+ return { host, routes, zoneId };
683
+ }
684
+
685
+ async function validateDevServerSettings(
686
+ args: StartDevOptions,
687
+ config: Config
906
688
  ) {
907
- // UGH, we should put port in context instead
908
- const [toggles, setToggles] = useState(initial);
909
- useInput(
910
- async (
911
- input,
912
- // eslint-disable-next-line unused-imports/no-unused-vars
913
- key
914
- ) => {
915
- switch (input.toLowerCase()) {
916
- // open browser
917
- case "b": {
918
- await openInBrowser(`http://localhost:${port}`);
919
- break;
920
- }
921
- // toggle inspector
922
- case "d": {
923
- await openInBrowser(
924
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:${inspectorPort}/ws`
925
- );
926
- break;
927
- }
928
- // toggle local
929
- case "l":
930
- setToggles((previousToggles) => ({
931
- ...previousToggles,
932
- local: !previousToggles.local,
933
- }));
934
- break;
935
- // shut down
936
- case "q":
937
- case "x":
938
- process.exit(0);
939
- break;
940
- default:
941
- // nothing?
942
- break;
943
- }
944
- }
945
- );
946
- return toggles;
689
+ const entry = await getEntry(
690
+ { assets: args.assets, script: args.script },
691
+ config,
692
+ "dev"
693
+ );
694
+
695
+ const { zoneId, host, routes } = await getZoneIdHostAndRoutes(args, config);
696
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
697
+ const getInspectorPort = memoizeGetPort(DEFAULT_INSPECTOR_PORT);
698
+
699
+ if (config.services && config.services.length > 0) {
700
+ logger.warn(
701
+ `This worker is bound to live services: ${config.services
702
+ .map(
703
+ (service) =>
704
+ `${service.binding} (${service.service}${
705
+ service.environment ? `@${service.environment}` : ""
706
+ })`
707
+ )
708
+ .join(", ")}`
709
+ );
710
+ }
711
+
712
+ if (args.inspect) {
713
+ //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
714
+ logger.warn(
715
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
716
+ );
717
+ }
718
+ if (args.experimentalPublic) {
719
+ throw new Error(
720
+ "The --experimental-public field has been renamed to --assets"
721
+ );
722
+ }
723
+
724
+ if (args.public) {
725
+ throw new Error("The --public field has been renamed to --assets");
726
+ }
727
+
728
+ if ((args.assets ?? config.assets) && (args.site ?? config.site)) {
729
+ throw new Error("Cannot use Assets and Workers Sites in the same Worker.");
730
+ }
731
+
732
+ if (args.assets) {
733
+ logger.warn(
734
+ "The --assets argument is experimental and may change or break at any time"
735
+ );
736
+ }
737
+ const upstreamProtocol =
738
+ args.upstreamProtocol ?? config.dev.upstream_protocol;
739
+ if (upstreamProtocol === "http") {
740
+ logger.warn(
741
+ "Setting upstream-protocol to http is not currently implemented.\n" +
742
+ "If this is required in your project, please add your use case to the following issue:\n" +
743
+ "https://github.com/cloudflare/workers-sdk/issues/583."
744
+ );
745
+ }
746
+ const legacyNodeCompat = args.nodeCompat ?? config.node_compat;
747
+ if (legacyNodeCompat) {
748
+ logger.warn(
749
+ "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."
750
+ );
751
+ }
752
+
753
+ const compatibilityFlags =
754
+ args.compatibilityFlags ?? config.compatibility_flags;
755
+ const nodejsCompat = compatibilityFlags?.includes("nodejs_compat");
756
+ if (legacyNodeCompat && nodejsCompat) {
757
+ throw new Error(
758
+ "The `nodejs_compat` compatibility flag cannot be used in conjunction with the legacy `--node-compat` flag. If you want to use the Workers runtime Node.js compatibility features, please remove the `--node-compat` argument from your CLI command or `node_compat = true` from your config file."
759
+ );
760
+ }
761
+
762
+ if (args.experimentalEnableLocalPersistence) {
763
+ logger.warn(
764
+ `--experimental-enable-local-persistence is deprecated.\n` +
765
+ `Move any existing data to .wrangler/state and use --persist, or\n` +
766
+ `use --persist-to=./wrangler-local-state to keep using the old path.`
767
+ );
768
+ }
769
+
770
+ const localPersistencePath = getLocalPersistencePath(
771
+ args.persistTo,
772
+ Boolean(args.persist),
773
+ config.configPath
774
+ );
775
+
776
+ const cliDefines = collectKeyValues(args.define);
777
+
778
+ return {
779
+ entry,
780
+ upstreamProtocol,
781
+ legacyNodeCompat,
782
+ nodejsCompat,
783
+ getLocalPort,
784
+ getInspectorPort,
785
+ zoneId,
786
+ host,
787
+ routes,
788
+ cliDefines,
789
+ localPersistencePath,
790
+ };
947
791
  }
948
792
 
949
- function ErrorFallback(props: { error: Error }) {
950
- const { exit } = useApp();
951
- useEffect(() => exit(new Error()));
952
- return (
953
- <>
954
- <Text>Something went wrong:</Text>
955
- <Text>{props.error.stack}</Text>
956
- </>
957
- );
793
+ function getBindingsAndAssetPaths(args: StartDevOptions, configParam: Config) {
794
+ const cliVars = collectKeyValues(args.var);
795
+
796
+ // now log all available bindings into the terminal
797
+ const bindings = getBindings(configParam, args.env, args.local ?? false, {
798
+ kv: args.kv,
799
+ vars: { ...args.vars, ...cliVars },
800
+ durableObjects: args.durableObjects,
801
+ r2: args.r2,
802
+ d1Databases: args.d1Databases,
803
+ });
804
+
805
+ const maskedVars = maskVars(bindings, configParam);
806
+
807
+ printBindings({
808
+ ...bindings,
809
+ vars: maskedVars,
810
+ });
811
+
812
+ const assetPaths =
813
+ args.assets || configParam.assets
814
+ ? getAssetPaths(configParam, args.assets)
815
+ : getSiteAssetPaths(
816
+ configParam,
817
+ args.site,
818
+ args.siteInclude,
819
+ args.siteExclude
820
+ );
821
+ return { assetPaths, bindings };
958
822
  }
959
823
 
960
- export default withErrorBoundary(Dev, { FallbackComponent: ErrorFallback });
824
+ function getBindings(
825
+ configParam: Config,
826
+ env: string | undefined,
827
+ local: boolean,
828
+ args: AdditionalDevProps
829
+ ): CfWorkerInit["bindings"] {
830
+ const bindings = {
831
+ kv_namespaces: [
832
+ ...(configParam.kv_namespaces || []).map(
833
+ ({ binding, preview_id, id: _id }) => {
834
+ // In `dev`, we make folks use a separate kv namespace called
835
+ // `preview_id` instead of `id` so that they don't
836
+ // break production data. So here we check that a `preview_id`
837
+ // has actually been configured.
838
+ // This whole block of code will be obsoleted in the future
839
+ // when we have copy-on-write for previews on edge workers.
840
+ if (!preview_id) {
841
+ // TODO: This error has to be a _lot_ better, ideally just asking
842
+ // to create a preview namespace for the user automatically
843
+ throw new Error(
844
+ `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`
845
+ ); // Ugh, I really don't like this message very much
846
+ }
847
+ return {
848
+ binding,
849
+ id: preview_id,
850
+ };
851
+ }
852
+ ),
853
+ ...(args.kv || []),
854
+ ],
855
+ // Use a copy of combinedVars since we're modifying it later
856
+ vars: {
857
+ ...getVarsForDev(configParam, env),
858
+ ...args.vars,
859
+ },
860
+ wasm_modules: configParam.wasm_modules,
861
+ text_blobs: configParam.text_blobs,
862
+ data_blobs: configParam.data_blobs,
863
+ durable_objects: {
864
+ bindings: [
865
+ ...(configParam.durable_objects || { bindings: [] }).bindings,
866
+ ...(args.durableObjects || []),
867
+ ],
868
+ },
869
+ queues: [
870
+ ...(configParam.queues.producers || []).map((queue) => {
871
+ return { binding: queue.binding, queue_name: queue.queue };
872
+ }),
873
+ ],
874
+ r2_buckets: [
875
+ ...(configParam.r2_buckets?.map(
876
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
877
+ // same idea as kv namespace preview id,
878
+ // same copy-on-write TODO
879
+ if (!preview_bucket_name) {
880
+ throw new Error(
881
+ `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`
882
+ );
883
+ }
884
+ return {
885
+ binding,
886
+ bucket_name: preview_bucket_name,
887
+ };
888
+ }
889
+ ) || []),
890
+ ...(args.r2 || []),
891
+ ],
892
+ dispatch_namespaces: configParam.dispatch_namespaces,
893
+ mtls_certificates: configParam.mtls_certificates,
894
+ services: configParam.services,
895
+ analytics_engine_datasets: configParam.analytics_engine_datasets,
896
+ unsafe: {
897
+ bindings: configParam.unsafe.bindings,
898
+ metadata: configParam.unsafe.metadata,
899
+ },
900
+ logfwdr: configParam.logfwdr,
901
+ d1_databases: identifyD1BindingsAsBeta([
902
+ ...(configParam.d1_databases ?? []).map((d1Db) => {
903
+ //in local dev, bindings don't matter
904
+ if (local) {
905
+ return {
906
+ ...d1Db,
907
+ database_id: "local",
908
+ };
909
+ }
910
+ // if you have a preview_database_id, we'll use it, but we shouldn't force people to use it.
911
+ if (!d1Db.preview_database_id && !process.env.NO_D1_WARNING) {
912
+ logger.log(
913
+ `--------------------\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`
914
+ );
915
+ }
916
+ return {
917
+ ...d1Db,
918
+ database_id: d1Db.preview_database_id
919
+ ? d1Db.preview_database_id
920
+ : d1Db.database_id,
921
+ };
922
+ }),
923
+ ...(args.d1Databases || []),
924
+ ]),
925
+ };
926
+
927
+ return bindings;
928
+ }