wrangler 0.0.0-e88a54e → 0.0.0-e8df68ee

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 (167) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +46 -15
  3. package/bin/wrangler.js +118 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +194 -143
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +23 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +172 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +127 -0
  17. package/templates/middleware/loader-sw.ts +228 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-d1-beta.ts +244 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +31 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/cli.d.ts +1726 -0
  41. package/wrangler-dist/cli.js +134048 -126481
  42. package/wrangler-dist/wasm-sync.wasm +0 -0
  43. package/import_meta_url.js +0 -3
  44. package/miniflare-config-stubs/.env.empty +0 -0
  45. package/miniflare-config-stubs/package.empty.json +0 -1
  46. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  47. package/miniflare-dist/index.mjs +0 -79
  48. package/miniflare-dist/index.mjs.map +0 -7
  49. package/pages/functions/buildWorker.ts +0 -62
  50. package/pages/functions/filepath-routing.test.ts +0 -223
  51. package/pages/functions/filepath-routing.ts +0 -181
  52. package/pages/functions/identifiers.ts +0 -78
  53. package/pages/functions/routes.ts +0 -151
  54. package/pages/functions/template-worker.ts +0 -130
  55. package/src/__tests__/configuration.test.ts +0 -2796
  56. package/src/__tests__/dev.test.tsx +0 -496
  57. package/src/__tests__/dev2.test.tsx +0 -154
  58. package/src/__tests__/guess-worker-format.test.ts +0 -58
  59. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  60. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  61. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  62. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  63. package/src/__tests__/helpers/mock-bin.ts +0 -36
  64. package/src/__tests__/helpers/mock-cfetch.ts +0 -207
  65. package/src/__tests__/helpers/mock-console.ts +0 -70
  66. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  69. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  70. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  71. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  72. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  73. package/src/__tests__/https-options.test.ts +0 -127
  74. package/src/__tests__/index.test.ts +0 -991
  75. package/src/__tests__/jest.setup.ts +0 -69
  76. package/src/__tests__/kv.test.ts +0 -1382
  77. package/src/__tests__/logout.test.ts +0 -52
  78. package/src/__tests__/package-manager.test.ts +0 -206
  79. package/src/__tests__/pages.test.ts +0 -44
  80. package/src/__tests__/parse.test.ts +0 -322
  81. package/src/__tests__/publish.test.ts +0 -2704
  82. package/src/__tests__/r2.test.ts +0 -198
  83. package/src/__tests__/route.test.ts +0 -45
  84. package/src/__tests__/secret.test.ts +0 -425
  85. package/src/__tests__/sentry.test.ts +0 -146
  86. package/src/__tests__/tail.test.ts +0 -564
  87. package/src/__tests__/whoami.test.tsx +0 -100
  88. package/src/bundle.ts +0 -142
  89. package/src/cfetch/index.ts +0 -104
  90. package/src/cfetch/internal.ts +0 -139
  91. package/src/cli.ts +0 -19
  92. package/src/config/README.md +0 -107
  93. package/src/config/config.ts +0 -218
  94. package/src/config/diagnostics.ts +0 -80
  95. package/src/config/environment.ts +0 -366
  96. package/src/config/index.ts +0 -62
  97. package/src/config/validation-helpers.ts +0 -486
  98. package/src/config/validation.ts +0 -1090
  99. package/src/create-worker-preview.ts +0 -166
  100. package/src/create-worker-upload-form.ts +0 -217
  101. package/src/dev/dev.tsx +0 -364
  102. package/src/dev/local.tsx +0 -232
  103. package/src/dev/remote.tsx +0 -203
  104. package/src/dev/use-esbuild.ts +0 -100
  105. package/src/dialogs.tsx +0 -77
  106. package/src/entry.ts +0 -208
  107. package/src/environment-variables.ts +0 -33
  108. package/src/https-options.ts +0 -122
  109. package/src/index.tsx +0 -2373
  110. package/src/inspect.ts +0 -617
  111. package/src/kv.ts +0 -319
  112. package/src/miniflare-cli/README.md +0 -30
  113. package/src/miniflare-cli/enum-keys.ts +0 -17
  114. package/src/miniflare-cli/index.ts +0 -37
  115. package/src/module-collection.ts +0 -258
  116. package/src/open-in-browser.ts +0 -25
  117. package/src/package-manager.ts +0 -126
  118. package/src/pages.tsx +0 -1047
  119. package/src/parse.ts +0 -183
  120. package/src/paths.ts +0 -26
  121. package/src/proxy.ts +0 -440
  122. package/src/publish.ts +0 -347
  123. package/src/r2.ts +0 -50
  124. package/src/reporting.ts +0 -131
  125. package/src/selfsigned.d.ts +0 -29
  126. package/src/sites.tsx +0 -280
  127. package/src/tail/filters.ts +0 -279
  128. package/src/tail/index.ts +0 -299
  129. package/src/tail/printing.ts +0 -62
  130. package/src/user.tsx +0 -1118
  131. package/src/whoami.tsx +0 -69
  132. package/src/worker.ts +0 -163
  133. package/templates/static-asset-facade.js +0 -47
  134. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  135. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  136. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  137. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  138. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  139. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  140. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  141. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  142. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  143. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  144. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  145. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  146. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  147. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  148. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  149. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  150. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  151. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  152. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  153. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  154. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  155. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  156. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  157. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  158. package/vendor/wrangler-mime/LICENSE +0 -21
  159. package/vendor/wrangler-mime/Mime.js +0 -97
  160. package/vendor/wrangler-mime/README.md +0 -187
  161. package/vendor/wrangler-mime/cli.js +0 -46
  162. package/vendor/wrangler-mime/index.js +0 -4
  163. package/vendor/wrangler-mime/lite.js +0 -4
  164. package/vendor/wrangler-mime/package.json +0 -52
  165. package/vendor/wrangler-mime/types/other.js +0 -1
  166. package/vendor/wrangler-mime/types/standard.js +0 -1
  167. package/wrangler-dist/cli.js.map +0 -7
package/src/parse.ts DELETED
@@ -1,183 +0,0 @@
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 DELETED
@@ -1,26 +0,0 @@
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 DELETED
@@ -1,440 +0,0 @@
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 { 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";
10
- import type {
11
- IncomingHttpHeaders,
12
- RequestListener,
13
- IncomingMessage,
14
- ServerResponse,
15
- Server as HttpServer,
16
- } from "node:http";
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
- }
25
-
26
- /**
27
- * `usePreviewServer` is a React hook that creates a local development
28
- * server that can be used to develop a Worker.
29
- *
30
- * When we run `wrangler dev`, we start by uploading the compiled worker
31
- * to the preview service, which responds with a preview token.
32
- * (see `useWorker`/`createWorker` for details.)
33
- * We can then use that token to connect to the preview server for a
34
- * great local development experience. Further, as we change the worker,
35
- * we can update the preview token transparently without having to restart
36
- * the development server.
37
- */
38
-
39
- /** Rewrite request headers to add the preview token. */
40
- function addCfPreviewTokenHeader(
41
- headers: IncomingHttpHeaders,
42
- previewTokenValue: string
43
- ) {
44
- headers["cf-workers-preview-token"] = previewTokenValue;
45
- }
46
-
47
- /**
48
- * Rewrite references in request headers
49
- * from the preview host to the local host.
50
- */
51
- function rewriteRemoteHostToLocalHostInHeaders(
52
- headers: IncomingHttpHeaders,
53
- remoteHost: string,
54
- localPort: number,
55
- localProtocol: "https" | "http"
56
- ) {
57
- for (const [name, value] of Object.entries(headers)) {
58
- // Rewrite the remote host to the local host.
59
- if (typeof value === "string" && value.includes(remoteHost)) {
60
- headers[name] = value
61
- .replaceAll(
62
- `https://${remoteHost}`,
63
- `${localProtocol}://localhost:${localPort}`
64
- )
65
- .replaceAll(remoteHost, `localhost:${localPort}`);
66
- }
67
- }
68
- }
69
-
70
- export function usePreviewServer({
71
- previewToken,
72
- publicRoot,
73
- localProtocol,
74
- localPort: port,
75
- ip,
76
- }: {
77
- previewToken: CfPreviewToken | undefined;
78
- publicRoot: undefined | string;
79
- localProtocol: "https" | "http";
80
- localPort: number;
81
- ip: string;
82
- }) {
83
- /** Creates an HTTP/1 proxy that sends requests over HTTP/2. */
84
- const [proxyServer, setProxyServer] = useState<HttpServer | HttpsServer>();
85
-
86
- /**
87
- * Create the instance of the local proxy server that will pass on
88
- * requests to the preview worker.
89
- */
90
- useEffect(() => {
91
- if (proxyServer === undefined) {
92
- createProxyServer(localProtocol)
93
- .then((proxy) => setProxyServer(proxy))
94
- .catch(async (err) => {
95
- console.error("Failed to create proxy server.", err);
96
- await reportError(err);
97
- });
98
- }
99
- }, [proxyServer, localProtocol]);
100
-
101
- /**
102
- * When we're not connected / getting a fresh token on changes,
103
- * we'd like to buffer streams/requests until we're connected.
104
- * Once connected, we can flush the buffered streams/requests.
105
- * streamBufferRef is used to buffer http/2 streams, while
106
- * requestResponseBufferRef is used to buffer http/1 requests.
107
- */
108
- const streamBufferRef = useRef<
109
- { stream: ServerHttp2Stream; headers: IncomingHttpHeaders }[]
110
- >([]);
111
- const requestResponseBufferRef = useRef<
112
- { request: IncomingMessage; response: ServerResponse }[]
113
- >([]);
114
-
115
- /**
116
- * The session doesn't last forever, and will eventually drop
117
- * (usually within 5-15 minutes). When that happens, we simply
118
- * restart the effect, effectively restarting the server. We use
119
- * a state sigil as an effect dependency to do so.
120
- */
121
- const [retryServerSetupSigil, setRetryServerSetupSigil] = useState<number>(0);
122
- function retryServerSetup() {
123
- setRetryServerSetupSigil((x) => x + 1);
124
- }
125
-
126
- useEffect(() => {
127
- if (proxyServer === undefined) {
128
- return;
129
- }
130
-
131
- // If we don't have a token, that means either we're just starting up,
132
- // or we're refreshing the token.
133
- if (!previewToken) {
134
- const cleanupListeners: (() => void)[] = [];
135
- const bufferStream = (
136
- stream: ServerHttp2Stream,
137
- headers: IncomingHttpHeaders
138
- ) => {
139
- // store the stream in a buffer so we can replay it later
140
- streamBufferRef.current.push({ stream, headers });
141
- };
142
- proxyServer.on("stream", bufferStream);
143
- cleanupListeners.push(() => proxyServer.off("stream", bufferStream));
144
-
145
- const bufferRequestResponse = (
146
- request: IncomingMessage,
147
- response: ServerResponse
148
- ) => {
149
- // store the request and response in a buffer so we can replay it later
150
- requestResponseBufferRef.current.push({ request, response });
151
- };
152
-
153
- proxyServer.on("request", bufferRequestResponse);
154
- cleanupListeners.push(() =>
155
- proxyServer.off("request", bufferRequestResponse)
156
- );
157
- return () => {
158
- cleanupListeners.forEach((cleanup) => cleanup());
159
- };
160
- }
161
-
162
- // We have a token. Let's proxy requests to the preview end point.
163
- const cleanupListeners: (() => void)[] = [];
164
-
165
- const assetPath = typeof publicRoot === "string" ? publicRoot : null;
166
-
167
- // create a ClientHttp2Session
168
- const remote = connect(`https://${previewToken.host}`);
169
- cleanupListeners.push(() => remote.destroy());
170
-
171
- // As mentioned above, the session may die at any point,
172
- // so we need to restart the effect.
173
- remote.on("close", retryServerSetup);
174
- cleanupListeners.push(() => remote.off("close", retryServerSetup));
175
-
176
- /** HTTP/2 -> HTTP/2 */
177
- const handleStream = createStreamHandler(
178
- previewToken,
179
- remote,
180
- port,
181
- localProtocol
182
- );
183
- proxyServer.on("stream", handleStream);
184
- cleanupListeners.push(() => proxyServer.off("stream", handleStream));
185
-
186
- // flush and replay buffered streams
187
- streamBufferRef.current.forEach((buffer) =>
188
- handleStream(buffer.stream, buffer.headers)
189
- );
190
- streamBufferRef.current = [];
191
-
192
- /** HTTP/1 -> HTTP/2 */
193
- const handleRequest: RequestListener = (
194
- message: IncomingMessage,
195
- response: ServerResponse
196
- ) => {
197
- const { httpVersionMajor, headers, method, url } = message;
198
- if (httpVersionMajor >= 2) {
199
- return; // Already handled by the "stream" event.
200
- }
201
- addCfPreviewTokenHeader(headers, previewToken.value);
202
- headers[":method"] = method;
203
- headers[":path"] = url;
204
- headers[":authority"] = previewToken.host;
205
- headers[":scheme"] = "https";
206
- for (const name of Object.keys(headers)) {
207
- if (HTTP1_HEADERS.has(name.toLowerCase())) {
208
- delete headers[name];
209
- }
210
- }
211
- const request = message.pipe(remote.request(headers));
212
- request.on("response", (responseHeaders) => {
213
- const status = responseHeaders[":status"] ?? 500;
214
- rewriteRemoteHostToLocalHostInHeaders(
215
- responseHeaders,
216
- previewToken.host,
217
- port,
218
- localProtocol
219
- );
220
- for (const name of Object.keys(responseHeaders)) {
221
- if (name.startsWith(":")) {
222
- delete responseHeaders[name];
223
- }
224
- }
225
- response.writeHead(status, responseHeaders);
226
- request.pipe(response, { end: true });
227
- });
228
- };
229
-
230
- // If an asset path is defined, check the file system
231
- // for a file first and serve if it exists.
232
- const actualHandleRequest = assetPath
233
- ? createHandleAssetsRequest(assetPath, handleRequest)
234
- : handleRequest;
235
-
236
- proxyServer.on("request", actualHandleRequest);
237
- cleanupListeners.push(() =>
238
- proxyServer.off("request", actualHandleRequest)
239
- );
240
-
241
- // flush and replay buffered requests
242
- requestResponseBufferRef.current.forEach(({ request, response }) =>
243
- actualHandleRequest(request, response)
244
- );
245
- requestResponseBufferRef.current = [];
246
-
247
- /** HTTP/1 -> WebSocket (over HTTP/1) */
248
- const handleUpgrade = (
249
- message: IncomingMessage,
250
- socket: WebSocket,
251
- body: Buffer
252
- ) => {
253
- const { headers, url } = message;
254
- addCfPreviewTokenHeader(headers, previewToken.value);
255
- headers["host"] = previewToken.host;
256
- const localWebsocket = new WebSocket(message, socket, body) as IWebsocket;
257
- // TODO(soon): Custom WebSocket protocol is not working?
258
- const remoteWebsocketClient = new WebSocket.Client(
259
- `wss://${previewToken.host}${url}`,
260
- [],
261
- { headers }
262
- ) as IWebsocket;
263
- localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
264
- // We close down websockets whenever we refresh the token.
265
- cleanupListeners.push(() => {
266
- localWebsocket.close();
267
- remoteWebsocketClient.close();
268
- });
269
- };
270
- proxyServer.on("upgrade", handleUpgrade);
271
- cleanupListeners.push(() => proxyServer.off("upgrade", handleUpgrade));
272
-
273
- return () => {
274
- cleanupListeners.forEach((cleanup) => cleanup());
275
- };
276
- }, [
277
- previewToken,
278
- publicRoot,
279
- port,
280
- localProtocol,
281
- proxyServer,
282
- // We use a state value as a sigil to trigger reconnecting the server.
283
- // It's not used inside the effect, so react-hooks/exhaustive-deps
284
- // doesn't complain if it's not included in the dependency array.
285
- // But its presence is critical, so Do NOT remove it from the dependency list.
286
- retryServerSetupSigil,
287
- ]);
288
-
289
- // Start/stop the server whenever the
290
- // containing component is mounted/unmounted.
291
- useEffect(() => {
292
- if (proxyServer === undefined) {
293
- return;
294
- }
295
-
296
- waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 })
297
- .then(() => {
298
- proxyServer.listen(port, ip);
299
- console.log(`⬣ Listening at ${localProtocol}://${ip}:${port}`);
300
- })
301
- .catch((err) => {
302
- console.error(`⬣ Failed to start server: ${err}`);
303
- });
304
-
305
- return () => {
306
- proxyServer.close();
307
- };
308
- }, [port, ip, proxyServer, localProtocol]);
309
- }
310
-
311
- function createHandleAssetsRequest(
312
- assetPath: string,
313
- handleRequest: RequestListener
314
- ) {
315
- const handleAsset = serveStatic(assetPath, {
316
- cacheControl: false,
317
- });
318
- return (request: IncomingMessage, response: ServerResponse) => {
319
- handleAsset(request, response, () => {
320
- handleRequest(request, response);
321
- });
322
- };
323
- }
324
-
325
- /** A Set of headers we want to remove from HTTP/1 requests. */
326
- const HTTP1_HEADERS = new Set([
327
- "host",
328
- "connection",
329
- "upgrade",
330
- "keep-alive",
331
- "proxy-connection",
332
- "transfer-encoding",
333
- "http2-settings",
334
- ]);
335
-
336
- async function createProxyServer(
337
- localProtocol: "https" | "http"
338
- ): Promise<HttpServer | HttpsServer> {
339
- const server: HttpServer | HttpsServer =
340
- localProtocol === "https"
341
- ? createHttpsServer(await getHttpsOptions())
342
- : createHttpServer();
343
-
344
- return server
345
- .on("request", function (req, res) {
346
- // log all requests
347
- console.log(
348
- new Date().toLocaleTimeString(),
349
- req.method,
350
- req.url,
351
- res.statusCode
352
- );
353
- })
354
- .on("upgrade", (req) => {
355
- // log all websocket connections
356
- console.log(
357
- new Date().toLocaleTimeString(),
358
- req.method,
359
- req.url,
360
- 101,
361
- "(WebSocket)"
362
- );
363
- })
364
- .on("error", (err) => {
365
- // log all connection errors
366
- console.error(new Date().toLocaleTimeString(), err);
367
- });
368
- }
369
-
370
- function createStreamHandler(
371
- previewToken: CfPreviewToken,
372
- remote: ClientHttp2Session,
373
- localPort: number,
374
- localProtocol: "https" | "http"
375
- ) {
376
- return function handleStream(
377
- stream: ServerHttp2Stream,
378
- headers: IncomingHttpHeaders
379
- ) {
380
- addCfPreviewTokenHeader(headers, previewToken.value);
381
- headers[":authority"] = previewToken.host;
382
- const request = stream.pipe(remote.request(headers));
383
- request.on("response", (responseHeaders: IncomingHttpHeaders) => {
384
- rewriteRemoteHostToLocalHostInHeaders(
385
- responseHeaders,
386
- previewToken.host,
387
- localPort,
388
- localProtocol
389
- );
390
- stream.respond(responseHeaders);
391
- request.pipe(stream, { end: true });
392
- });
393
- };
394
- }
395
-
396
- /**
397
- * A helper function that waits for a port to be available.
398
- */
399
- export async function waitForPortToBeAvailable(
400
- port: number,
401
- options: { retryPeriod: number; timeout: number }
402
- ): Promise<void> {
403
- return new Promise((resolve, reject) => {
404
- const timeout = setTimeout(() => {
405
- doReject(new Error(`Timed out waiting for port ${port}`));
406
- }, options.timeout);
407
-
408
- const interval = setInterval(checkPort, options.retryPeriod);
409
- checkPort();
410
-
411
- function doResolve() {
412
- clearTimeout(timeout);
413
- clearInterval(interval);
414
- resolve();
415
- }
416
-
417
- function doReject(err: unknown) {
418
- clearInterval(interval);
419
- clearTimeout(timeout);
420
- reject(err);
421
- }
422
-
423
- function checkPort() {
424
- // Testing whether a port is 'available' involves simply
425
- // trying to make a server listen on that port, and retrying
426
- // until it succeeds.
427
- const server = createHttpServer();
428
- server.on("error", (err) => {
429
- // @ts-expect-error non standard property on Error
430
- if (err.code !== "EADDRINUSE") {
431
- doReject(err);
432
- }
433
- });
434
- server.listen(port, () => {
435
- server.close();
436
- doResolve();
437
- });
438
- }
439
- });
440
- }