wrangler 0.0.0-e928f94 → 0.0.0-e978986

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 (124) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +48 -4
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +74 -34
  6. package/pages/functions/buildPlugin.ts +105 -0
  7. package/pages/functions/buildWorker.ts +151 -0
  8. package/pages/functions/filepath-routing.test.ts +234 -0
  9. package/pages/functions/filepath-routing.ts +189 -0
  10. package/pages/functions/identifiers.ts +78 -0
  11. package/pages/functions/routes.ts +156 -0
  12. package/pages/functions/template-plugin.ts +147 -0
  13. package/pages/functions/template-worker.ts +143 -0
  14. package/src/__tests__/config-cache.test.ts +36 -0
  15. package/src/__tests__/configuration.test.ts +3374 -0
  16. package/src/__tests__/dev.test.tsx +980 -0
  17. package/src/__tests__/guess-worker-format.test.ts +85 -0
  18. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  19. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  20. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  21. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  22. package/src/__tests__/helpers/mock-bin.ts +36 -0
  23. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  24. package/src/__tests__/helpers/mock-console.ts +87 -0
  25. package/src/__tests__/helpers/mock-dialogs.ts +130 -0
  26. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  27. package/src/__tests__/helpers/mock-istty.ts +27 -0
  28. package/src/__tests__/helpers/mock-kv.ts +33 -0
  29. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  31. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  32. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  33. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  34. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  35. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  36. package/src/__tests__/https-options.test.ts +130 -0
  37. package/src/__tests__/index.test.ts +233 -130
  38. package/src/__tests__/init.test.ts +1567 -0
  39. package/src/__tests__/jest.setup.ts +77 -0
  40. package/src/__tests__/kv.test.ts +1481 -0
  41. package/src/__tests__/logger.test.ts +115 -0
  42. package/src/__tests__/package-manager.test.ts +353 -0
  43. package/src/__tests__/pages.test.ts +657 -0
  44. package/src/__tests__/parse.test.ts +330 -0
  45. package/src/__tests__/publish.test.ts +5468 -0
  46. package/src/__tests__/r2.test.ts +233 -0
  47. package/src/__tests__/route.test.ts +45 -0
  48. package/src/__tests__/secret.test.ts +481 -0
  49. package/src/__tests__/tail.test.ts +690 -0
  50. package/src/__tests__/user.test.ts +131 -0
  51. package/src/__tests__/whoami.test.tsx +105 -0
  52. package/src/abort.d.ts +3 -0
  53. package/src/bundle.ts +200 -0
  54. package/src/cfetch/index.ts +121 -0
  55. package/src/cfetch/internal.ts +145 -0
  56. package/src/cli.ts +10 -7
  57. package/src/config/README.md +107 -0
  58. package/src/config/config.ts +234 -0
  59. package/src/config/diagnostics.ts +80 -0
  60. package/src/config/environment.ts +420 -0
  61. package/src/config/index.ts +225 -0
  62. package/src/config/validation-helpers.ts +575 -0
  63. package/src/config/validation.ts +1539 -0
  64. package/src/config-cache.ts +45 -0
  65. package/src/create-worker-preview.ts +185 -0
  66. package/src/create-worker-upload-form.ts +254 -0
  67. package/src/dev/dev-vars.ts +36 -0
  68. package/src/dev/dev.tsx +419 -0
  69. package/src/dev/local.tsx +318 -0
  70. package/src/dev/remote.tsx +227 -0
  71. package/src/dev/use-esbuild.ts +118 -0
  72. package/src/dialogs.tsx +67 -17
  73. package/src/durable.ts +102 -0
  74. package/src/entry.ts +322 -0
  75. package/src/environment-variables.ts +35 -0
  76. package/src/errors.ts +11 -0
  77. package/src/https-options.ts +123 -0
  78. package/src/index.tsx +2031 -1041
  79. package/src/inspect.ts +662 -0
  80. package/src/intl-polyfill.d.ts +139 -0
  81. package/src/kv.ts +408 -0
  82. package/src/logger.ts +66 -0
  83. package/src/miniflare-cli/README.md +30 -0
  84. package/src/miniflare-cli/enum-keys.ts +17 -0
  85. package/src/miniflare-cli/index.ts +41 -0
  86. package/src/miniflare-cli/request-context.ts +40 -0
  87. package/src/module-collection.ts +229 -35
  88. package/src/open-in-browser.ts +19 -0
  89. package/src/package-manager.ts +174 -0
  90. package/src/pages.tsx +1444 -260
  91. package/src/parse.ts +202 -0
  92. package/src/paths.ts +26 -0
  93. package/src/proxy.ts +465 -0
  94. package/src/publish.ts +498 -261
  95. package/src/r2.ts +50 -0
  96. package/src/selfsigned.d.ts +29 -0
  97. package/src/sites.tsx +240 -60
  98. package/src/tail/filters.ts +279 -0
  99. package/src/tail/index.ts +299 -0
  100. package/src/tail/printing.ts +67 -0
  101. package/src/update-check.ts +19 -0
  102. package/src/user.tsx +395 -221
  103. package/src/whoami.tsx +70 -0
  104. package/src/worker.ts +180 -0
  105. package/templates/gitignore +171 -0
  106. package/templates/new-worker-scheduled.js +17 -0
  107. package/templates/new-worker-scheduled.ts +32 -0
  108. package/templates/new-worker.js +15 -0
  109. package/templates/new-worker.ts +30 -0
  110. package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
  111. package/templates/tsconfig.json +105 -0
  112. package/wrangler-dist/cli.js +118298 -116056
  113. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  114. package/src/__tests__/mock-cfetch.js +0 -46
  115. package/src/api/form_data.ts +0 -141
  116. package/src/api/inspect.ts +0 -441
  117. package/src/api/preview.ts +0 -128
  118. package/src/api/worker.ts +0 -161
  119. package/src/cfetch.ts +0 -72
  120. package/src/config.ts +0 -122
  121. package/src/dev.tsx +0 -724
  122. package/src/kv.tsx +0 -211
  123. package/src/tail.tsx +0 -71
  124. package/wrangler-dist/cli.js.map +0 -7
package/src/parse.ts ADDED
@@ -0,0 +1,202 @@
1
+ import * as fs from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import TOML from "@iarna/toml";
4
+ import { formatMessagesSync } from "esbuild";
5
+
6
+ export type Message = {
7
+ text: string;
8
+ location?: Location;
9
+ notes?: Message[];
10
+ kind?: "warning" | "error";
11
+ };
12
+
13
+ export type Location = File & {
14
+ line: number;
15
+ column: number;
16
+ length?: number;
17
+ lineText?: string;
18
+ suggestion?: string;
19
+ };
20
+
21
+ export type File = {
22
+ file?: string;
23
+ fileText?: string;
24
+ };
25
+
26
+ /**
27
+ * Formats a `Message` using esbuild's pretty-printing algorithm.
28
+ */
29
+ export function formatMessage(
30
+ { text, notes, location, kind = "error" }: Message,
31
+ color = true
32
+ ): string {
33
+ const input = { text, notes, location };
34
+ delete input.location?.fileText;
35
+ for (const note of notes ?? []) {
36
+ delete note.location?.fileText;
37
+ }
38
+ const lines = formatMessagesSync([input], {
39
+ color,
40
+ kind: kind,
41
+ terminalWidth: process.stderr.columns,
42
+ });
43
+ return lines.join("\n");
44
+ }
45
+
46
+ /**
47
+ * An error that's thrown when something fails to parse.
48
+ */
49
+ export class ParseError extends Error implements Message {
50
+ readonly text: string;
51
+ readonly notes: Message[];
52
+ readonly location?: Location;
53
+ readonly kind: "warning" | "error";
54
+
55
+ constructor({ text, notes, location, kind }: Message) {
56
+ super(text);
57
+ this.name = this.constructor.name;
58
+ this.text = text;
59
+ this.notes = notes ?? [];
60
+ this.location = location;
61
+ this.kind = kind ?? "error";
62
+ }
63
+ }
64
+
65
+ const TOML_ERROR_NAME = "TomlError";
66
+ const TOML_ERROR_SUFFIX = " at row ";
67
+
68
+ type TomlError = Error & {
69
+ line: number;
70
+ col: number;
71
+ };
72
+
73
+ /**
74
+ * A wrapper around `TOML.parse` that throws a `ParseError`.
75
+ */
76
+ export function parseTOML(input: string, file?: string): TOML.JsonMap | never {
77
+ try {
78
+ // Normalize CRLF to LF to avoid hitting https://github.com/iarna/iarna-toml/issues/33.
79
+ const normalizedInput = input.replace(/\r\n/g, "\n");
80
+ return TOML.parse(normalizedInput);
81
+ } catch (err) {
82
+ const { name, message, line, col } = err as TomlError;
83
+ if (name !== TOML_ERROR_NAME) {
84
+ throw err;
85
+ }
86
+ const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
87
+ const lineText = input.split("\n")[line];
88
+ const location = {
89
+ lineText,
90
+ line: line + 1,
91
+ column: col - 1,
92
+ file,
93
+ fileText: input,
94
+ };
95
+ throw new ParseError({ text, location });
96
+ }
97
+ }
98
+
99
+ const JSON_ERROR_SUFFIX = " in JSON at position ";
100
+
101
+ /**
102
+ * A minimal type describing a package.json file.
103
+ */
104
+ export type PackageJSON = {
105
+ devDependencies?: Record<string, unknown>;
106
+ dependencies?: Record<string, unknown>;
107
+ scripts?: Record<string, unknown>;
108
+ };
109
+
110
+ /**
111
+ * A typed version of `parseJSON()`.
112
+ */
113
+ export function parsePackageJSON<T extends PackageJSON = PackageJSON>(
114
+ input: string,
115
+ file?: string
116
+ ): T {
117
+ return parseJSON<T>(input, file);
118
+ }
119
+
120
+ /**
121
+ * A wrapper around `JSON.parse` that throws a `ParseError`.
122
+ */
123
+ export function parseJSON<T>(input: string, file?: string): T {
124
+ try {
125
+ return JSON.parse(input);
126
+ } catch (err) {
127
+ const { message } = err as Error;
128
+ const index = message.lastIndexOf(JSON_ERROR_SUFFIX);
129
+ if (index < 0) {
130
+ throw err;
131
+ }
132
+ const text = message.substring(0, index);
133
+ const position = parseInt(
134
+ message.substring(index + JSON_ERROR_SUFFIX.length)
135
+ );
136
+ const location = indexLocation({ file, fileText: input }, position);
137
+ throw new ParseError({ text, location });
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Reads a file and parses it based on its type.
143
+ */
144
+ export function readFileSync(file: string): string {
145
+ try {
146
+ return fs.readFileSync(file, { encoding: "utf-8" });
147
+ } catch (err) {
148
+ const { message } = err as Error;
149
+ throw new ParseError({
150
+ text: `Could not read file: ${file}`,
151
+ notes: [
152
+ {
153
+ text: message.replace(file, resolve(file)),
154
+ },
155
+ ],
156
+ });
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Calculates the line and column location from an index.
162
+ */
163
+ export function indexLocation(file: File, index: number): Location {
164
+ let lineText,
165
+ line = 0,
166
+ column = 0,
167
+ cursor = 0;
168
+ const { fileText = "" } = file;
169
+ for (const row of fileText.split("\n")) {
170
+ line++;
171
+ cursor += row.length + 1;
172
+ if (cursor >= index) {
173
+ lineText = row;
174
+ column = row.length - (cursor - index);
175
+ break;
176
+ }
177
+ }
178
+ return { lineText, line, column, ...file };
179
+ }
180
+
181
+ /**
182
+ * Guesses the line and column location of a search query.
183
+ */
184
+ export function searchLocation(file: File, query: unknown): Location {
185
+ let lineText,
186
+ length,
187
+ line = 0,
188
+ column = 0;
189
+ const queryText = String(query);
190
+ const { fileText = "" } = file;
191
+ for (const content of fileText.split("\n")) {
192
+ line++;
193
+ const index = content.indexOf(queryText);
194
+ if (index >= 0) {
195
+ lineText = content;
196
+ column = index;
197
+ length = queryText.length;
198
+ break;
199
+ }
200
+ }
201
+ return { lineText, line, column, length, ...file };
202
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { assert } from "console";
2
+
3
+ type DiscriminatedPath<Discriminator extends string> = string & {
4
+ _discriminator: Discriminator;
5
+ };
6
+
7
+ /**
8
+ * A branded string that expects to be URL compatible.
9
+ *
10
+ * Require this type when you want callers to ensure that they have converted file-path strings into URL-safe paths.
11
+ */
12
+ export type UrlPath = DiscriminatedPath<"UrlPath">;
13
+
14
+ /**
15
+ * Convert a file-path string to a URL-path string.
16
+ *
17
+ * Use this helper to convert a `string` to a `UrlPath` when it is not clear whether the string needs normalizing.
18
+ * Replaces all back-slashes with forward-slashes, and throws an error if the path contains a drive letter (e.g. `C:`).
19
+ */
20
+ export function toUrlPath(path: string): UrlPath {
21
+ assert(
22
+ !/^[a-z]:/i.test(path),
23
+ "Tried to convert a Windows file path with a drive to a URL path."
24
+ );
25
+ return path.replace(/\\/g, "/") as UrlPath;
26
+ }
package/src/proxy.ts ADDED
@@ -0,0 +1,465 @@
1
+ import { createServer as createHttpServer } from "node:http";
2
+ import { connect } from "node:http2";
3
+ import { createServer as createHttpsServer } from "node:https";
4
+ import WebSocket from "faye-websocket";
5
+ import { createHttpTerminator } from "http-terminator";
6
+ import { useEffect, useRef, useState } from "react";
7
+ import serveStatic from "serve-static";
8
+ import { getHttpsOptions } from "./https-options";
9
+ import { logger } from "./logger";
10
+ import type { CfPreviewToken } from "./create-worker-preview";
11
+ import type { HttpTerminator } from "http-terminator";
12
+ import type {
13
+ IncomingHttpHeaders,
14
+ RequestListener,
15
+ IncomingMessage,
16
+ ServerResponse,
17
+ Server as HttpServer,
18
+ } from "node:http";
19
+ import type { ClientHttp2Session, ServerHttp2Stream } from "node:http2";
20
+ import type { Server as HttpsServer } from "node:https";
21
+ import type ws from "ws";
22
+
23
+ interface IWebsocket extends ws {
24
+ // Pipe implements .on("message", ...)
25
+ pipe<T>(fn: T): IWebsocket;
26
+ }
27
+
28
+ /**
29
+ * `usePreviewServer` is a React hook that creates a local development
30
+ * server that can be used to develop a Worker.
31
+ *
32
+ * When we run `wrangler dev`, we start by uploading the compiled worker
33
+ * to the preview service, which responds with a preview token.
34
+ * (see `useWorker`/`createWorker` for details.)
35
+ * We can then use that token to connect to the preview server for a
36
+ * great local development experience. Further, as we change the worker,
37
+ * we can update the preview token transparently without having to restart
38
+ * the development server.
39
+ */
40
+
41
+ /** Rewrite request headers to add the preview token. */
42
+ function addCfPreviewTokenHeader(
43
+ headers: IncomingHttpHeaders,
44
+ previewTokenValue: string
45
+ ) {
46
+ headers["cf-workers-preview-token"] = previewTokenValue;
47
+ }
48
+
49
+ /**
50
+ * Rewrite references in request headers
51
+ * from the preview host to the local host.
52
+ */
53
+ function rewriteRemoteHostToLocalHostInHeaders(
54
+ headers: IncomingHttpHeaders,
55
+ remoteHost: string,
56
+ localPort: number,
57
+ localProtocol: "https" | "http"
58
+ ) {
59
+ for (const [name, value] of Object.entries(headers)) {
60
+ // Rewrite the remote host to the local host.
61
+ if (typeof value === "string" && value.includes(remoteHost)) {
62
+ headers[name] = value
63
+ .replaceAll(
64
+ `https://${remoteHost}`,
65
+ `${localProtocol}://localhost:${localPort}`
66
+ )
67
+ .replaceAll(remoteHost, `localhost:${localPort}`);
68
+ }
69
+ }
70
+ }
71
+
72
+ type PreviewProxy = {
73
+ server: HttpServer | HttpsServer;
74
+ terminator: HttpTerminator;
75
+ };
76
+
77
+ export function usePreviewServer({
78
+ previewToken,
79
+ publicRoot,
80
+ localProtocol,
81
+ localPort: port,
82
+ ip,
83
+ }: {
84
+ previewToken: CfPreviewToken | undefined;
85
+ publicRoot: string | undefined;
86
+ localProtocol: "https" | "http";
87
+ localPort: number;
88
+ ip: string;
89
+ }) {
90
+ /** Creates an HTTP/1 proxy that sends requests over HTTP/2. */
91
+ const [proxy, setProxy] = useState<PreviewProxy>();
92
+
93
+ /**
94
+ * Create the instance of the local proxy server that will pass on
95
+ * requests to the preview worker.
96
+ */
97
+ useEffect(() => {
98
+ if (proxy === undefined) {
99
+ createProxyServer(localProtocol)
100
+ .then((server) => {
101
+ setProxy({
102
+ server,
103
+ terminator: createHttpTerminator({ server }),
104
+ });
105
+ })
106
+ .catch(async (err) => {
107
+ logger.error("Failed to create proxy server:", err);
108
+ });
109
+ }
110
+ }, [proxy, localProtocol]);
111
+
112
+ /**
113
+ * When we're not connected / getting a fresh token on changes,
114
+ * we'd like to buffer streams/requests until we're connected.
115
+ * Once connected, we can flush the buffered streams/requests.
116
+ * streamBufferRef is used to buffer http/2 streams, while
117
+ * requestResponseBufferRef is used to buffer http/1 requests.
118
+ */
119
+ const streamBufferRef = useRef<
120
+ { stream: ServerHttp2Stream; headers: IncomingHttpHeaders }[]
121
+ >([]);
122
+ const requestResponseBufferRef = useRef<
123
+ { request: IncomingMessage; response: ServerResponse }[]
124
+ >([]);
125
+
126
+ /**
127
+ * The session doesn't last forever, and will eventually drop
128
+ * (usually within 5-15 minutes). When that happens, we simply
129
+ * restart the effect, effectively restarting the server. We use
130
+ * a state sigil as an effect dependency to do so.
131
+ */
132
+ const [retryServerSetupSigil, setRetryServerSetupSigil] = useState<number>(0);
133
+ function retryServerSetup() {
134
+ setRetryServerSetupSigil((x) => x + 1);
135
+ }
136
+
137
+ useEffect(() => {
138
+ if (proxy === undefined) {
139
+ return;
140
+ }
141
+
142
+ // If we don't have a token, that means either we're just starting up,
143
+ // or we're refreshing the token.
144
+ if (!previewToken) {
145
+ const cleanupListeners: (() => void)[] = [];
146
+ const bufferStream = (
147
+ stream: ServerHttp2Stream,
148
+ headers: IncomingHttpHeaders
149
+ ) => {
150
+ // store the stream in a buffer so we can replay it later
151
+ streamBufferRef.current.push({ stream, headers });
152
+ };
153
+ proxy.server.on("stream", bufferStream);
154
+ cleanupListeners.push(() => proxy.server.off("stream", bufferStream));
155
+
156
+ const bufferRequestResponse = (
157
+ request: IncomingMessage,
158
+ response: ServerResponse
159
+ ) => {
160
+ // store the request and response in a buffer so we can replay it later
161
+ requestResponseBufferRef.current.push({ request, response });
162
+ };
163
+
164
+ proxy.server.on("request", bufferRequestResponse);
165
+ cleanupListeners.push(() =>
166
+ proxy.server.off("request", bufferRequestResponse)
167
+ );
168
+ return () => {
169
+ cleanupListeners.forEach((cleanup) => cleanup());
170
+ };
171
+ }
172
+
173
+ // We have a token. Let's proxy requests to the preview end point.
174
+ const cleanupListeners: (() => void)[] = [];
175
+
176
+ const assetPath = typeof publicRoot === "string" ? publicRoot : null;
177
+
178
+ // create a ClientHttp2Session
179
+ const remote = connect(`https://${previewToken.host}`);
180
+ cleanupListeners.push(() => remote.destroy());
181
+
182
+ // As mentioned above, the session may die at any point,
183
+ // so we need to restart the effect.
184
+ remote.on("close", retryServerSetup);
185
+ cleanupListeners.push(() => remote.off("close", retryServerSetup));
186
+
187
+ /** HTTP/2 -> HTTP/2 */
188
+ const handleStream = createStreamHandler(
189
+ previewToken,
190
+ remote,
191
+ port,
192
+ localProtocol
193
+ );
194
+ proxy.server.on("stream", handleStream);
195
+ cleanupListeners.push(() => proxy.server.off("stream", handleStream));
196
+
197
+ // flush and replay buffered streams
198
+ streamBufferRef.current.forEach((buffer) =>
199
+ handleStream(buffer.stream, buffer.headers)
200
+ );
201
+ streamBufferRef.current = [];
202
+
203
+ /** HTTP/1 -> HTTP/2 */
204
+ const handleRequest: RequestListener = (
205
+ message: IncomingMessage,
206
+ response: ServerResponse
207
+ ) => {
208
+ const { httpVersionMajor, headers, method, url } = message;
209
+ if (httpVersionMajor >= 2) {
210
+ return; // Already handled by the "stream" event.
211
+ }
212
+ addCfPreviewTokenHeader(headers, previewToken.value);
213
+ headers[":method"] = method;
214
+ headers[":path"] = url;
215
+ headers[":authority"] = previewToken.host;
216
+ headers[":scheme"] = "https";
217
+ for (const name of Object.keys(headers)) {
218
+ if (HTTP1_HEADERS.has(name.toLowerCase())) {
219
+ delete headers[name];
220
+ }
221
+ }
222
+ const request = message.pipe(remote.request(headers));
223
+ request.on("response", (responseHeaders) => {
224
+ const status = responseHeaders[":status"] ?? 500;
225
+
226
+ // log all requests to terminal
227
+ logger.log(new Date().toLocaleTimeString(), method, url, status);
228
+
229
+ rewriteRemoteHostToLocalHostInHeaders(
230
+ responseHeaders,
231
+ previewToken.host,
232
+ port,
233
+ localProtocol
234
+ );
235
+ for (const name of Object.keys(responseHeaders)) {
236
+ if (name.startsWith(":")) {
237
+ delete responseHeaders[name];
238
+ }
239
+ }
240
+ response.writeHead(status, responseHeaders);
241
+ request.pipe(response, { end: true });
242
+ });
243
+ };
244
+
245
+ // If an asset path is defined, check the file system
246
+ // for a file first and serve if it exists.
247
+ const actualHandleRequest = assetPath
248
+ ? createHandleAssetsRequest(assetPath, handleRequest)
249
+ : handleRequest;
250
+
251
+ proxy.server.on("request", actualHandleRequest);
252
+ cleanupListeners.push(() =>
253
+ proxy.server.off("request", actualHandleRequest)
254
+ );
255
+
256
+ // flush and replay buffered requests
257
+ requestResponseBufferRef.current.forEach(({ request, response }) =>
258
+ actualHandleRequest(request, response)
259
+ );
260
+ requestResponseBufferRef.current = [];
261
+
262
+ /** HTTP/1 -> WebSocket (over HTTP/1) */
263
+ const handleUpgrade = (
264
+ message: IncomingMessage,
265
+ socket: WebSocket,
266
+ body: Buffer
267
+ ) => {
268
+ const { headers, url } = message;
269
+ addCfPreviewTokenHeader(headers, previewToken.value);
270
+ headers["host"] = previewToken.host;
271
+ const localWebsocket = new WebSocket(message, socket, body) as IWebsocket;
272
+ // TODO(soon): Custom WebSocket protocol is not working?
273
+ const remoteWebsocketClient = new WebSocket.Client(
274
+ `wss://${previewToken.host}${url}`,
275
+ [],
276
+ { headers }
277
+ ) as IWebsocket;
278
+ localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
279
+ // We close down websockets whenever we refresh the token.
280
+ cleanupListeners.push(() => {
281
+ localWebsocket.close();
282
+ remoteWebsocketClient.close();
283
+ });
284
+ };
285
+ proxy.server.on("upgrade", handleUpgrade);
286
+ cleanupListeners.push(() => proxy.server.off("upgrade", handleUpgrade));
287
+
288
+ return () => {
289
+ cleanupListeners.forEach((cleanup) => cleanup());
290
+ };
291
+ }, [
292
+ previewToken,
293
+ publicRoot,
294
+ port,
295
+ localProtocol,
296
+ proxy,
297
+ // We use a state value as a sigil to trigger reconnecting the server.
298
+ // It's not used inside the effect, so react-hooks/exhaustive-deps
299
+ // doesn't complain if it's not included in the dependency array.
300
+ // But its presence is critical, so Do NOT remove it from the dependency list.
301
+ retryServerSetupSigil,
302
+ ]);
303
+
304
+ // Start/stop the server whenever the
305
+ // containing component is mounted/unmounted.
306
+ useEffect(() => {
307
+ const abortController = new AbortController();
308
+ if (proxy === undefined) {
309
+ return;
310
+ }
311
+
312
+ waitForPortToBeAvailable(port, {
313
+ retryPeriod: 200,
314
+ timeout: 2000,
315
+ abortSignal: abortController.signal,
316
+ })
317
+ .then(() => {
318
+ proxy.server.on("listening", () => {
319
+ logger.log(`⬣ Listening at ${localProtocol}://${ip}:${port}`);
320
+ });
321
+ proxy.server.listen(port, ip);
322
+ })
323
+ .catch((err) => {
324
+ if ((err as { code: string }).code !== "ABORT_ERR") {
325
+ logger.error(`Failed to start server: ${err}`);
326
+ }
327
+ });
328
+
329
+ return () => {
330
+ abortController.abort();
331
+ // Running `proxy.server.close()` does not close open connections, preventing the process from exiting.
332
+ // So we use this `terminator` to close all the connections and force the server to shutdown.
333
+ proxy.terminator.terminate();
334
+ };
335
+ }, [port, ip, proxy, localProtocol]);
336
+ }
337
+
338
+ function createHandleAssetsRequest(
339
+ assetPath: string,
340
+ handleRequest: RequestListener
341
+ ) {
342
+ const handleAsset = serveStatic(assetPath, {
343
+ cacheControl: false,
344
+ });
345
+ return (request: IncomingMessage, response: ServerResponse) => {
346
+ handleAsset(request, response, () => {
347
+ handleRequest(request, response);
348
+ });
349
+ };
350
+ }
351
+
352
+ /** A Set of headers we want to remove from HTTP/1 requests. */
353
+ const HTTP1_HEADERS = new Set([
354
+ "host",
355
+ "connection",
356
+ "upgrade",
357
+ "keep-alive",
358
+ "proxy-connection",
359
+ "transfer-encoding",
360
+ "http2-settings",
361
+ ]);
362
+
363
+ async function createProxyServer(
364
+ localProtocol: "https" | "http"
365
+ ): Promise<HttpServer | HttpsServer> {
366
+ const server: HttpServer | HttpsServer =
367
+ localProtocol === "https"
368
+ ? createHttpsServer(await getHttpsOptions())
369
+ : createHttpServer();
370
+
371
+ return server
372
+ .on("upgrade", (req) => {
373
+ // log all websocket connections
374
+ logger.log(
375
+ new Date().toLocaleTimeString(),
376
+ req.method,
377
+ req.url,
378
+ 101,
379
+ "(WebSocket)"
380
+ );
381
+ })
382
+ .on("error", (err) => {
383
+ // log all connection errors
384
+ logger.error(new Date().toLocaleTimeString(), err);
385
+ });
386
+ }
387
+
388
+ function createStreamHandler(
389
+ previewToken: CfPreviewToken,
390
+ remote: ClientHttp2Session,
391
+ localPort: number,
392
+ localProtocol: "https" | "http"
393
+ ) {
394
+ return function handleStream(
395
+ stream: ServerHttp2Stream,
396
+ headers: IncomingHttpHeaders
397
+ ) {
398
+ addCfPreviewTokenHeader(headers, previewToken.value);
399
+ headers[":authority"] = previewToken.host;
400
+ const request = stream.pipe(remote.request(headers));
401
+ request.on("response", (responseHeaders: IncomingHttpHeaders) => {
402
+ rewriteRemoteHostToLocalHostInHeaders(
403
+ responseHeaders,
404
+ previewToken.host,
405
+ localPort,
406
+ localProtocol
407
+ );
408
+ stream.respond(responseHeaders);
409
+ request.pipe(stream, { end: true });
410
+ });
411
+ };
412
+ }
413
+
414
+ /**
415
+ * A helper function that waits for a port to be available.
416
+ */
417
+ export async function waitForPortToBeAvailable(
418
+ port: number,
419
+ options: { retryPeriod: number; timeout: number; abortSignal: AbortSignal }
420
+ ): Promise<void> {
421
+ return new Promise((resolve, reject) => {
422
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
423
+ options.abortSignal.addEventListener("abort", () => {
424
+ const abortError = new Error("waitForPortToBeAvailable() aborted");
425
+ (abortError as Error & { code: string }).code = "ABORT_ERR";
426
+ doReject(abortError);
427
+ });
428
+
429
+ const timeout = setTimeout(() => {
430
+ doReject(new Error(`Timed out waiting for port ${port}`));
431
+ }, options.timeout);
432
+
433
+ const interval = setInterval(checkPort, options.retryPeriod);
434
+ checkPort();
435
+
436
+ function doResolve() {
437
+ clearTimeout(timeout);
438
+ clearInterval(interval);
439
+ resolve();
440
+ }
441
+
442
+ function doReject(err: unknown) {
443
+ clearInterval(interval);
444
+ clearTimeout(timeout);
445
+ reject(err);
446
+ }
447
+
448
+ function checkPort() {
449
+ // Testing whether a port is 'available' involves simply
450
+ // trying to make a server listen on that port, and retrying
451
+ // until it succeeds.
452
+ const server = createHttpServer();
453
+ server.on("error", (err) => {
454
+ // @ts-expect-error non standard property on Error
455
+ if (err.code !== "EADDRINUSE") {
456
+ doReject(err);
457
+ }
458
+ });
459
+ server.listen(port, () => {
460
+ server.close();
461
+ doResolve();
462
+ });
463
+ }
464
+ });
465
+ }