wrangler 0.0.0-e928f94 → 0.0.0-e93063e9

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