wrangler 0.0.0-e151223 → 0.0.0-e1e2ee5c

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 (209) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +160 -28
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +5354 -0
  6. package/package.json +166 -127
  7. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  8. package/src/__tests__/config-cache.test.ts +42 -0
  9. package/src/__tests__/configuration.test.ts +3950 -0
  10. package/src/__tests__/dev.test.tsx +1199 -67
  11. package/src/__tests__/guess-worker-format.test.ts +85 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/mock-account-id.ts +36 -18
  14. package/src/__tests__/helpers/mock-bin.ts +36 -0
  15. package/src/__tests__/helpers/mock-cfetch.ts +118 -80
  16. package/src/__tests__/helpers/mock-console.ts +70 -29
  17. package/src/__tests__/helpers/mock-dialogs.ts +121 -33
  18. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  19. package/src/__tests__/helpers/mock-istty.ts +74 -0
  20. package/src/__tests__/helpers/mock-kv.ts +28 -35
  21. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  22. package/src/__tests__/helpers/mock-process.ts +39 -0
  23. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  24. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  25. package/src/__tests__/helpers/run-in-tmp.ts +29 -20
  26. package/src/__tests__/helpers/run-wrangler.ts +8 -6
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  29. package/src/__tests__/https-options.test.ts +163 -0
  30. package/src/__tests__/index.test.ts +255 -399
  31. package/src/__tests__/init.test.ts +1992 -0
  32. package/src/__tests__/jest.setup.ts +102 -16
  33. package/src/__tests__/kv.test.ts +1400 -878
  34. package/src/__tests__/logger.test.ts +141 -0
  35. package/src/__tests__/metrics.test.ts +445 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1261 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6633 -1184
  40. package/src/__tests__/pubsub.test.ts +367 -0
  41. package/src/__tests__/r2.test.ts +233 -0
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +484 -202
  44. package/src/__tests__/tail.test.ts +698 -0
  45. package/src/__tests__/test-old-node-version.js +31 -0
  46. package/src/__tests__/user.test.ts +143 -0
  47. package/src/__tests__/version.test.ts +35 -0
  48. package/src/__tests__/whoami.test.tsx +219 -75
  49. package/src/__tests__/worker-namespace.test.ts +327 -0
  50. package/src/abort.d.ts +3 -0
  51. package/src/api/dev.ts +86 -0
  52. package/src/api/index.ts +1 -0
  53. package/src/bundle-reporter.tsx +29 -0
  54. package/src/bundle.ts +236 -0
  55. package/src/cfetch/index.ts +86 -76
  56. package/src/cfetch/internal.ts +122 -45
  57. package/src/cli.ts +24 -6
  58. package/src/config/README.md +107 -0
  59. package/src/config/config.ts +251 -0
  60. package/src/config/diagnostics.ts +80 -0
  61. package/src/config/environment.ts +453 -0
  62. package/src/config/index.ts +238 -0
  63. package/src/config/validation-helpers.ts +584 -0
  64. package/src/config/validation.ts +1754 -0
  65. package/src/config-cache.ts +84 -0
  66. package/src/create-worker-preview.ts +255 -0
  67. package/src/create-worker-upload-form.ts +263 -0
  68. package/src/dev/dev-vars.ts +36 -0
  69. package/src/dev/dev.tsx +452 -0
  70. package/src/dev/local.tsx +373 -0
  71. package/src/dev/remote.tsx +386 -0
  72. package/src/dev/use-esbuild.ts +150 -0
  73. package/src/dev.tsx +579 -820
  74. package/src/dialogs.tsx +115 -57
  75. package/src/durable.ts +102 -0
  76. package/src/entry.ts +328 -0
  77. package/src/environment-variables.ts +35 -0
  78. package/src/errors.ts +11 -0
  79. package/src/faye-websocket.d.ts +6 -0
  80. package/src/generate.ts +33 -0
  81. package/src/git-client.ts +42 -0
  82. package/src/global-wrangler-config-path.ts +26 -0
  83. package/src/https-options.ts +127 -0
  84. package/src/index.tsx +1969 -2024
  85. package/src/init.ts +549 -0
  86. package/src/inspect.ts +603 -537
  87. package/src/intl-polyfill.d.ts +139 -0
  88. package/src/is-interactive.ts +12 -0
  89. package/src/kv.ts +430 -0
  90. package/src/logger.ts +73 -0
  91. package/src/metrics/index.ts +4 -0
  92. package/src/metrics/is-ci.ts +14 -0
  93. package/src/metrics/metrics-config.ts +239 -0
  94. package/src/metrics/metrics-dispatcher.ts +95 -0
  95. package/src/metrics/send-event.ts +92 -0
  96. package/src/miniflare-cli/README.md +30 -0
  97. package/src/miniflare-cli/assets.ts +543 -0
  98. package/src/miniflare-cli/enum-keys.ts +17 -0
  99. package/src/miniflare-cli/index.ts +85 -0
  100. package/src/miniflare-cli/request-context.ts +40 -0
  101. package/src/module-collection.ts +244 -49
  102. package/src/open-in-browser.ts +17 -0
  103. package/src/package-manager.ts +219 -0
  104. package/src/pages/build.tsx +204 -0
  105. package/src/pages/constants.ts +7 -0
  106. package/src/pages/deployments.tsx +106 -0
  107. package/src/pages/dev.tsx +401 -0
  108. package/src/pages/functions/buildPlugin.ts +105 -0
  109. package/src/pages/functions/buildWorker.ts +151 -0
  110. package/src/pages/functions/filepath-routing.test.ts +234 -0
  111. package/src/pages/functions/filepath-routing.ts +189 -0
  112. package/src/pages/functions/identifiers.ts +78 -0
  113. package/src/pages/functions/routes.ts +151 -0
  114. package/src/pages/index.tsx +84 -0
  115. package/src/pages/projects.tsx +163 -0
  116. package/src/pages/publish.tsx +338 -0
  117. package/src/pages/types.ts +40 -0
  118. package/src/pages/upload.tsx +396 -0
  119. package/src/pages/utils.ts +12 -0
  120. package/src/parse.ts +286 -0
  121. package/src/paths.ts +6 -6
  122. package/src/preview.ts +31 -0
  123. package/src/proxy.ts +417 -311
  124. package/src/publish.ts +774 -391
  125. package/src/pubsub/index.ts +286 -0
  126. package/src/pubsub/pubsub-commands.tsx +623 -0
  127. package/src/r2.ts +50 -0
  128. package/src/selfsigned.d.ts +29 -0
  129. package/src/sites.tsx +291 -159
  130. package/src/tail/filters.ts +279 -0
  131. package/src/tail/index.ts +299 -0
  132. package/src/tail/printing.ts +67 -0
  133. package/src/update-check.ts +19 -0
  134. package/src/user/choose-account.tsx +69 -0
  135. package/src/user/env-vars.ts +46 -0
  136. package/src/user/generate-auth-url.ts +33 -0
  137. package/src/user/generate-random-state.ts +16 -0
  138. package/src/user/index.ts +3 -0
  139. package/src/user/user.tsx +1171 -0
  140. package/src/whoami.tsx +63 -41
  141. package/src/worker-namespace.ts +206 -0
  142. package/src/worker.ts +191 -0
  143. package/src/zones.ts +76 -0
  144. package/templates/checked-fetch.js +17 -0
  145. package/templates/gitignore +171 -0
  146. package/templates/new-worker-scheduled.js +17 -0
  147. package/templates/new-worker-scheduled.ts +32 -0
  148. package/templates/new-worker.js +15 -0
  149. package/templates/new-worker.ts +30 -0
  150. package/templates/no-op-worker.js +10 -0
  151. package/templates/pages-shim.ts +9 -0
  152. package/templates/pages-template-plugin.ts +155 -0
  153. package/templates/pages-template-worker.ts +161 -0
  154. package/templates/static-asset-facade.js +49 -0
  155. package/templates/tsconfig.json +105 -0
  156. package/wrangler-dist/cli.d.ts +327 -0
  157. package/wrangler-dist/cli.js +78107 -79324
  158. package/pages/functions/buildWorker.ts +0 -62
  159. package/pages/functions/filepath-routing.test.ts +0 -47
  160. package/pages/functions/filepath-routing.ts +0 -231
  161. package/pages/functions/identifiers.ts +0 -78
  162. package/pages/functions/routes.ts +0 -160
  163. package/pages/functions/template-worker.ts +0 -136
  164. package/src/__tests__/helpers/mock-user.ts +0 -27
  165. package/src/__tests__/logout.test.ts +0 -50
  166. package/src/api/form_data.ts +0 -134
  167. package/src/api/preview.ts +0 -128
  168. package/src/api/worker.ts +0 -155
  169. package/src/config.ts +0 -641
  170. package/src/kv.tsx +0 -276
  171. package/src/npm-installer.ts +0 -20
  172. package/src/pages.tsx +0 -1045
  173. package/src/tail.tsx +0 -73
  174. package/src/user.tsx +0 -1019
  175. package/static-asset-facade.js +0 -47
  176. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  177. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  178. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  179. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  180. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  181. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  182. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  183. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  184. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  185. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  186. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  187. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  188. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  189. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  190. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  191. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  192. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  193. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  194. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  195. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  196. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  197. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  198. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  199. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  200. package/vendor/wrangler-mime/LICENSE +0 -21
  201. package/vendor/wrangler-mime/Mime.js +0 -97
  202. package/vendor/wrangler-mime/README.md +0 -187
  203. package/vendor/wrangler-mime/cli.js +0 -46
  204. package/vendor/wrangler-mime/index.js +0 -4
  205. package/vendor/wrangler-mime/lite.js +0 -4
  206. package/vendor/wrangler-mime/package.json +0 -52
  207. package/vendor/wrangler-mime/types/other.js +0 -1
  208. package/vendor/wrangler-mime/types/standard.js +0 -1
  209. package/wrangler-dist/cli.js.map +0 -7
package/src/dev.tsx CHANGED
@@ -1,834 +1,593 @@
1
- import assert from "node:assert";
2
- import { spawn } from "node:child_process";
3
- import { existsSync } from "node:fs";
4
- import { readFile } from "node:fs/promises";
5
1
  import path from "node:path";
6
2
  import { watch } from "chokidar";
7
- import clipboardy from "clipboardy";
8
- import commandExists from "command-exists";
9
- import * as esbuild from "esbuild";
10
- import { execaCommand } from "execa";
11
- import { Box, Text, useApp, useInput } from "ink";
12
- import open from "open";
13
- import React, { useState, useEffect, useRef } from "react";
14
- import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
15
- import onExit from "signal-exit";
16
- import tmp from "tmp-promise";
3
+ import getPort from "get-port";
4
+ import { render } from "ink";
5
+ import React from "react";
17
6
  import { fetch } from "undici";
18
-
19
- import { createWorker } from "./api/worker";
20
-
21
- import useInspector from "./inspect";
22
- import makeModuleCollector from "./module-collection";
23
- import { usePreviewServer, waitForPortToBeAvailable } from "./proxy";
24
- import { syncAssets } from "./sites";
25
- import { getAPIToken } from "./user";
26
- import type { CfPreviewToken } from "./api/preview";
27
- import type { CfModule, CfWorkerInit } from "./api/worker";
28
- import type { AssetPaths } from "./sites";
29
- import type { DirectoryResult } from "tmp-promise";
30
-
31
- type CfScriptFormat = undefined | "modules" | "service-worker";
32
-
33
- export type DevProps = {
34
- name?: string;
35
- entry: string;
36
- port?: number;
37
- format: CfScriptFormat;
38
- accountId: undefined | string;
39
- initialMode: "local" | "remote";
40
- jsxFactory: undefined | string;
41
- jsxFragment: undefined | string;
42
- enableLocalPersistence: boolean;
43
- bindings: CfWorkerInit["bindings"];
44
- public: undefined | string;
45
- assetPaths: undefined | AssetPaths;
46
- compatibilityDate: undefined | string;
47
- compatibilityFlags: undefined | string[];
48
- usageModel: undefined | "bundled" | "unbound";
49
- buildCommand: {
50
- command?: undefined | string;
51
- cwd?: undefined | string;
52
- watch_dir?: undefined | string;
53
- };
54
- env: string | undefined;
55
- };
56
-
57
- function Dev(props: DevProps): JSX.Element {
58
- if (props.public && props.format === "service-worker") {
59
- throw new Error(
60
- "You cannot use the service worker format with a `public` directory."
61
- );
62
- }
63
- const port = props.port ?? 8787;
64
- const apiToken = getAPIToken();
65
- const directory = useTmpDir();
66
-
67
- // if there isn't a build command, we just return the entry immediately
68
- // ideally there would be a conditional here, but the rules of hooks
69
- // kinda forbid that, so we thread the entry through useCustomBuild
70
- const entry = useCustomBuild(props.entry, props.buildCommand);
71
-
72
- const bundle = useEsbuild({
73
- entry,
74
- destination: directory,
75
- staticRoot: props.public,
76
- jsxFactory: props.jsxFactory,
77
- jsxFragment: props.jsxFragment,
78
- });
79
- if (bundle && bundle.type === "commonjs" && !props.format && props.public) {
80
- throw new Error(
81
- "You cannot use the service worker format with a `public` directory."
82
- );
83
- }
84
-
85
- const toggles = useHotkeys(
86
- {
87
- local: props.initialMode === "local",
88
- tunnel: false,
89
- },
90
- port
91
- );
92
-
93
- useTunnel(toggles.tunnel);
94
-
95
- return (
96
- <>
97
- {toggles.local ? (
98
- <Local
99
- name={props.name}
100
- bundle={bundle}
101
- format={props.format}
102
- bindings={props.bindings}
103
- assetPaths={props.assetPaths}
104
- public={props.public}
105
- port={port}
106
- enableLocalPersistence={props.enableLocalPersistence}
107
- />
108
- ) : (
109
- <Remote
110
- name={props.name}
111
- bundle={bundle}
112
- format={props.format}
113
- accountId={props.accountId}
114
- apiToken={apiToken}
115
- bindings={props.bindings}
116
- assetPaths={props.assetPaths}
117
- public={props.public}
118
- port={port}
119
- compatibilityDate={props.compatibilityDate}
120
- compatibilityFlags={props.compatibilityFlags}
121
- usageModel={props.usageModel}
122
- env={props.env}
123
- />
124
- )}
125
- <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
126
- <Text>
127
- {`B to open a browser, D to open Devtools, S to ${
128
- toggles.tunnel ? "turn off" : "turn on"
129
- } (experimental) sharing, L to ${
130
- toggles.local ? "turn off" : "turn on"
131
- } local mode, X to exit`}
132
- </Text>
133
- </Box>
134
- </>
135
- );
136
- }
137
-
138
- function Remote(props: {
139
- name: undefined | string;
140
- bundle: EsbuildBundle | undefined;
141
- format: CfScriptFormat;
142
- public: undefined | string;
143
- assetPaths: undefined | AssetPaths;
144
- port: number;
145
- accountId: undefined | string;
146
- apiToken: undefined | string;
147
- bindings: CfWorkerInit["bindings"];
148
- compatibilityDate: string | undefined;
149
- compatibilityFlags: undefined | string[];
150
- usageModel: undefined | "bundled" | "unbound";
151
- env: string | undefined;
152
- }) {
153
- assert(props.accountId, "accountId is required");
154
- assert(props.apiToken, "apiToken is required");
155
- const previewToken = useWorker({
156
- name: props.name,
157
- bundle: props.bundle,
158
- format: props.format,
159
- modules: props.bundle ? props.bundle.modules : [],
160
- accountId: props.accountId,
161
- apiToken: props.apiToken,
162
- bindings: props.bindings,
163
- assetPaths: props.assetPaths,
164
- port: props.port,
165
- compatibilityDate: props.compatibilityDate,
166
- compatibilityFlags: props.compatibilityFlags,
167
- usageModel: props.usageModel,
168
- env: props.env,
169
- });
170
-
171
- usePreviewServer({
172
- previewToken,
173
- publicRoot: props.public,
174
- port: props.port,
175
- });
176
-
177
- useInspector({
178
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
179
- port: 9229,
180
- logToTerminal: true,
181
- });
182
- return null;
183
- }
184
- function Local(props: {
185
- name: undefined | string;
186
- bundle: EsbuildBundle | undefined;
187
- format: CfScriptFormat;
188
- bindings: CfWorkerInit["bindings"];
189
- assetPaths: undefined | AssetPaths;
190
- public: undefined | string;
191
- port: number;
192
- enableLocalPersistence: boolean;
193
- }) {
194
- const { inspectorUrl } = useLocalWorker({
195
- name: props.name,
196
- bundle: props.bundle,
197
- format: props.format,
198
- bindings: props.bindings,
199
- assetPaths: props.assetPaths,
200
- public: props.public,
201
- port: props.port,
202
- enableLocalPersistence: props.enableLocalPersistence,
203
- });
204
- useInspector({ inspectorUrl, port: 9229, logToTerminal: false });
205
- return null;
7
+ import { findWranglerToml, printBindings, readConfig } from "./config";
8
+ import Dev from "./dev/dev";
9
+ import { getVarsForDev } from "./dev/dev-vars";
10
+
11
+ import { getEntry } from "./entry";
12
+ import { logger } from "./logger";
13
+ import * as metrics from "./metrics";
14
+ import { getAssetPaths, getSiteAssetPaths } from "./sites";
15
+ import { getAccountFromCache } from "./user";
16
+ import { getZoneIdFromHost, getZoneForRoute, getHostFromRoute } from "./zones";
17
+ import {
18
+ printWranglerBanner,
19
+ DEFAULT_LOCAL_PORT,
20
+ type ConfigPath,
21
+ getScriptName,
22
+ getDevCompatibilityDate,
23
+ getRules,
24
+ isLegacyEnv,
25
+ } from "./index";
26
+
27
+ import type { Config } from "./config";
28
+ import type { Route } from "./config/environment";
29
+ import type { EnablePagesAssetsServiceBindingOptions } from "./miniflare-cli";
30
+ import type { CfWorkerInit } from "./worker";
31
+ import type { RequestInit } from "undici";
32
+ import type { Argv, ArgumentsCamelCase } from "yargs";
33
+
34
+ interface DevArgs {
35
+ config?: string;
36
+ script?: string;
37
+ name?: string;
38
+ bundle?: boolean;
39
+ build?: boolean;
40
+ format?: string;
41
+ env?: string;
42
+ "compatibility-date"?: string;
43
+ "compatibility-flags"?: string[];
44
+ latest?: boolean;
45
+ ip?: string;
46
+ inspect?: boolean;
47
+ port?: number;
48
+ "inspector-port"?: number;
49
+ routes?: string[];
50
+ host?: string;
51
+ "local-protocol"?: "http" | "https";
52
+ "local-upstream"?: string | undefined;
53
+ "experimental-public"?: string;
54
+ public?: string;
55
+ assets?: string;
56
+ site?: string;
57
+ "site-include"?: string[];
58
+ "site-exclude"?: string[];
59
+ "upstream-protocol"?: "http" | "https";
60
+ "jsx-factory"?: string;
61
+ "jsx-fragment"?: string;
62
+ tsconfig?: string;
63
+ local?: boolean;
64
+ minify?: boolean;
65
+ "node-compat"?: boolean;
66
+ "experimental-enable-local-persistence"?: boolean;
67
+ "live-reload"?: boolean;
68
+ onReady?: () => void;
69
+ logLevel?: "none" | "error" | "log" | "warn" | "debug";
70
+ logPrefix?: string;
71
+ showInteractiveDevSession?: boolean;
206
72
  }
207
73
 
208
- function useLocalWorker(props: {
209
- name: undefined | string;
210
- bundle: EsbuildBundle | undefined;
211
- format: CfScriptFormat;
212
- bindings: CfWorkerInit["bindings"];
213
- assetPaths: undefined | AssetPaths;
214
- public: undefined | string;
215
- port: number;
216
- enableLocalPersistence: boolean;
217
- }) {
218
- // TODO: pass vars via command line
219
- const { bundle, format, bindings, port, assetPaths } = props;
220
- const local = useRef<ReturnType<typeof spawn>>();
221
- const removeSignalExitListener = useRef<() => void>();
222
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
223
- useEffect(() => {
224
- async function startLocalWorker() {
225
- if (!bundle) return;
226
- if (format === "modules" && bundle.type === "commonjs") {
227
- console.error("⎔ Cannot use modules with a commonjs bundle.");
228
- // TODO: a much better error message here, with what to do next
229
- return;
230
- }
231
- if (format === "service-worker" && bundle.type !== "esm") {
232
- console.error("⎔ Cannot use service-worker with a esm bundle.");
233
- // TODO: a much better error message here, with what to do next
234
- return;
235
- }
236
-
237
- await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
238
- if (props.public) {
239
- throw new Error(
240
- '⎔ A "public" folder is not yet supported in local mode.'
241
- );
242
- }
243
-
244
- console.log("⎔ Starting a local server...");
245
- // TODO: just use execa for this
246
- local.current = spawn("node", [
247
- "--experimental-vm-modules",
248
- "--inspect",
249
- require.resolve("miniflare/cli"),
250
- bundle.path,
251
- "--watch",
252
- "--wrangler-config",
253
- path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
254
- "--env",
255
- path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
256
- "--package",
257
- path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
258
- "--port",
259
- port.toString(),
260
- ...(assetPaths
261
- ? [
262
- "--site",
263
- assetPaths.baseDirectory,
264
- ...assetPaths.includePatterns.map((pattern) => [
265
- "--site-include",
266
- pattern,
267
- ]),
268
- ...assetPaths.excludePatterns.map((pattern) => [
269
- "--site-exclude",
270
- pattern,
271
- ]),
272
- ].flatMap((x) => x)
273
- : []),
274
- ...(props.enableLocalPersistence
275
- ? ["--kv-persist", "--cache-persist", "--do-persist"]
276
- : []),
277
- ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
278
- return ["--binding", `${key}=${value}`];
279
- }),
280
- ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
281
- return ["--kv", binding];
282
- }),
283
- ...(bindings.durable_objects?.bindings || []).flatMap(
284
- ({ name, class_name }) => {
285
- return ["--do", `${name}=${class_name}`];
286
- }
287
- ),
288
- "--modules",
289
- format ||
290
- (bundle.type === "esm" ? "modules" : "service-worker") === "modules"
291
- ? "true"
292
- : "false",
293
- ]);
294
- console.log(`⬣ Listening at http://localhost:${port}`);
295
-
296
- local.current.on("close", (code) => {
297
- if (code !== null) {
298
- console.log(`miniflare process exited with code ${code}`);
299
- }
300
- });
301
-
302
- local.current.stdout?.on("data", (data: Buffer) => {
303
- console.log(`${data.toString()}`);
304
- });
305
-
306
- local.current.stderr?.on("data", (data: Buffer) => {
307
- console.error(`${data.toString()}`);
308
- const matches =
309
- /Debugger listening on (ws:\/\/127\.0\.0\.1:9229\/[A-Za-z0-9-]+)/.exec(
310
- data.toString()
311
- );
312
- if (matches) {
313
- setInspectorUrl(matches[1]);
314
- }
315
- });
316
-
317
- local.current.on("exit", (code) => {
318
- if (code !== 0) {
319
- console.error(`miniflare process exited with code ${code}`);
320
- }
321
- });
322
-
323
- local.current.on("error", (error: Error) => {
324
- console.error(`miniflare process failed to spawn`);
325
- console.error(error);
326
- });
327
-
328
- removeSignalExitListener.current = onExit((_code, _signal) => {
329
- console.log("⎔ Shutting down local server.");
330
- local.current?.kill();
331
- local.current = undefined;
332
- });
333
- }
334
-
335
- startLocalWorker().catch((err) => {
336
- console.error("local worker:", err);
337
- });
338
-
339
- return () => {
340
- if (local.current) {
341
- console.log("⎔ Shutting down local server.");
342
- local.current?.kill();
343
- local.current = undefined;
344
- removeSignalExitListener.current && removeSignalExitListener.current();
345
- removeSignalExitListener.current = undefined;
346
- }
347
- };
348
- }, [
349
- bundle,
350
- format,
351
- port,
352
- bindings.durable_objects?.bindings,
353
- bindings.kv_namespaces,
354
- bindings.vars,
355
- props.enableLocalPersistence,
356
- assetPaths,
357
- props.public,
358
- ]);
359
- return { inspectorUrl };
74
+ export function devOptions(yargs: Argv): Argv<DevArgs> {
75
+ return (
76
+ yargs
77
+ .positional("script", {
78
+ describe: "The path to an entry point for your worker",
79
+ type: "string",
80
+ })
81
+ .option("name", {
82
+ describe: "Name of the worker",
83
+ type: "string",
84
+ requiresArg: true,
85
+ })
86
+ // We want to have a --no-bundle flag, but yargs requires that
87
+ // we also have a --bundle flag (that it adds the --no to by itself)
88
+ // So we make a --bundle flag, but hide it, and then add a --no-bundle flag
89
+ // that's visible to the user but doesn't "do" anything.
90
+ .option("bundle", {
91
+ describe: "Run wrangler's compilation step before publishing",
92
+ type: "boolean",
93
+ hidden: true,
94
+ })
95
+ .option("no-bundle", {
96
+ describe: "Skip internal build steps and directly publish script",
97
+ type: "boolean",
98
+ default: false,
99
+ })
100
+ .option("format", {
101
+ choices: ["modules", "service-worker"] as const,
102
+ describe: "Choose an entry type",
103
+ deprecated: true,
104
+ })
105
+ .option("env", {
106
+ describe: "Perform on a specific environment",
107
+ type: "string",
108
+ requiresArg: true,
109
+ alias: "e",
110
+ })
111
+ .option("compatibility-date", {
112
+ describe: "Date to use for compatibility checks",
113
+ type: "string",
114
+ requiresArg: true,
115
+ })
116
+ .option("compatibility-flags", {
117
+ describe: "Flags to use for compatibility checks",
118
+ alias: "compatibility-flag",
119
+ type: "string",
120
+ requiresArg: true,
121
+ array: true,
122
+ })
123
+ .option("latest", {
124
+ describe: "Use the latest version of the worker runtime",
125
+ type: "boolean",
126
+ default: true,
127
+ })
128
+ .option("ip", {
129
+ describe: "IP address to listen on, defaults to `localhost`",
130
+ type: "string",
131
+ requiresArg: true,
132
+ })
133
+ .option("port", {
134
+ describe: "Port to listen on",
135
+ type: "number",
136
+ })
137
+ .option("inspector-port", {
138
+ describe: "Port for devtools to connect to",
139
+ type: "number",
140
+ })
141
+ .option("routes", {
142
+ describe: "Routes to upload",
143
+ alias: "route",
144
+ type: "string",
145
+ requiresArg: true,
146
+ array: true,
147
+ })
148
+ .option("host", {
149
+ type: "string",
150
+ requiresArg: true,
151
+ describe:
152
+ "Host to forward requests to, defaults to the zone of project",
153
+ })
154
+ .option("local-protocol", {
155
+ describe: "Protocol to listen to requests on, defaults to http.",
156
+ choices: ["http", "https"] as const,
157
+ })
158
+ .options("local-upstream", {
159
+ type: "string",
160
+ describe:
161
+ "Host to act as origin in local mode, defaults to dev.host or route",
162
+ })
163
+ .option("experimental-public", {
164
+ describe: "Static assets to be served",
165
+ type: "string",
166
+ requiresArg: true,
167
+ deprecated: true,
168
+ hidden: true,
169
+ })
170
+ .option("assets", {
171
+ describe: "Static assets to be served",
172
+ type: "string",
173
+ requiresArg: true,
174
+ })
175
+ .option("site", {
176
+ describe: "Root folder of static assets for Workers Sites",
177
+ type: "string",
178
+ requiresArg: true,
179
+ })
180
+ .option("site-include", {
181
+ describe:
182
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.",
183
+ type: "string",
184
+ requiresArg: true,
185
+ array: true,
186
+ })
187
+ .option("site-exclude", {
188
+ describe:
189
+ "Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.",
190
+ type: "string",
191
+ requiresArg: true,
192
+ array: true,
193
+ })
194
+ .option("upstream-protocol", {
195
+ describe: "Protocol to forward requests to host on, defaults to https.",
196
+ choices: ["http", "https"] as const,
197
+ })
198
+ .option("jsx-factory", {
199
+ describe: "The function that is called for each JSX element",
200
+ type: "string",
201
+ requiresArg: true,
202
+ })
203
+ .option("jsx-fragment", {
204
+ describe: "The function that is called for each JSX fragment",
205
+ type: "string",
206
+ requiresArg: true,
207
+ })
208
+ .option("tsconfig", {
209
+ describe: "Path to a custom tsconfig.json file",
210
+ type: "string",
211
+ requiresArg: true,
212
+ })
213
+ .option("local", {
214
+ alias: "l",
215
+ describe: "Run on my machine",
216
+ type: "boolean",
217
+ default: false, // I bet this will a point of contention. We'll revisit it.
218
+ })
219
+ .option("minify", {
220
+ describe: "Minify the script",
221
+ type: "boolean",
222
+ })
223
+ .option("node-compat", {
224
+ describe: "Enable node.js compatibility",
225
+ type: "boolean",
226
+ })
227
+ .option("experimental-enable-local-persistence", {
228
+ describe: "Enable persistence for this session (only for local mode)",
229
+ type: "boolean",
230
+ })
231
+ .option("live-reload", {
232
+ // TODO: Add back in once we have remote `--live-reload`
233
+ hidden: true,
234
+ // describe: "Auto reload HTML pages when change is detected",
235
+ type: "boolean",
236
+ })
237
+ .option("inspect", {
238
+ describe: "Enable dev tools",
239
+ type: "boolean",
240
+ deprecated: true,
241
+ })
242
+ .option("legacy-env", {
243
+ type: "boolean",
244
+ describe: "Use legacy environments",
245
+ hidden: true,
246
+ })
247
+ );
360
248
  }
361
249
 
362
- function useTmpDir(): string | undefined {
363
- const [directory, setDirectory] = useState<DirectoryResult>();
364
- const handleError = useErrorHandler();
365
- useEffect(() => {
366
- let dir: DirectoryResult;
367
- async function create() {
368
- try {
369
- dir = await tmp.dir({ unsafeCleanup: true });
370
- setDirectory(dir);
371
- return;
372
- } catch (err) {
373
- console.error("failed to create tmp dir");
374
- throw err;
375
- }
376
- }
377
- create().catch((err) => {
378
- // we want to break here
379
- // we can't do much without a temp dir anyway
380
- handleError(err);
381
- });
382
- return () => {
383
- dir.cleanup().catch(() => {
384
- // extremely unlikely,
385
- // but it's 2022 after all
386
- console.error("failed to cleanup tmp dir");
387
- });
388
- };
389
- }, [handleError]);
390
- return directory?.path;
250
+ export async function devHandler(args: ArgumentsCamelCase<DevArgs>) {
251
+ let watcher;
252
+ try {
253
+ const devInstance = await startDev(args);
254
+ watcher = devInstance.watcher;
255
+ const { waitUntilExit } = devInstance.devReactElement;
256
+ await waitUntilExit();
257
+ } finally {
258
+ await watcher?.close();
259
+ }
391
260
  }
392
261
 
393
- function useCustomBuild(
394
- expectedEntry: string,
395
- props: {
396
- command?: undefined | string;
397
- cwd?: undefined | string;
398
- watch_dir?: undefined | string;
399
- }
400
- ): undefined | string {
401
- const [entry, setEntry] = useState<string | undefined>(
402
- // if there's no build command, just return the expected entry
403
- props.command || expectedEntry
404
- );
405
- const { command, cwd, watch_dir } = props;
406
- useEffect(() => {
407
- if (!command) return;
408
- let cmd, interval;
409
- console.log("running:", command);
410
- cmd = execaCommand(command, {
411
- ...(cwd && { cwd }),
412
- shell: true,
413
- stderr: "inherit",
414
- stdout: "inherit",
415
- });
416
- if (watch_dir) {
417
- watch(watch_dir, { persistent: true, ignoreInitial: true }).on(
418
- "all",
419
- (_event, filePath) => {
420
- console.log(`The file ${filePath} changed, restarting build...`);
421
- cmd.kill();
422
- cmd = execaCommand(command, {
423
- ...(cwd && { cwd }),
424
- shell: true,
425
- stderr: "inherit",
426
- stdout: "inherit",
427
- });
428
- }
429
- );
430
- }
431
-
432
- // check every so often whether `expectedEntry` exists
433
- // if it does, we're done
434
- const startedAt = Date.now();
435
- interval = setInterval(() => {
436
- if (existsSync(expectedEntry)) {
437
- clearInterval(interval);
438
- setEntry(expectedEntry);
439
- } else {
440
- const elapsed = Date.now() - startedAt;
441
- // timeout after 30 seconds of waiting
442
- if (elapsed > 1000 * 60 * 30) {
443
- console.error("⎔ Build timed out.");
444
- clearInterval(interval);
445
- cmd.kill();
446
- }
447
- }
448
- }, 200);
449
- // TODO: we could probably timeout here after a while
450
-
451
- return () => {
452
- if (cmd) {
453
- cmd.kill();
454
- cmd = undefined;
455
- }
456
- clearInterval(interval);
457
- interval = undefined;
458
- };
459
- }, [command, cwd, expectedEntry, watch_dir]);
460
- return entry;
461
- }
462
-
463
- type EsbuildBundle = {
464
- id: number;
465
- path: string;
466
- entry: string;
467
- type: "esm" | "commonjs";
468
- exports: string[];
469
- modules: CfModule[];
262
+ type StartDevOptions = ArgumentsCamelCase<DevArgs> & {
263
+ // These options can be passed in directly when called with the `wrangler.dev()` API.
264
+ // They aren't exposed as CLI arguments.
265
+ vars?: {
266
+ [key: string]: unknown;
267
+ };
268
+ kv?: {
269
+ binding: string;
270
+ id: string;
271
+ preview_id?: string;
272
+ }[];
273
+ durableObjects?: {
274
+ name: string;
275
+ class_name: string;
276
+ script_name?: string | undefined;
277
+ environment?: string | undefined;
278
+ }[];
279
+ forceLocal?: boolean;
280
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
470
281
  };
471
282
 
472
- function useEsbuild(props: {
473
- entry: undefined | string;
474
- destination: string | undefined;
475
- staticRoot: undefined | string;
476
- jsxFactory: string | undefined;
477
- jsxFragment: string | undefined;
478
- }): EsbuildBundle | undefined {
479
- const { entry, destination, staticRoot, jsxFactory, jsxFragment } = props;
480
- const [bundle, setBundle] = useState<EsbuildBundle>();
481
- useEffect(() => {
482
- let result: esbuild.BuildResult | undefined;
483
- async function build() {
484
- if (!destination || !entry) return;
485
- const moduleCollector = makeModuleCollector();
486
- result = await esbuild.build({
487
- entryPoints: [entry],
488
- bundle: true,
489
- outdir: destination,
490
- metafile: true,
491
- format: "esm",
492
- sourcemap: true,
493
- loader: {
494
- ".js": "jsx",
495
- ".html": "text",
496
- ".pem": "text",
497
- ".txt": "text",
498
- },
499
- ...(jsxFactory && { jsxFactory }),
500
- ...(jsxFragment && { jsxFragment }),
501
- external: ["__STATIC_CONTENT_MANIFEST"],
502
- conditions: ["worker", "browser"],
503
- plugins: [moduleCollector.plugin],
504
- // TODO: import.meta.url
505
- watch: {
506
- async onRebuild(error) {
507
- if (error) console.error("watch build failed:", error);
508
- else {
509
- // nothing really changes here, so let's increment the id
510
- // to change the return object's identity
511
- setBundle((previousBundle) => {
512
- if (previousBundle === undefined) {
513
- assert.fail(
514
- "Rebuild triggered with no previous build available"
515
- );
516
- }
517
- return { ...previousBundle, id: previousBundle.id + 1 };
518
- });
519
- }
520
- },
521
- },
522
- });
523
-
524
- // result.metafile is defined because of the `metafile: true` option above.
525
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
526
- const metafile = result.metafile!;
527
- const outputEntry = Object.entries(metafile.outputs).find(
528
- ([_path, { entryPoint }]) => entryPoint === entry
529
- ); // assumedly only one entry point
530
-
531
- if (outputEntry === undefined) {
532
- throw new Error(
533
- `Cannot find entry-point "${entry}" in generated bundle.`
534
- );
535
- }
536
- setBundle({
537
- id: 0,
538
- entry,
539
- path: outputEntry[0],
540
- type: outputEntry[1].exports.length > 0 ? "esm" : "commonjs",
541
- exports: outputEntry[1].exports,
542
- modules: moduleCollector.modules,
543
- });
544
- }
545
- build().catch((_err) => {
546
- // esbuild already logs errors to stderr
547
- // and we don't want to end the process
548
- // on build errors anyway
549
- // so this is a no-op error handler
550
- });
551
- return () => {
552
- result?.stop?.();
553
- };
554
- }, [entry, destination, staticRoot, jsxFactory, jsxFragment]);
555
- return bundle;
556
- }
557
-
558
- function useWorker(props: {
559
- name: undefined | string;
560
- bundle: EsbuildBundle | undefined;
561
- format: CfScriptFormat;
562
- modules: CfModule[];
563
- accountId: string;
564
- apiToken: string;
565
- bindings: CfWorkerInit["bindings"];
566
- assetPaths: undefined | AssetPaths;
567
- port: number;
568
- compatibilityDate: string | undefined;
569
- compatibilityFlags: string[] | undefined;
570
- usageModel: undefined | "bundled" | "unbound";
571
- env: string | undefined;
572
- }): CfPreviewToken | undefined {
573
- const {
574
- name,
575
- bundle,
576
- format,
577
- modules,
578
- accountId,
579
- apiToken,
580
- bindings,
581
- assetPaths,
582
- compatibilityDate,
583
- compatibilityFlags,
584
- usageModel,
585
- port,
586
- } = props;
587
- const [token, setToken] = useState<CfPreviewToken | undefined>();
588
-
589
- // This is the most reliable way to detect whether
590
- // something's "happened" in our system; We make a ref and
591
- // mark it once we log our initial message. Refs are vars!
592
- const startedRef = useRef(false);
593
-
594
- useEffect(() => {
595
- async function start() {
596
- setToken(undefined); // reset token in case we're re-running
597
-
598
- if (!bundle) return;
599
- if (format === "modules" && bundle.type === "commonjs") {
600
- console.error("⎔ Cannot use modules with a commonjs bundle.");
601
- // TODO: a much better error message here, with what to do next
602
- return;
603
- }
604
- if (format === "service-worker" && bundle.type !== "esm") {
605
- console.error("⎔ Cannot use service-worker with a esm bundle.");
606
- // TODO: a much better error message here, with what to do next
607
- return;
608
- }
609
-
610
- if (!startedRef.current) {
611
- startedRef.current = true;
612
- } else {
613
- console.log("⎔ Detected changes, restarted server.");
614
- }
615
-
616
- const assets = await syncAssets(
617
- accountId,
618
- name || path.basename(bundle.path),
619
- assetPaths,
620
- true,
621
- props.env
622
- ); // TODO: cancellable?
623
-
624
- const workerType = format || bundle.type === "esm" ? "esm" : "commonjs";
625
- let content = await readFile(bundle.path, "utf-8");
626
- if (workerType !== "esm" && assets.manifest) {
627
- content = `const __STATIC_CONTENT_MANIFEST = ${JSON.stringify(
628
- assets.manifest
629
- )};\n${content}`;
630
- }
631
-
632
- const init: CfWorkerInit = {
633
- name,
634
- main: {
635
- name: path.basename(bundle.path),
636
- type: workerType,
637
- content,
638
- },
639
- modules: modules.concat(
640
- assets.manifest && workerType === "esm"
641
- ? {
642
- name: "__STATIC_CONTENT_MANIFEST",
643
- content: JSON.stringify(assets.manifest),
644
- type: "text",
645
- }
646
- : []
647
- ),
648
- bindings: {
649
- ...bindings,
650
- kv_namespaces: (bindings.kv_namespaces || []).concat(
651
- assets.namespace
652
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
653
- : []
654
- ),
655
- },
656
- migrations: undefined, // no migrations in dev
657
- compatibility_date: compatibilityDate,
658
- compatibility_flags: compatibilityFlags,
659
- usage_model: usageModel,
660
- };
661
- setToken(
662
- await createWorker(init, {
663
- accountId,
664
- apiToken,
665
- })
666
- );
667
- }
668
- start().catch((err) => {
669
- // we want to log the error, but not end the process
670
- // since it could recover after the developer fixes whatever's wrong
671
- console.error("remote worker:", err);
672
- });
673
- }, [
674
- name,
675
- bundle,
676
- format,
677
- accountId,
678
- apiToken,
679
- port,
680
- assetPaths,
681
- compatibilityDate,
682
- compatibilityFlags,
683
- usageModel,
684
- bindings,
685
- modules,
686
- props.env,
687
- ]);
688
- return token;
283
+ export async function startDev(args: StartDevOptions) {
284
+ let watcher: ReturnType<typeof watch> | undefined;
285
+ let rerender: (node: React.ReactNode) => void | undefined;
286
+ try {
287
+ if (args.logLevel) {
288
+ // we don't define a "none" logLevel, so "error" will do for now.
289
+ logger.loggerLevel = args.logLevel === "none" ? "error" : args.logLevel;
290
+ }
291
+ await printWranglerBanner();
292
+
293
+ const configPath =
294
+ (args.config as ConfigPath) ||
295
+ ((args.script &&
296
+ findWranglerToml(path.dirname(args.script))) as ConfigPath);
297
+ let config = readConfig(configPath, args);
298
+ await metrics.sendMetricsEvent(
299
+ "run dev",
300
+ { local: args.local },
301
+ { sendMetrics: config.send_metrics, offline: args.local }
302
+ );
303
+
304
+ if (config.configPath) {
305
+ watcher = watch(config.configPath, {
306
+ persistent: true,
307
+ }).on("change", async (_event) => {
308
+ // TODO: Do we need to handle different `_event` types differently?
309
+ // e.g. what if the file is deleted, or added?
310
+ config = readConfig(configPath, args);
311
+ if (config.configPath) {
312
+ logger.log(`${path.basename(config.configPath)} changed...`);
313
+ rerender(await getDevReactElement(config));
314
+ }
315
+ });
316
+ }
317
+
318
+ const entry = await getEntry(
319
+ { assets: args.assets, script: args.script },
320
+ config,
321
+ "dev"
322
+ );
323
+
324
+ if (config.services && config.services.length > 0) {
325
+ logger.warn(
326
+ `This worker is bound to live services: ${config.services
327
+ .map(
328
+ (service) =>
329
+ `${service.binding} (${service.service}${
330
+ service.environment ? `@${service.environment}` : ""
331
+ })`
332
+ )
333
+ .join(", ")}`
334
+ );
335
+ }
336
+
337
+ if (args.inspect) {
338
+ //devtools are enabled by default, but we still need to disable them if the caller doesn't want them
339
+ logger.warn(
340
+ "Passing --inspect is unnecessary, now you can always connect to devtools."
341
+ );
342
+ }
343
+
344
+ if (args["experimental-public"]) {
345
+ throw new Error(
346
+ "The --experimental-public field has been renamed to --assets"
347
+ );
348
+ }
349
+
350
+ if (args.public) {
351
+ throw new Error("The --public field has been renamed to --assets");
352
+ }
353
+
354
+ if ((args.assets || config.assets) && (args.site || config.site)) {
355
+ throw new Error(
356
+ "Cannot use Assets and Workers Sites in the same Worker."
357
+ );
358
+ }
359
+
360
+ if (args.assets) {
361
+ logger.warn(
362
+ "The --assets argument is experimental and may change or break at any time"
363
+ );
364
+ }
365
+
366
+ const upstreamProtocol =
367
+ args["upstream-protocol"] || config.dev.upstream_protocol;
368
+ if (upstreamProtocol === "http") {
369
+ logger.warn(
370
+ "Setting upstream-protocol to http is not currently implemented.\n" +
371
+ "If this is required in your project, please add your use case to the following issue:\n" +
372
+ "https://github.com/cloudflare/wrangler2/issues/583."
373
+ );
374
+ }
375
+
376
+ // TODO: if worker_dev = false and no routes, then error (only for dev)
377
+
378
+ // Compute zone info from the `host` and `route` args and config;
379
+ let host = args.host || config.dev.host;
380
+ let zoneId: string | undefined;
381
+ const routes: Route[] | undefined =
382
+ args.routes || (config.route && [config.route]) || config.routes;
383
+
384
+ if (args.forceLocal) {
385
+ args.local = true;
386
+ }
387
+
388
+ if (!args.local) {
389
+ if (host) {
390
+ zoneId = await getZoneIdFromHost(host);
391
+ }
392
+ if (!zoneId && routes) {
393
+ const firstRoute = routes[0];
394
+ const zone = await getZoneForRoute(firstRoute);
395
+ if (zone) {
396
+ zoneId = zone.id;
397
+ host = zone.host;
398
+ }
399
+ }
400
+ } else if (!host) {
401
+ if (routes) {
402
+ const firstRoute = routes[0];
403
+ host = getHostFromRoute(firstRoute);
404
+ }
405
+ }
406
+
407
+ const nodeCompat = args.nodeCompat ?? config.node_compat;
408
+ if (nodeCompat) {
409
+ logger.warn(
410
+ "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."
411
+ );
412
+ }
413
+
414
+ // eslint-disable-next-line no-inner-declarations
415
+ async function getBindings(
416
+ configParam: Config
417
+ ): Promise<CfWorkerInit["bindings"]> {
418
+ return {
419
+ kv_namespaces: [
420
+ ...(configParam.kv_namespaces || []).map(
421
+ ({ binding, preview_id, id: _id }) => {
422
+ // In `dev`, we make folks use a separate kv namespace called
423
+ // `preview_id` instead of `id` so that they don't
424
+ // break production data. So here we check that a `preview_id`
425
+ // has actually been configured.
426
+ // This whole block of code will be obsoleted in the future
427
+ // when we have copy-on-write for previews on edge workers.
428
+ if (!preview_id) {
429
+ // TODO: This error has to be a _lot_ better, ideally just asking
430
+ // to create a preview namespace for the user automatically
431
+ throw new Error(
432
+ `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`
433
+ ); // Ugh, I really don't like this message very much
434
+ }
435
+ return {
436
+ binding,
437
+ id: preview_id,
438
+ };
439
+ }
440
+ ),
441
+ ...(args.kv || []),
442
+ ],
443
+ // Use a copy of combinedVars since we're modifying it later
444
+ vars: {
445
+ ...getVarsForDev(configParam),
446
+ ...args.vars,
447
+ },
448
+ wasm_modules: configParam.wasm_modules,
449
+ text_blobs: configParam.text_blobs,
450
+ data_blobs: configParam.data_blobs,
451
+ durable_objects: {
452
+ bindings: [
453
+ ...(configParam.durable_objects || { bindings: [] }).bindings,
454
+ ...(args.durableObjects || []),
455
+ ],
456
+ },
457
+ r2_buckets: configParam.r2_buckets?.map(
458
+ ({ binding, preview_bucket_name, bucket_name: _bucket_name }) => {
459
+ // same idea as kv namespace preview id,
460
+ // same copy-on-write TODO
461
+ if (!preview_bucket_name) {
462
+ throw new Error(
463
+ `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`
464
+ );
465
+ }
466
+ return {
467
+ binding,
468
+ bucket_name: preview_bucket_name,
469
+ };
470
+ }
471
+ ),
472
+ worker_namespaces: configParam.worker_namespaces,
473
+ services: configParam.services,
474
+ unsafe: configParam.unsafe?.bindings,
475
+ };
476
+ }
477
+
478
+ const getLocalPort = memoizeGetPort(DEFAULT_LOCAL_PORT);
479
+ const getInspectorPort = memoizeGetPort(9229);
480
+
481
+ // eslint-disable-next-line no-inner-declarations
482
+ async function getDevReactElement(configParam: Config) {
483
+ // now log all available bindings into the terminal
484
+ const bindings = await getBindings(configParam);
485
+ // mask anything that was overridden in .dev.vars
486
+ // so that we don't log potential secrets into the terminal
487
+ const maskedVars = { ...bindings.vars };
488
+ for (const key of Object.keys(maskedVars)) {
489
+ if (maskedVars[key] !== configParam.vars[key]) {
490
+ // This means it was overridden in .dev.vars
491
+ // so let's mask it
492
+ maskedVars[key] = "(hidden)";
493
+ }
494
+ }
495
+
496
+ printBindings({
497
+ ...bindings,
498
+ vars: maskedVars,
499
+ });
500
+
501
+ const assetPaths =
502
+ args.assets || config.assets
503
+ ? getAssetPaths(config, args.assets)
504
+ : getSiteAssetPaths(
505
+ config,
506
+ args.site,
507
+ args.siteInclude,
508
+ args.siteExclude
509
+ );
510
+
511
+ return (
512
+ <Dev
513
+ name={getScriptName({ name: args.name, env: args.env }, config)}
514
+ noBundle={!(args.bundle ?? !config.no_bundle)}
515
+ entry={entry}
516
+ env={args.env}
517
+ zone={zoneId}
518
+ host={host}
519
+ routes={routes}
520
+ rules={getRules(config)}
521
+ legacyEnv={isLegacyEnv(config)}
522
+ minify={args.minify ?? config.minify}
523
+ nodeCompat={nodeCompat}
524
+ build={config.build || {}}
525
+ define={config.define}
526
+ initialMode={args.local ? "local" : "remote"}
527
+ jsxFactory={args["jsx-factory"] || config.jsx_factory}
528
+ jsxFragment={args["jsx-fragment"] || config.jsx_fragment}
529
+ tsconfig={args.tsconfig ?? config.tsconfig}
530
+ upstreamProtocol={upstreamProtocol}
531
+ localProtocol={args.localProtocol || config.dev.local_protocol}
532
+ localUpstream={args["local-upstream"] || host}
533
+ enableLocalPersistence={
534
+ args["experimental-enable-local-persistence"] || false
535
+ }
536
+ liveReload={args.liveReload || false}
537
+ accountId={config.account_id || getAccountFromCache()?.id}
538
+ assetPaths={assetPaths}
539
+ port={args.port || config.dev.port || (await getLocalPort())}
540
+ ip={args.ip || config.dev.ip}
541
+ inspectorPort={args["inspector-port"] ?? (await getInspectorPort())}
542
+ isWorkersSite={Boolean(args.site || config.site)}
543
+ compatibilityDate={getDevCompatibilityDate(
544
+ config,
545
+ args["compatibility-date"]
546
+ )}
547
+ compatibilityFlags={
548
+ args["compatibility-flags"] || config.compatibility_flags
549
+ }
550
+ usageModel={config.usage_model}
551
+ bindings={bindings}
552
+ crons={config.triggers.crons}
553
+ logLevel={args.logLevel}
554
+ logPrefix={args.logPrefix}
555
+ onReady={args.onReady}
556
+ inspect={args.inspect ?? true}
557
+ showInteractiveDevSession={args.showInteractiveDevSession}
558
+ forceLocal={args.forceLocal}
559
+ enablePagesAssetsServiceBinding={args.enablePagesAssetsServiceBinding}
560
+ />
561
+ );
562
+ }
563
+ const devReactElement = render(await getDevReactElement(config));
564
+ rerender = devReactElement.rerender;
565
+ return {
566
+ devReactElement,
567
+ watcher,
568
+ stop: async () => {
569
+ devReactElement.unmount();
570
+ await watcher?.close();
571
+ },
572
+ fetch: async (init?: RequestInit) => {
573
+ //TODO: we are not guaranteed to be assigned this port, we should fix this ASAP
574
+ const port = args.port || config.dev.port || (await getLocalPort());
575
+ const address = args.ip || config.dev.ip || "localhost";
576
+
577
+ return await fetch(`http://${address}:${port}/`, init);
578
+ },
579
+ };
580
+ } finally {
581
+ await watcher?.close();
582
+ }
689
583
  }
690
584
 
691
- function sleep(period: number) {
692
- return new Promise((resolve) => setTimeout(resolve, period));
693
- }
694
- const SLEEP_DURATION = 2000;
695
- // really need a first class api for this
696
- const hostNameRegex = /userHostname="(.*)"/g;
697
- async function findTunnelHostname() {
698
- let hostName: string | undefined;
699
- while (!hostName) {
700
- try {
701
- const resp = await fetch("http://localhost:8789/metrics");
702
- const data = await resp.text();
703
- const matches = Array.from(data.matchAll(hostNameRegex));
704
- hostName = matches[0][1];
705
- } catch (err) {
706
- await sleep(SLEEP_DURATION);
707
- }
708
- }
709
- return hostName;
585
+ /**
586
+ * Avoiding calling `getPort()` multiple times by memoizing the first result.
587
+ */
588
+ function memoizeGetPort(defaultPort: number) {
589
+ let portValue: number;
590
+ return async () => {
591
+ return portValue || (portValue = await getPort({ port: defaultPort }));
592
+ };
710
593
  }
711
-
712
- function useTunnel(toggle: boolean) {
713
- const tunnel = useRef<ReturnType<typeof spawn>>();
714
- const removeSignalExitListener = useRef<() => void>();
715
- // TODO: test if cloudflared is available, if not
716
- // point them to a url where they can get docs to install it
717
- useEffect(() => {
718
- async function startTunnel() {
719
- if (toggle) {
720
- try {
721
- await commandExists("cloudflared");
722
- } catch (e) {
723
- console.error(
724
- "To share your worker on the internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
725
- );
726
- return;
727
- }
728
- console.log("⎔ Starting a tunnel...");
729
- tunnel.current = spawn("cloudflared", [
730
- "tunnel",
731
- "--url",
732
- "http://localhost:8787",
733
- "--metrics",
734
- "localhost:8789",
735
- ]);
736
-
737
- tunnel.current.on("close", (code) => {
738
- if (code !== 0) {
739
- console.log(`Tunnel process exited with code ${code}`);
740
- }
741
- });
742
-
743
- removeSignalExitListener.current = onExit((_code, _signal) => {
744
- console.log("⎔ Shutting down local tunnel.");
745
- tunnel.current?.kill();
746
- tunnel.current = undefined;
747
- });
748
-
749
- const hostName = await findTunnelHostname();
750
- await clipboardy.write(hostName);
751
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
752
- }
753
- }
754
-
755
- startTunnel().catch((err) => {
756
- console.error("tunnel:", err);
757
- });
758
-
759
- return () => {
760
- if (tunnel.current) {
761
- console.log("⎔ Shutting down tunnel.");
762
- tunnel.current?.kill();
763
- tunnel.current = undefined;
764
- removeSignalExitListener.current && removeSignalExitListener.current();
765
- removeSignalExitListener.current = undefined;
766
- }
767
- };
768
- }, [toggle]);
769
- }
770
-
771
- type useHotkeysInitialState = {
772
- local: boolean;
773
- tunnel: boolean;
774
- };
775
- function useHotkeys(initial: useHotkeysInitialState, port: number) {
776
- // UGH, we should put port in context instead
777
- const [toggles, setToggles] = useState(initial);
778
- useInput(
779
- async (
780
- input,
781
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
782
- key
783
- ) => {
784
- switch (input.toLowerCase()) {
785
- // open browser
786
- case "b":
787
- await open(`http://localhost:${port}/`);
788
- break;
789
- // toggle inspector
790
- case "d":
791
- await open(
792
- `https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
793
- );
794
- break;
795
- // toggle tunnel
796
- case "s":
797
- setToggles((previousToggles) => ({
798
- ...previousToggles,
799
- tunnel: !previousToggles.tunnel,
800
- }));
801
- break;
802
- // toggle local
803
- case "l":
804
- setToggles((previousToggles) => ({
805
- ...previousToggles,
806
- local: !previousToggles.local,
807
- }));
808
- break;
809
- // shut down
810
- case "q":
811
- case "x":
812
- process.exit(0);
813
- break;
814
- default:
815
- // nothing?
816
- break;
817
- }
818
- }
819
- );
820
- return toggles;
821
- }
822
-
823
- function ErrorFallback(props: { error: Error }) {
824
- const { exit } = useApp();
825
- useEffect(() => exit(new Error()));
826
- return (
827
- <>
828
- <Text>Something went wrong:</Text>
829
- <Text>{props.error.stack}</Text>
830
- </>
831
- );
832
- }
833
-
834
- export default withErrorBoundary(Dev, { FallbackComponent: ErrorFallback });