wrangler 0.0.0-eaea98f7 → 0.0.0-eb08e2dc

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.
@@ -0,0 +1,252 @@
1
+ import assert from "node:assert";
2
+ import type {
3
+ ProxyWorkerIncomingRequestBody,
4
+ ProxyWorkerOutgoingRequestBody,
5
+ ProxyData,
6
+ } from "../../src/api/startDevWorker/events";
7
+ import {
8
+ DeferredPromise,
9
+ createDeferred,
10
+ } from "../../src/api/startDevWorker/utils";
11
+
12
+ interface Env {
13
+ PROXY_CONTROLLER: Fetcher;
14
+ PROXY_CONTROLLER_AUTH_SECRET: string;
15
+ DURABLE_OBJECT: DurableObjectNamespace;
16
+ }
17
+
18
+ // request.cf.hostMetadata is verbose to type using the workers-types Request -- this allows us to have Request correctly typed in this scope
19
+ type Request = Parameters<
20
+ NonNullable<
21
+ ExportedHandler<Env, unknown, ProxyWorkerIncomingRequestBody>["fetch"]
22
+ >
23
+ >[0];
24
+
25
+ const LIVE_RELOAD_PROTOCOL = "WRANGLER_PROXYWORKER_LIVE_RELOAD_PROTOCOL";
26
+ export default {
27
+ fetch(req, env) {
28
+ const singleton = env.DURABLE_OBJECT.idFromName("");
29
+ const inspectorProxy = env.DURABLE_OBJECT.get(singleton);
30
+
31
+ return inspectorProxy.fetch(req);
32
+ },
33
+ } as ExportedHandler<Env, unknown, ProxyWorkerIncomingRequestBody>;
34
+
35
+ export class ProxyWorker implements DurableObject {
36
+ constructor(readonly state: DurableObjectState, readonly env: Env) {}
37
+
38
+ proxyData?: ProxyData;
39
+ requestQueue = new Map<Request, DeferredPromise<Response>>();
40
+
41
+ fetch(request: Request) {
42
+ if (isRequestForLiveReloadWebsocket(request)) {
43
+ // requests for live-reload websocket
44
+
45
+ return this.handleLiveReloadWebSocket(request);
46
+ }
47
+
48
+ if (isRequestFromProxyController(request, this.env)) {
49
+ // requests from ProxyController
50
+
51
+ return this.processProxyControllerRequest(request);
52
+ }
53
+
54
+ // regular requests to be proxied
55
+ const deferred = createDeferred<Response>();
56
+
57
+ this.requestQueue.set(request, deferred);
58
+ this.processQueue();
59
+
60
+ return deferred.promise;
61
+ }
62
+
63
+ handleLiveReloadWebSocket(request: Request) {
64
+ const { 0: response, 1: liveReload } = new WebSocketPair();
65
+ const websocketProtocol =
66
+ request.headers.get("Sec-WebSocket-Protocol") ?? "";
67
+
68
+ this.state.acceptWebSocket(liveReload, ["live-reload"]);
69
+
70
+ return new Response(null, {
71
+ status: 101,
72
+ webSocket: response,
73
+ headers: { "Sec-WebSocket-Protocol": websocketProtocol },
74
+ });
75
+ }
76
+
77
+ processProxyControllerRequest(request: Request) {
78
+ const event = request.cf?.hostMetadata;
79
+ switch (event?.type) {
80
+ case "pause":
81
+ this.proxyData = undefined;
82
+ break;
83
+
84
+ case "play":
85
+ this.proxyData = event.proxyData;
86
+ this.processQueue();
87
+ this.state
88
+ .getWebSockets("live-reload")
89
+ .forEach((ws) => ws.send("reload"));
90
+
91
+ break;
92
+ }
93
+
94
+ return new Response(null, { status: 204 });
95
+ }
96
+
97
+ processQueue() {
98
+ const { proxyData } = this; // destructuring is required to keep the type-narrowing (not undefined) in the .then callback and to ensure the same proxyData is used throughout each request
99
+ if (proxyData === undefined) return;
100
+
101
+ for (const [request, deferredResponse] of this.requestQueue) {
102
+ this.requestQueue.delete(request);
103
+
104
+ const userWorkerUrl = new URL(request.url);
105
+ const headers = new Headers(request.headers);
106
+
107
+ // override url parts for proxying
108
+ Object.assign(userWorkerUrl, proxyData.userWorkerUrl);
109
+
110
+ // set request.url in the UserWorker
111
+ const innerUrl = new URL(request.url);
112
+ Object.assign(innerUrl, proxyData.userWorkerInnerUrlOverrides);
113
+ headers.set("MF-Original-URL", innerUrl.href);
114
+ headers.set("MF-Disable-Pretty-Error", "true"); // disables the UserWorker miniflare instance from rendering the pretty error -- instead the ProxyWorker miniflare instance will intercept the json error response and render the pretty error page
115
+
116
+ // merge proxyData headers with the request headers
117
+ for (const [key, value] of Object.entries(proxyData.headers ?? {})) {
118
+ if (key.toLowerCase() === "cookie") {
119
+ const existing = request.headers.get("cookie") ?? "";
120
+ headers.set("cookie", `${existing};${value}`);
121
+ } else {
122
+ headers.set(key, value);
123
+ }
124
+ }
125
+
126
+ // explicitly NOT await-ing this promise, we are in a loop and want to process the whole queue quickly
127
+ // if we decide to await, we should include a timeout (~100ms) in case the user worker has long-running/parellel requests
128
+ void fetch(userWorkerUrl, new Request(request, { headers }))
129
+ .then((res) => {
130
+ if (isHtmlResponse(res)) {
131
+ res = insertLiveReloadScript(request, res, this.env, proxyData);
132
+ }
133
+
134
+ deferredResponse.resolve(res);
135
+ })
136
+ .catch((error: Error) => {
137
+ // errors here are network errors or from response post-processing
138
+ // to catch only network errors, use the 2nd param of the fetch.then()
139
+
140
+ void sendMessageToProxyController(this.env, {
141
+ type: "error",
142
+ error: {
143
+ name: error.name,
144
+ message: error.message,
145
+ stack: error.stack,
146
+ cause: error.cause,
147
+ },
148
+ });
149
+
150
+ deferredResponse.reject(error);
151
+ });
152
+ }
153
+ }
154
+ }
155
+
156
+ function isRequestFromProxyController(req: Request, env: Env): boolean {
157
+ return req.headers.get("Authorization") === env.PROXY_CONTROLLER_AUTH_SECRET;
158
+ }
159
+ function isHtmlResponse(res: Response): boolean {
160
+ return res.headers.get("content-type")?.startsWith("text/html") ?? false;
161
+ }
162
+ function isRequestForLiveReloadWebsocket(req: Request): boolean {
163
+ const websocketProtocol = req.headers.get("Sec-WebSocket-Protocol");
164
+ const isWebSocketUpgrade = req.headers.get("Upgrade") === "websocket";
165
+
166
+ return isWebSocketUpgrade && websocketProtocol === LIVE_RELOAD_PROTOCOL;
167
+ }
168
+
169
+ async function sendMessageToProxyController(
170
+ env: Env,
171
+ message: ProxyWorkerOutgoingRequestBody,
172
+ retries = 3
173
+ ) {
174
+ try {
175
+ await env.PROXY_CONTROLLER.fetch("http://dummy", {
176
+ method: "POST",
177
+ body: JSON.stringify(message),
178
+ });
179
+ } catch (cause) {
180
+ if (retries > 0) {
181
+ return sendMessageToProxyController(env, message, retries - 1);
182
+ }
183
+
184
+ // no point sending an error message if we can't send this message
185
+
186
+ throw cause;
187
+ }
188
+ }
189
+
190
+ function insertLiveReloadScript(
191
+ request: Request,
192
+ response: Response,
193
+ env: Env,
194
+ proxyData: ProxyData
195
+ ) {
196
+ const htmlRewriter = new HTMLRewriter();
197
+
198
+ // if preview-token-expired response, errorDetails will contain "Invalid Workers Preview configuration"
199
+ let errorDetails = "";
200
+ htmlRewriter.on("#cf-error-details", {
201
+ text(element) {
202
+ errorDetails += element.text;
203
+ },
204
+ });
205
+
206
+ htmlRewriter.onDocument({
207
+ end(end) {
208
+ if (
209
+ response.status === 400 &&
210
+ errorDetails.includes("Invalid Workers Preview configuration")
211
+ ) {
212
+ void sendMessageToProxyController(env, {
213
+ type: "previewTokenExpired",
214
+ proxyData,
215
+ });
216
+ }
217
+
218
+ // if liveReload enabled, append a script tag
219
+ // TODO: compare to existing nodejs implementation
220
+ if (proxyData.liveReload) {
221
+ const websocketUrl = new URL(request.url);
222
+ websocketUrl.protocol =
223
+ websocketUrl.protocol === "http:" ? "ws:" : "wss:";
224
+
225
+ end.append(
226
+ `
227
+ <script>
228
+ (function() {
229
+ var ws;
230
+ function recover() {
231
+ ws = null;
232
+ setTimeout(initLiveReload, 100);
233
+ }
234
+ function initLiveReload() {
235
+ if (ws) return;
236
+ var origin = (location.protocol === "http:" ? "ws://" : "wss://") + location.host;
237
+ ws = new WebSocket(origin + "/cdn-cgi/live-reload", "${LIVE_RELOAD_PROTOCOL}");
238
+ ws.onclose = recover;
239
+ ws.onerror = recover;
240
+ ws.onmessage = location.reload.bind(location);
241
+ }
242
+ })();
243
+ </script>
244
+ `,
245
+ { html: true }
246
+ );
247
+ }
248
+ },
249
+ });
250
+
251
+ return htmlRewriter.transform(response);
252
+ }
@@ -0,0 +1,460 @@
1
+ // templates/startDevWorker/InspectorProxyWorker.ts
2
+ import assert2 from "node:assert";
3
+
4
+ // src/api/startDevWorker/events.ts
5
+ function serialiseError(e) {
6
+ if (e instanceof Error) {
7
+ return {
8
+ message: e.message,
9
+ name: e.name,
10
+ stack: e.stack,
11
+ cause: e.cause && serialiseError(e.cause)
12
+ };
13
+ } else {
14
+ return { message: String(e) };
15
+ }
16
+ }
17
+
18
+ // src/api/startDevWorker/utils.ts
19
+ import assert from "node:assert";
20
+ function createDeferred(previousDeferred) {
21
+ let resolve, reject;
22
+ const newPromise = new Promise((_resolve, _reject) => {
23
+ resolve = _resolve;
24
+ reject = _reject;
25
+ });
26
+ assert(resolve);
27
+ assert(reject);
28
+ previousDeferred?.resolve(newPromise);
29
+ return {
30
+ promise: newPromise,
31
+ resolve,
32
+ reject
33
+ };
34
+ }
35
+ function assertNever(_value) {
36
+ }
37
+ function urlFromParts(parts, base = "http://localhost") {
38
+ const url = new URL(base);
39
+ Object.assign(url, parts);
40
+ return url;
41
+ }
42
+
43
+ // templates/startDevWorker/InspectorProxyWorker.ts
44
+ var ALLOWED_HOST_HOSTNAMES = ["127.0.0.1", "[::1]", "localhost"];
45
+ var ALLOWED_ORIGIN_HOSTNAMES = [
46
+ "devtools.devprod.cloudflare.dev",
47
+ "cloudflare-devtools.pages.dev",
48
+ /^[a-z0-9]+\.cloudflare-devtools\.pages\.dev$/,
49
+ "127.0.0.1",
50
+ "[::1]",
51
+ "localhost"
52
+ ];
53
+ var InspectorProxyWorker_default = {
54
+ fetch(req, env) {
55
+ const singleton = env.DURABLE_OBJECT.idFromName("");
56
+ const inspectorProxy = env.DURABLE_OBJECT.get(singleton);
57
+ return inspectorProxy.fetch(req);
58
+ }
59
+ };
60
+ function isDevToolsEvent(event, name) {
61
+ return typeof event === "object" && event !== null && "method" in event && event.method === name;
62
+ }
63
+ var InspectorProxyWorker = class {
64
+ constructor(_state, env) {
65
+ this.env = env;
66
+ }
67
+ websockets = {
68
+ runtimeDeferred: createDeferred()
69
+ };
70
+ proxyData;
71
+ runtimeMessageBuffer = [];
72
+ async fetch(req) {
73
+ if (req.headers.get("Authorization") === this.env.PROXY_CONTROLLER_AUTH_SECRET) {
74
+ return this.handleProxyControllerRequest(req);
75
+ }
76
+ if (req.headers.get("Upgrade") === "websocket") {
77
+ return this.handleDevToolsWebSocketUpgradeRequest(req);
78
+ }
79
+ return this.handleDevToolsJsonRequest(req);
80
+ }
81
+ // ************************
82
+ // ** PROXY CONTROLLER **
83
+ // ************************
84
+ handleProxyControllerRequest(req) {
85
+ assert2(
86
+ req.headers.get("Upgrade") === "websocket",
87
+ "Expected proxy controller data request to be WebSocket upgrade"
88
+ );
89
+ const { 0: response, 1: proxyController } = new WebSocketPair();
90
+ proxyController.accept();
91
+ proxyController.addEventListener("close", (event) => {
92
+ this.sendDebugLog(
93
+ "PROXY CONTROLLER WEBSOCKET CLOSED",
94
+ event.code,
95
+ event.reason
96
+ );
97
+ if (this.websockets.proxyController === proxyController) {
98
+ this.websockets.proxyController = void 0;
99
+ }
100
+ });
101
+ proxyController.addEventListener("error", (event) => {
102
+ const error = serialiseError(event.error);
103
+ this.sendDebugLog("PROXY CONTROLLER WEBSOCKET ERROR", error);
104
+ if (this.websockets.proxyController === proxyController) {
105
+ this.websockets.proxyController = void 0;
106
+ }
107
+ });
108
+ proxyController.addEventListener(
109
+ "message",
110
+ this.handleProxyControllerIncomingMessage
111
+ );
112
+ this.websockets.proxyController = proxyController;
113
+ return new Response(null, {
114
+ status: 101,
115
+ webSocket: response
116
+ });
117
+ }
118
+ handleProxyControllerIncomingMessage = (event) => {
119
+ assert2(
120
+ typeof event.data === "string",
121
+ "Expected event.data from proxy controller to be string"
122
+ );
123
+ const message = JSON.parse(
124
+ event.data
125
+ );
126
+ this.sendDebugLog("handleProxyControllerIncomingMessage", event.data);
127
+ switch (message.type) {
128
+ case "reloadStart": {
129
+ this.sendRuntimeDiscardConsoleEntries();
130
+ break;
131
+ }
132
+ case "reloadComplete": {
133
+ this.proxyData = message.proxyData;
134
+ this.reconnectRuntimeWebSocket();
135
+ break;
136
+ }
137
+ default: {
138
+ assertNever(message);
139
+ }
140
+ }
141
+ };
142
+ sendProxyControllerMessage(message) {
143
+ message = typeof message === "string" ? message : JSON.stringify(message);
144
+ this.websockets.proxyController?.send(message);
145
+ }
146
+ async sendProxyControllerRequest(message) {
147
+ try {
148
+ const res = await this.env.PROXY_CONTROLLER.fetch("http://dummy", {
149
+ method: "POST",
150
+ body: JSON.stringify(message)
151
+ });
152
+ return res.ok ? await res.text() : void 0;
153
+ } catch (e) {
154
+ this.sendDebugLog(
155
+ "FAILED TO SEND PROXY CONTROLLER REQUEST",
156
+ serialiseError(e)
157
+ );
158
+ return void 0;
159
+ }
160
+ }
161
+ sendDebugLog = (...args) => {
162
+ this.sendProxyControllerRequest({ type: "debug-log", args });
163
+ };
164
+ // ***************
165
+ // ** RUNTIME **
166
+ // ***************
167
+ handleRuntimeIncomingMessage = (event) => {
168
+ assert2(typeof event.data === "string");
169
+ const msg = JSON.parse(event.data);
170
+ this.sendDebugLog("RUNTIME INCOMING MESSAGE", msg);
171
+ if (isDevToolsEvent(msg, "Runtime.exceptionThrown")) {
172
+ this.sendProxyControllerMessage(event.data);
173
+ }
174
+ if (this.proxyData?.proxyLogsToController && isDevToolsEvent(msg, "Runtime.consoleAPICalled")) {
175
+ this.sendProxyControllerMessage(event.data);
176
+ }
177
+ this.runtimeMessageBuffer.push(msg);
178
+ this.tryDrainRuntimeMessageBuffer();
179
+ };
180
+ handleRuntimeScriptParsed(msg) {
181
+ if (!this.websockets.devtoolsHasFileSystemAccess && msg.params.sourceMapURL !== void 0 && // Don't try to find a sourcemap for e.g. node-internal: scripts
182
+ msg.params.url.startsWith("file:")) {
183
+ const url = new URL(msg.params.sourceMapURL, msg.params.url);
184
+ if (url.protocol === "file:") {
185
+ msg.params.sourceMapURL = url.href.replace("file:", "wrangler-file:");
186
+ }
187
+ }
188
+ void this.sendDevToolsMessage(msg);
189
+ }
190
+ tryDrainRuntimeMessageBuffer = () => {
191
+ if (this.websockets.devtools === void 0)
192
+ return;
193
+ for (const msg of this.runtimeMessageBuffer.splice(0)) {
194
+ if (isDevToolsEvent(msg, "Debugger.scriptParsed")) {
195
+ this.handleRuntimeScriptParsed(msg);
196
+ } else {
197
+ void this.sendDevToolsMessage(msg);
198
+ }
199
+ }
200
+ };
201
+ runtimeAbortController = new AbortController();
202
+ // will abort the in-flight websocket upgrade request to the remote runtime
203
+ runtimeKeepAliveInterval = null;
204
+ async reconnectRuntimeWebSocket() {
205
+ assert2(this.proxyData, "Expected this.proxyData to be defined");
206
+ this.sendDebugLog("reconnectRuntimeWebSocket");
207
+ this.websockets.runtime?.close();
208
+ this.websockets.runtime = void 0;
209
+ this.runtimeAbortController.abort();
210
+ this.runtimeAbortController = new AbortController();
211
+ this.websockets.runtimeDeferred = createDeferred(
212
+ this.websockets.runtimeDeferred
213
+ );
214
+ const runtimeWebSocketUrl = urlFromParts(
215
+ this.proxyData.userWorkerInspectorUrl
216
+ );
217
+ runtimeWebSocketUrl.protocol = this.proxyData.userWorkerUrl.protocol;
218
+ this.sendDebugLog("NEW RUNTIME WEBSOCKET", runtimeWebSocketUrl);
219
+ const upgrade = await fetch(runtimeWebSocketUrl, {
220
+ headers: {
221
+ ...this.proxyData.headers,
222
+ Upgrade: "websocket"
223
+ },
224
+ signal: this.runtimeAbortController.signal
225
+ });
226
+ const runtime = upgrade.webSocket;
227
+ if (!runtime) {
228
+ const error = new Error(
229
+ `Failed to establish the WebSocket connection: expected server to reply with HTTP status code 101 (switching protocols), but received ${upgrade.status} instead.`
230
+ );
231
+ this.websockets.runtimeDeferred.reject(error);
232
+ this.sendProxyControllerRequest({
233
+ type: "runtime-websocket-error",
234
+ error: serialiseError(error)
235
+ });
236
+ return;
237
+ }
238
+ this.websockets.runtime = runtime;
239
+ runtime.addEventListener("message", this.handleRuntimeIncomingMessage);
240
+ runtime.addEventListener("close", (event) => {
241
+ this.sendDebugLog("RUNTIME WEBSOCKET CLOSED", event.code, event.reason);
242
+ clearInterval(this.runtimeKeepAliveInterval);
243
+ if (this.websockets.runtime === runtime) {
244
+ this.websockets.runtime = void 0;
245
+ }
246
+ });
247
+ runtime.addEventListener("error", (event) => {
248
+ const error = serialiseError(event.error);
249
+ this.sendDebugLog("RUNTIME WEBSOCKET ERROR", error);
250
+ clearInterval(this.runtimeKeepAliveInterval);
251
+ if (this.websockets.runtime === runtime) {
252
+ this.websockets.runtime = void 0;
253
+ }
254
+ this.sendProxyControllerRequest({
255
+ type: "runtime-websocket-error",
256
+ error
257
+ });
258
+ });
259
+ runtime.accept();
260
+ this.handleRuntimeWebSocketOpen(runtime);
261
+ }
262
+ #runtimeMessageCounter = 1e8;
263
+ nextCounter() {
264
+ return ++this.#runtimeMessageCounter;
265
+ }
266
+ handleRuntimeWebSocketOpen(runtime) {
267
+ this.sendDebugLog("RUNTIME WEBSOCKET OPENED");
268
+ this.sendRuntimeMessage(
269
+ { method: "Runtime.enable", id: this.nextCounter() },
270
+ runtime
271
+ );
272
+ this.sendRuntimeMessage(
273
+ { method: "Debugger.enable", id: this.nextCounter() },
274
+ runtime
275
+ );
276
+ this.sendRuntimeMessage(
277
+ { method: "Network.enable", id: this.nextCounter() },
278
+ runtime
279
+ );
280
+ clearInterval(this.runtimeKeepAliveInterval);
281
+ this.runtimeKeepAliveInterval = setInterval(() => {
282
+ this.sendRuntimeMessage(
283
+ { method: "Runtime.getIsolateId", id: this.nextCounter() },
284
+ runtime
285
+ );
286
+ }, 1e4);
287
+ this.websockets.runtimeDeferred.resolve(runtime);
288
+ }
289
+ sendRuntimeDiscardConsoleEntries() {
290
+ if (this.websockets.runtime) {
291
+ this.sendRuntimeMessage(
292
+ {
293
+ method: "Runtime.discardConsoleEntries",
294
+ id: this.nextCounter()
295
+ },
296
+ this.websockets.runtime
297
+ );
298
+ }
299
+ }
300
+ async sendRuntimeMessage(message, runtime = this.websockets.runtimeDeferred.promise) {
301
+ runtime = await runtime;
302
+ message = typeof message === "string" ? message : JSON.stringify(message);
303
+ this.sendDebugLog("SEND TO RUNTIME", message);
304
+ runtime.send(message);
305
+ }
306
+ // ****************
307
+ // ** DEVTOOLS **
308
+ // ****************
309
+ #inspectorId = crypto.randomUUID();
310
+ async handleDevToolsJsonRequest(req) {
311
+ const url = new URL(req.url);
312
+ if (url.pathname === "/json/version") {
313
+ return Response.json({
314
+ Browser: `wrangler/v${this.env.WRANGLER_VERSION}`,
315
+ // TODO: (someday): The DevTools protocol should match that of workerd.
316
+ // This could be exposed by the preview API.
317
+ "Protocol-Version": "1.3"
318
+ });
319
+ }
320
+ if (url.pathname === "/json" || url.pathname === "/json/list") {
321
+ const localHost = `${url.host}/ws`;
322
+ const devtoolsFrontendUrl = `https://devtools.devprod.cloudflare.dev/js_app?theme=systemPreferred&debugger=true&ws=${localHost}`;
323
+ return Response.json([
324
+ {
325
+ id: this.#inspectorId,
326
+ type: "node",
327
+ // TODO: can we specify different type?
328
+ description: "workers",
329
+ webSocketDebuggerUrl: `ws://${localHost}`,
330
+ devtoolsFrontendUrl,
331
+ devtoolsFrontendUrlCompat: devtoolsFrontendUrl,
332
+ // Below are fields that are visible in the DevTools UI.
333
+ title: "Cloudflare Worker",
334
+ faviconUrl: "https://workers.cloudflare.com/favicon.ico"
335
+ // url: "http://" + localHost, // looks unnecessary
336
+ }
337
+ ]);
338
+ }
339
+ return new Response(null, { status: 404 });
340
+ }
341
+ async handleDevToolsWebSocketUpgradeRequest(req) {
342
+ let hostHeader = req.headers.get("Host");
343
+ if (hostHeader == null)
344
+ return new Response(null, { status: 400 });
345
+ try {
346
+ const host = new URL(`http://${hostHeader}`);
347
+ if (!ALLOWED_HOST_HOSTNAMES.includes(host.hostname)) {
348
+ return new Response("Disallowed `Host` header", { status: 401 });
349
+ }
350
+ } catch {
351
+ return new Response("Expected `Host` header", { status: 400 });
352
+ }
353
+ let originHeader = req.headers.get("Origin");
354
+ if (originHeader === null && !req.headers.has("User-Agent")) {
355
+ originHeader = "http://localhost";
356
+ }
357
+ if (originHeader === null) {
358
+ return new Response("Expected `Origin` header", { status: 400 });
359
+ }
360
+ try {
361
+ const origin = new URL(originHeader);
362
+ const allowed = ALLOWED_ORIGIN_HOSTNAMES.some((rule) => {
363
+ if (typeof rule === "string")
364
+ return origin.hostname === rule;
365
+ else
366
+ return rule.test(origin.hostname);
367
+ });
368
+ if (!allowed) {
369
+ return new Response("Disallowed `Origin` header", { status: 401 });
370
+ }
371
+ } catch {
372
+ return new Response("Expected `Origin` header", { status: 400 });
373
+ }
374
+ this.sendDebugLog("DEVTOOLS WEBSOCKET TRYING TO CONNECT");
375
+ await this.websockets.runtimeDeferred.promise;
376
+ this.sendDebugLog("DEVTOOLS WEBSOCKET CAN NOW CONNECT");
377
+ assert2(
378
+ req.headers.get("Upgrade") === "websocket",
379
+ "Expected DevTools connection to be WebSocket upgrade"
380
+ );
381
+ const { 0: response, 1: devtools } = new WebSocketPair();
382
+ devtools.accept();
383
+ if (this.websockets.devtools !== void 0) {
384
+ devtools.close(
385
+ 1013,
386
+ "Too many clients; only one can be connected at a time"
387
+ );
388
+ } else {
389
+ devtools.addEventListener("message", this.handleDevToolsIncomingMessage);
390
+ devtools.addEventListener("close", (event) => {
391
+ this.sendDebugLog(
392
+ "DEVTOOLS WEBSOCKET CLOSED",
393
+ event.code,
394
+ event.reason
395
+ );
396
+ if (this.websockets.devtools === devtools) {
397
+ this.websockets.devtools = void 0;
398
+ }
399
+ });
400
+ devtools.addEventListener("error", (event) => {
401
+ const error = serialiseError(event.error);
402
+ this.sendDebugLog("DEVTOOLS WEBSOCKET ERROR", error);
403
+ if (this.websockets.devtools === devtools) {
404
+ this.websockets.devtools = void 0;
405
+ }
406
+ });
407
+ this.sendRuntimeMessage({
408
+ id: this.nextCounter(),
409
+ method: "Debugger.disable"
410
+ });
411
+ this.sendDebugLog("DEVTOOLS WEBSOCKET CONNECTED");
412
+ const userAgent = req.headers.get("User-Agent") ?? "";
413
+ const hasFileSystemAccess = !/mozilla/i.test(userAgent);
414
+ this.websockets.devtools = devtools;
415
+ this.websockets.devtoolsHasFileSystemAccess = hasFileSystemAccess;
416
+ this.tryDrainRuntimeMessageBuffer();
417
+ }
418
+ return new Response(null, { status: 101, webSocket: response });
419
+ }
420
+ handleDevToolsIncomingMessage = (event) => {
421
+ assert2(
422
+ typeof event.data === "string",
423
+ "Expected devtools incoming message to be of type string"
424
+ );
425
+ const message = JSON.parse(event.data);
426
+ this.sendDebugLog("DEVTOOLS INCOMING MESSAGE", message);
427
+ if (message.method === "Network.loadNetworkResource") {
428
+ return void this.handleDevToolsLoadNetworkResource(message);
429
+ }
430
+ this.sendRuntimeMessage(JSON.stringify(message));
431
+ };
432
+ async handleDevToolsLoadNetworkResource(message) {
433
+ const response = await this.sendProxyControllerRequest({
434
+ type: "load-network-resource",
435
+ url: message.params.url
436
+ });
437
+ if (response === void 0) {
438
+ this.sendDebugLog(
439
+ `ProxyController could not resolve Network.loadNetworkResource for "${message.params.url}"`
440
+ );
441
+ this.sendRuntimeMessage(JSON.stringify(message));
442
+ } else {
443
+ this.sendDevToolsMessage({
444
+ id: message.id,
445
+ // @ts-expect-error DevTools Protocol type does not match our patched devtools -- result.resource.text was added
446
+ result: { resource: { success: true, text: response } }
447
+ });
448
+ }
449
+ }
450
+ sendDevToolsMessage(message) {
451
+ message = typeof message === "string" ? message : JSON.stringify(message);
452
+ this.sendDebugLog("SEND TO DEVTOOLS", message);
453
+ this.websockets.devtools?.send(message);
454
+ }
455
+ };
456
+ export {
457
+ InspectorProxyWorker,
458
+ InspectorProxyWorker_default as default
459
+ };
460
+ //# sourceMappingURL=InspectorProxyWorker.js.map