Skip to content

Commit 639086b

Browse files
committed
fix: add WebSocket polyfill for Electron main process
Resolves ReferenceError where WebSocket was undefined in main process. Implements dual WebSocket loading strategy with proper environment detection and fallback mechanisms for Node.js contexts.
1 parent e7ecd9e commit 639086b

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

frontend/util/wsutil.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,14 @@
33

44
import type { WebSocket as NodeWebSocketType } from "ws";
55

6-
let NodeWebSocket: typeof NodeWebSocketType = null;
6+
let NodeWebSocket: any = null;
77

8-
if (typeof window === "undefined") {
9-
// Necessary to avoid issues with Rollup: https://github.com/websockets/ws/issues/2057
10-
import("ws")
11-
.then((ws) => (NodeWebSocket = ws.default))
12-
.catch((e) => {
13-
console.log("Error importing 'ws':", e);
14-
});
8+
if (typeof window === "undefined" || (typeof process !== "undefined" && process.type === "browser")) {
9+
try {
10+
NodeWebSocket = require("ws").WebSocket;
11+
} catch (e) {
12+
import("ws").then((ws) => (NodeWebSocket = ws.default)).catch((e) => console.log("ws import error:", e));
13+
}
1514
}
1615

1716
type ComboWebSocket = NodeWebSocketType | WebSocket;
@@ -20,6 +19,9 @@ function newWebSocket(url: string, headers: { [key: string]: string }): ComboWeb
2019
if (NodeWebSocket) {
2120
return new NodeWebSocket(url, { headers });
2221
} else {
22+
if (typeof WebSocket === "undefined") {
23+
throw new Error("WebSocket not available in this environment");
24+
}
2325
return new WebSocket(url);
2426
}
2527
}

0 commit comments

Comments
 (0)