wrangler 0.0.0-de73fa2 → 0.0.0-e0b9366

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 (94) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +33 -15
  3. package/pages/functions/buildWorker.ts +1 -1
  4. package/pages/functions/filepath-routing.test.ts +212 -28
  5. package/pages/functions/filepath-routing.ts +91 -131
  6. package/pages/functions/routes.ts +11 -18
  7. package/pages/functions/template-worker.ts +19 -33
  8. package/src/__tests__/configuration.test.ts +2551 -0
  9. package/src/__tests__/dev.test.tsx +393 -59
  10. package/src/__tests__/dev2.test.tsx +152 -0
  11. package/src/__tests__/guess-worker-format.test.ts +58 -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/faye-websocket.d.ts +6 -0
  15. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  16. package/src/__tests__/helpers/mock-bin.ts +36 -0
  17. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +52 -16
  18. package/src/__tests__/helpers/mock-console.ts +70 -0
  19. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  20. package/src/__tests__/helpers/mock-kv.ts +33 -0
  21. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  22. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  23. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  24. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  25. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  26. package/src/__tests__/https-options.test.ts +127 -0
  27. package/src/__tests__/index.test.ts +779 -75
  28. package/src/__tests__/jest.setup.ts +53 -6
  29. package/src/__tests__/kv.test.ts +713 -442
  30. package/src/__tests__/logout.test.ts +52 -0
  31. package/src/__tests__/package-manager.test.ts +206 -0
  32. package/src/__tests__/pages.test.ts +44 -0
  33. package/src/__tests__/parse.test.ts +322 -0
  34. package/src/__tests__/publish.test.ts +2611 -0
  35. package/src/__tests__/r2.test.ts +198 -0
  36. package/src/__tests__/route.test.ts +45 -0
  37. package/src/__tests__/secret.test.ts +425 -0
  38. package/src/__tests__/sentry.test.ts +146 -0
  39. package/src/__tests__/tail.test.ts +564 -0
  40. package/src/__tests__/whoami.test.tsx +100 -0
  41. package/src/bundle.ts +142 -0
  42. package/src/cfetch/index.ts +21 -19
  43. package/src/cfetch/internal.ts +92 -22
  44. package/src/cli.ts +10 -0
  45. package/src/config/README.md +107 -0
  46. package/src/config/config.ts +279 -0
  47. package/src/config/diagnostics.ts +80 -0
  48. package/src/config/environment.ts +305 -0
  49. package/src/config/index.ts +52 -0
  50. package/src/config/validation-helpers.ts +468 -0
  51. package/src/config/validation.ts +1037 -0
  52. package/src/{api/preview.ts → create-worker-preview.ts} +61 -23
  53. package/src/create-worker-upload-form.ts +217 -0
  54. package/src/dev/dev.tsx +357 -0
  55. package/src/dev/local.tsx +241 -0
  56. package/src/dev/remote.tsx +201 -0
  57. package/src/dev/use-esbuild.ts +100 -0
  58. package/src/dialogs.tsx +2 -2
  59. package/src/entry.ts +159 -0
  60. package/src/environment-variables.ts +33 -0
  61. package/src/https-options.ts +122 -0
  62. package/src/index.tsx +1181 -791
  63. package/src/inspect.ts +103 -25
  64. package/src/{kv.tsx → kv.ts} +119 -56
  65. package/src/module-collection.ts +215 -26
  66. package/src/open-in-browser.ts +25 -0
  67. package/src/package-manager.ts +126 -0
  68. package/src/pages.tsx +49 -35
  69. package/src/parse.ts +183 -0
  70. package/src/paths.ts +26 -0
  71. package/src/proxy.ts +175 -39
  72. package/src/publish.ts +291 -301
  73. package/src/r2.ts +50 -0
  74. package/src/reporting.ts +131 -0
  75. package/src/selfsigned.d.ts +29 -0
  76. package/src/sites.tsx +217 -62
  77. package/src/tail/filters.ts +279 -0
  78. package/src/tail/index.ts +299 -0
  79. package/src/tail/printing.ts +62 -0
  80. package/src/user.tsx +268 -177
  81. package/src/whoami.tsx +69 -0
  82. package/src/{api/worker.ts → worker.ts} +45 -37
  83. package/templates/new-worker.js +15 -0
  84. package/templates/new-worker.ts +15 -0
  85. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  86. package/templates/tsconfig.json +105 -0
  87. package/wrangler-dist/cli.js +130804 -112757
  88. package/wrangler-dist/cli.js.map +3 -3
  89. package/src/__tests__/run-in-tmp.ts +0 -19
  90. package/src/__tests__/run-wrangler.ts +0 -32
  91. package/src/api/form_data.ts +0 -131
  92. package/src/config.ts +0 -487
  93. package/src/dev.tsx +0 -786
  94. package/src/tail.tsx +0 -73
package/src/parse.ts ADDED
@@ -0,0 +1,183 @@
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
+ /* eslint-disable @typescript-eslint/no-explicit-any */
66
+
67
+ const TOML_ERROR_NAME = "TomlError";
68
+ const TOML_ERROR_SUFFIX = " at row ";
69
+
70
+ type TomlError = Error & {
71
+ line: number;
72
+ col: number;
73
+ };
74
+
75
+ /**
76
+ * A wrapper around `TOML.parse` that throws a `ParseError`.
77
+ */
78
+ export function parseTOML(input: string, file?: string): object {
79
+ try {
80
+ return TOML.parse(input);
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 wrapper around `JSON.parse` that throws a `ParseError`.
103
+ */
104
+ export function parseJSON(input: string, file?: string): any {
105
+ try {
106
+ return JSON.parse(input);
107
+ } catch (err) {
108
+ const { message } = err as Error;
109
+ const index = message.lastIndexOf(JSON_ERROR_SUFFIX);
110
+ if (index < 0) {
111
+ throw err;
112
+ }
113
+ const text = message.substring(0, index);
114
+ const position = parseInt(
115
+ message.substring(index + JSON_ERROR_SUFFIX.length)
116
+ );
117
+ const location = indexLocation({ file, fileText: input }, position);
118
+ throw new ParseError({ text, location });
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Reads a file and parses it based on its type.
124
+ */
125
+ export function readFileSync(file: string): string {
126
+ try {
127
+ return fs.readFileSync(file, { encoding: "utf-8" });
128
+ } catch (err) {
129
+ const { message } = err as Error;
130
+ throw new ParseError({
131
+ text: `Could not read file: ${file}`,
132
+ notes: [
133
+ {
134
+ text: message.replace(file, resolve(file)),
135
+ },
136
+ ],
137
+ });
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Calculates the line and column location from an index.
143
+ */
144
+ export function indexLocation(file: File, index: number): Location {
145
+ let lineText,
146
+ line = 0,
147
+ column = 0,
148
+ cursor = 0;
149
+ const { fileText = "" } = file;
150
+ for (const row of fileText.split("\n")) {
151
+ line++;
152
+ cursor += row.length + 1;
153
+ if (cursor >= index) {
154
+ lineText = row;
155
+ column = row.length - (cursor - index);
156
+ break;
157
+ }
158
+ }
159
+ return { lineText, line, column, ...file };
160
+ }
161
+
162
+ /**
163
+ * Guesses the line and column location of a search query.
164
+ */
165
+ export function searchLocation(file: File, query: unknown): Location {
166
+ let lineText,
167
+ length,
168
+ line = 0,
169
+ column = 0;
170
+ const queryText = String(query);
171
+ const { fileText = "" } = file;
172
+ for (const content of fileText.split("\n")) {
173
+ line++;
174
+ const index = content.indexOf(queryText);
175
+ if (index >= 0) {
176
+ lineText = content;
177
+ column = index;
178
+ length = queryText.length;
179
+ break;
180
+ }
181
+ }
182
+ return { lineText, line, column, length, ...file };
183
+ }
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 CHANGED
@@ -1,17 +1,27 @@
1
+ import { createServer as createHttpServer } from "node:http";
1
2
  import { connect } from "node:http2";
2
- import type { ClientHttp2Session, ServerHttp2Stream } from "node:http2";
3
- import { createServer } from "node:http";
3
+ import { createServer as createHttpsServer } from "node:https";
4
+ import WebSocket from "faye-websocket";
5
+ import { useEffect, useRef, useState } from "react";
6
+ import serveStatic from "serve-static";
7
+ import { getHttpsOptions } from "./https-options";
8
+ import { reportError } from "./reporting";
9
+ import type { CfPreviewToken } from "./create-worker-preview";
4
10
  import type {
5
11
  IncomingHttpHeaders,
6
12
  RequestListener,
7
13
  IncomingMessage,
8
14
  ServerResponse,
9
- Server,
15
+ Server as HttpServer,
10
16
  } from "node:http";
11
- import WebSocket from "faye-websocket";
12
- import serveStatic from "serve-static";
13
- import type { CfPreviewToken } from "./api/preview";
14
- import { useEffect, useRef } from "react";
17
+ import type { ClientHttp2Session, ServerHttp2Stream } from "node:http2";
18
+ import type { Server as HttpsServer } from "node:https";
19
+ import type ws from "ws";
20
+
21
+ interface IWebsocket extends ws {
22
+ // Pipe implements .on("message", ...)
23
+ pipe<T>(fn: T): IWebsocket;
24
+ }
15
25
 
16
26
  /**
17
27
  * `usePreviewServer` is a React hook that creates a local development
@@ -41,13 +51,17 @@ function addCfPreviewTokenHeader(
41
51
  function rewriteRemoteHostToLocalHostInHeaders(
42
52
  headers: IncomingHttpHeaders,
43
53
  remoteHost: string,
44
- localPort: number
54
+ localPort: number,
55
+ localProtocol: "https" | "http"
45
56
  ) {
46
57
  for (const [name, value] of Object.entries(headers)) {
47
58
  // Rewrite the remote host to the local host.
48
59
  if (typeof value === "string" && value.includes(remoteHost)) {
49
60
  headers[name] = value
50
- .replaceAll(`https://${remoteHost}`, `http://localhost:${localPort}`)
61
+ .replaceAll(
62
+ `https://${remoteHost}`,
63
+ `${localProtocol}://localhost:${localPort}`
64
+ )
51
65
  .replaceAll(remoteHost, `localhost:${localPort}`);
52
66
  }
53
67
  }
@@ -56,15 +70,31 @@ function rewriteRemoteHostToLocalHostInHeaders(
56
70
  export function usePreviewServer({
57
71
  previewToken,
58
72
  publicRoot,
59
- port,
73
+ localProtocol,
74
+ localPort: port,
60
75
  }: {
61
76
  previewToken: CfPreviewToken | undefined;
62
77
  publicRoot: undefined | string;
63
- port: number;
78
+ localProtocol: "https" | "http";
79
+ localPort: number;
64
80
  }) {
65
81
  /** Creates an HTTP/1 proxy that sends requests over HTTP/2. */
66
- const proxyServer = useRef<Server>();
67
- const proxy = (proxyServer.current ??= createProxyServer());
82
+ const [proxyServer, setProxyServer] = useState<HttpServer | HttpsServer>();
83
+
84
+ /**
85
+ * Create the instance of the local proxy server that will pass on
86
+ * requests to the preview worker.
87
+ */
88
+ useEffect(() => {
89
+ if (proxyServer === undefined) {
90
+ createProxyServer(localProtocol)
91
+ .then((proxy) => setProxyServer(proxy))
92
+ .catch(async (err) => {
93
+ console.error("Failed to create proxy server.", err);
94
+ await reportError(err);
95
+ });
96
+ }
97
+ }, [proxyServer, localProtocol]);
68
98
 
69
99
  /**
70
100
  * When we're not connected / getting a fresh token on changes,
@@ -80,7 +110,22 @@ export function usePreviewServer({
80
110
  { request: IncomingMessage; response: ServerResponse }[]
81
111
  >([]);
82
112
 
113
+ /**
114
+ * The session doesn't last forever, and will eventually drop
115
+ * (usually within 5-15 minutes). When that happens, we simply
116
+ * restart the effect, effectively restarting the server. We use
117
+ * a state sigil as an effect dependency to do so.
118
+ */
119
+ const [retryServerSetupSigil, setRetryServerSetupSigil] = useState<number>(0);
120
+ function retryServerSetup() {
121
+ setRetryServerSetupSigil((x) => x + 1);
122
+ }
123
+
83
124
  useEffect(() => {
125
+ if (proxyServer === undefined) {
126
+ return;
127
+ }
128
+
84
129
  // If we don't have a token, that means either we're just starting up,
85
130
  // or we're refreshing the token.
86
131
  if (!previewToken) {
@@ -92,8 +137,8 @@ export function usePreviewServer({
92
137
  // store the stream in a buffer so we can replay it later
93
138
  streamBufferRef.current.push({ stream, headers });
94
139
  };
95
- proxy.on("stream", bufferStream);
96
- cleanupListeners.push(() => proxy.off("stream", bufferStream));
140
+ proxyServer.on("stream", bufferStream);
141
+ cleanupListeners.push(() => proxyServer.off("stream", bufferStream));
97
142
 
98
143
  const bufferRequestResponse = (
99
144
  request: IncomingMessage,
@@ -103,8 +148,10 @@ export function usePreviewServer({
103
148
  requestResponseBufferRef.current.push({ request, response });
104
149
  };
105
150
 
106
- proxy.on("request", bufferRequestResponse);
107
- cleanupListeners.push(() => proxy.off("request", bufferRequestResponse));
151
+ proxyServer.on("request", bufferRequestResponse);
152
+ cleanupListeners.push(() =>
153
+ proxyServer.off("request", bufferRequestResponse)
154
+ );
108
155
  return () => {
109
156
  cleanupListeners.forEach((cleanup) => cleanup());
110
157
  };
@@ -119,10 +166,20 @@ export function usePreviewServer({
119
166
  const remote = connect(`https://${previewToken.host}`);
120
167
  cleanupListeners.push(() => remote.destroy());
121
168
 
169
+ // As mentioned above, the session may die at any point,
170
+ // so we need to restart the effect.
171
+ remote.on("close", retryServerSetup);
172
+ cleanupListeners.push(() => remote.off("close", retryServerSetup));
173
+
122
174
  /** HTTP/2 -> HTTP/2 */
123
- const handleStream = createStreamHandler(previewToken, remote, port);
124
- proxy.on("stream", handleStream);
125
- cleanupListeners.push(() => proxy.off("stream", handleStream));
175
+ const handleStream = createStreamHandler(
176
+ previewToken,
177
+ remote,
178
+ port,
179
+ localProtocol
180
+ );
181
+ proxyServer.on("stream", handleStream);
182
+ cleanupListeners.push(() => proxyServer.off("stream", handleStream));
126
183
 
127
184
  // flush and replay buffered streams
128
185
  streamBufferRef.current.forEach((buffer) =>
@@ -155,7 +212,8 @@ export function usePreviewServer({
155
212
  rewriteRemoteHostToLocalHostInHeaders(
156
213
  responseHeaders,
157
214
  previewToken.host,
158
- port
215
+ port,
216
+ localProtocol
159
217
  );
160
218
  for (const name of Object.keys(responseHeaders)) {
161
219
  if (name.startsWith(":")) {
@@ -173,8 +231,10 @@ export function usePreviewServer({
173
231
  ? createHandleAssetsRequest(assetPath, handleRequest)
174
232
  : handleRequest;
175
233
 
176
- proxy.on("request", actualHandleRequest);
177
- cleanupListeners.push(() => proxy.off("request", actualHandleRequest));
234
+ proxyServer.on("request", actualHandleRequest);
235
+ cleanupListeners.push(() =>
236
+ proxyServer.off("request", actualHandleRequest)
237
+ );
178
238
 
179
239
  // flush and replay buffered requests
180
240
  requestResponseBufferRef.current.forEach(({ request, response }) =>
@@ -191,38 +251,59 @@ export function usePreviewServer({
191
251
  const { headers, url } = message;
192
252
  addCfPreviewTokenHeader(headers, previewToken.value);
193
253
  headers["host"] = previewToken.host;
194
- const localWebsocket = new WebSocket(message, socket, body);
254
+ const localWebsocket = new WebSocket(message, socket, body) as IWebsocket;
195
255
  // TODO(soon): Custom WebSocket protocol is not working?
196
256
  const remoteWebsocketClient = new WebSocket.Client(
197
257
  `wss://${previewToken.host}${url}`,
198
258
  [],
199
259
  { headers }
200
- );
260
+ ) as IWebsocket;
201
261
  localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
202
262
  // We close down websockets whenever we refresh the token.
203
263
  cleanupListeners.push(() => {
204
- localWebsocket.destroy();
205
- remoteWebsocketClient.destroy();
264
+ localWebsocket.close();
265
+ remoteWebsocketClient.close();
206
266
  });
207
267
  };
208
- proxy.on("upgrade", handleUpgrade);
209
- cleanupListeners.push(() => proxy.off("upgrade", handleUpgrade));
268
+ proxyServer.on("upgrade", handleUpgrade);
269
+ cleanupListeners.push(() => proxyServer.off("upgrade", handleUpgrade));
210
270
 
211
271
  return () => {
212
- cleanupListeners.forEach((d) => d());
272
+ cleanupListeners.forEach((cleanup) => cleanup());
213
273
  };
214
- }, [previewToken, publicRoot, port, proxy]);
274
+ }, [
275
+ previewToken,
276
+ publicRoot,
277
+ port,
278
+ localProtocol,
279
+ proxyServer,
280
+ // We use a state value as a sigil to trigger reconnecting the server.
281
+ // It's not used inside the effect, so react-hooks/exhaustive-deps
282
+ // doesn't complain if it's not included in the dependency array.
283
+ // But its presence is critical, so Do NOT remove it from the dependency list.
284
+ retryServerSetupSigil,
285
+ ]);
215
286
 
216
287
  // Start/stop the server whenever the
217
288
  // containing component is mounted/unmounted.
218
289
  useEffect(() => {
219
- proxy.listen(port);
220
- console.log(`⬣ Listening at http://localhost:${port}`);
290
+ if (proxyServer === undefined) {
291
+ return;
292
+ }
293
+
294
+ waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 })
295
+ .then(() => {
296
+ proxyServer.listen(port);
297
+ console.log(`⬣ Listening at ${localProtocol}://localhost:${port}`);
298
+ })
299
+ .catch((err) => {
300
+ console.error(`⬣ Failed to start server: ${err}`);
301
+ });
221
302
 
222
303
  return () => {
223
- proxy.close();
304
+ proxyServer.close();
224
305
  };
225
- }, [port, proxy]);
306
+ }, [port, proxyServer, localProtocol]);
226
307
  }
227
308
 
228
309
  function createHandleAssetsRequest(
@@ -250,8 +331,15 @@ const HTTP1_HEADERS = new Set([
250
331
  "http2-settings",
251
332
  ]);
252
333
 
253
- function createProxyServer() {
254
- return createServer()
334
+ async function createProxyServer(
335
+ localProtocol: "https" | "http"
336
+ ): Promise<HttpServer | HttpsServer> {
337
+ const server: HttpServer | HttpsServer =
338
+ localProtocol === "https"
339
+ ? createHttpsServer(await getHttpsOptions())
340
+ : createHttpServer();
341
+
342
+ return server
255
343
  .on("request", function (req, res) {
256
344
  // log all requests
257
345
  console.log(
@@ -280,7 +368,8 @@ function createProxyServer() {
280
368
  function createStreamHandler(
281
369
  previewToken: CfPreviewToken,
282
370
  remote: ClientHttp2Session,
283
- port: number
371
+ localPort: number,
372
+ localProtocol: "https" | "http"
284
373
  ) {
285
374
  return function handleStream(
286
375
  stream: ServerHttp2Stream,
@@ -293,10 +382,57 @@ function createStreamHandler(
293
382
  rewriteRemoteHostToLocalHostInHeaders(
294
383
  responseHeaders,
295
384
  previewToken.host,
296
- port
385
+ localPort,
386
+ localProtocol
297
387
  );
298
388
  stream.respond(responseHeaders);
299
389
  request.pipe(stream, { end: true });
300
390
  });
301
391
  };
302
392
  }
393
+
394
+ /**
395
+ * A helper function that waits for a port to be available.
396
+ */
397
+ export async function waitForPortToBeAvailable(
398
+ port: number,
399
+ options: { retryPeriod: number; timeout: number }
400
+ ): Promise<void> {
401
+ return new Promise((resolve, reject) => {
402
+ const timeout = setTimeout(() => {
403
+ doReject(new Error(`Timed out waiting for port ${port}`));
404
+ }, options.timeout);
405
+
406
+ const interval = setInterval(checkPort, options.retryPeriod);
407
+ checkPort();
408
+
409
+ function doResolve() {
410
+ clearTimeout(timeout);
411
+ clearInterval(interval);
412
+ resolve();
413
+ }
414
+
415
+ function doReject(err: unknown) {
416
+ clearInterval(interval);
417
+ clearTimeout(timeout);
418
+ reject(err);
419
+ }
420
+
421
+ function checkPort() {
422
+ // Testing whether a port is 'available' involves simply
423
+ // trying to make a server listen on that port, and retrying
424
+ // until it succeeds.
425
+ const server = createHttpServer();
426
+ server.on("error", (err) => {
427
+ // @ts-expect-error non standard property on Error
428
+ if (err.code !== "EADDRINUSE") {
429
+ doReject(err);
430
+ }
431
+ });
432
+ server.listen(port, () => {
433
+ server.close();
434
+ doResolve();
435
+ });
436
+ }
437
+ });
438
+ }