wrangler 0.0.0-e0d2f35 → 0.0.0-e178d6fb

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