From 639086b1611f81d41f80dd0945216312a4bc6566 Mon Sep 17 00:00:00 2001 From: DepsCian Date: Sun, 6 Apr 2025 13:01:19 +0300 Subject: [PATCH] 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. --- frontend/util/wsutil.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/frontend/util/wsutil.ts b/frontend/util/wsutil.ts index 0e3baaf7d8..6dd24e600f 100644 --- a/frontend/util/wsutil.ts +++ b/frontend/util/wsutil.ts @@ -3,15 +3,14 @@ import type { WebSocket as NodeWebSocketType } from "ws"; -let NodeWebSocket: typeof NodeWebSocketType = null; +let NodeWebSocket: any = null; -if (typeof window === "undefined") { - // Necessary to avoid issues with Rollup: https://github.com/websockets/ws/issues/2057 - import("ws") - .then((ws) => (NodeWebSocket = ws.default)) - .catch((e) => { - console.log("Error importing 'ws':", e); - }); +if (typeof window === "undefined" || (typeof process !== "undefined" && process.type === "browser")) { + try { + NodeWebSocket = require("ws").WebSocket; + } catch (e) { + import("ws").then((ws) => (NodeWebSocket = ws.default)).catch((e) => console.log("ws import error:", e)); + } } type ComboWebSocket = NodeWebSocketType | WebSocket; @@ -20,6 +19,9 @@ function newWebSocket(url: string, headers: { [key: string]: string }): ComboWeb if (NodeWebSocket) { return new NodeWebSocket(url, { headers }); } else { + if (typeof WebSocket === "undefined") { + throw new Error("WebSocket not available in this environment"); + } return new WebSocket(url); } }