Skip to content
This repository was archived by the owner on Oct 9, 2025. It is now read-only.

Commit 25a5fee

Browse files
authored
fix: ws conditional import (#444)
only import types and ws dependency if NATIVE_WEBSOCKET_AVAILABLE not available
1 parent 9ef7649 commit 25a5fee

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
lines changed

src/RealtimeClient.ts

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import type { WebSocket as WSWebSocket } from 'ws'
2-
31
import {
42
CHANNEL_EVENTS,
53
CONNECTION_STATE,
@@ -62,16 +60,20 @@ export interface WebSocketLikeConstructor {
6260
options?: { headers: Object | undefined }
6361
): WebSocketLike
6462
}
63+
const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined'
6564

66-
export type WebSocketLike = WebSocket | WSWebSocket | WSWebSocketDummy
65+
const WSWebSocket = NATIVE_WEBSOCKET_AVAILABLE
66+
? WebSocket
67+
: require('ws').WebSocket
68+
69+
export type WebSocketLike = WebSocket | typeof WSWebSocket | WSWebSocketDummy
6770

6871
export interface WebSocketLikeError {
6972
error: any
7073
message: string
7174
type: string
7275
}
7376

74-
const NATIVE_WEBSOCKET_AVAILABLE = typeof WebSocket !== 'undefined'
7577
const WORKER_SCRIPT = `
7678
addEventListener("message", (e) => {
7779
if (e.data.event === "start") {
@@ -204,20 +206,20 @@ export default class RealtimeClient {
204206
this.conn = new WebSocket(this.endpointURL())
205207
this.setupConnection()
206208
return
207-
}
208-
209-
this.conn = new WSWebSocketDummy(this.endpointURL(), undefined, {
210-
close: () => {
211-
this.conn = null
212-
},
213-
})
209+
} else {
210+
this.conn = new WSWebSocketDummy(this.endpointURL(), undefined, {
211+
close: () => {
212+
this.conn = null
213+
},
214+
})
214215

215-
import('ws').then(({ default: WS }) => {
216-
this.conn = new WS(this.endpointURL(), undefined, {
217-
headers: this.headers,
216+
import('ws').then(({ default: WS }) => {
217+
this.conn = new WS(this.endpointURL(), undefined, {
218+
headers: this.headers,
219+
})
220+
this.setupConnection()
218221
})
219-
this.setupConnection()
220-
})
222+
}
221223
}
222224

223225
/**
File renamed without changes.

0 commit comments

Comments
 (0)