@pipecat-ai/gemini-live-websocket-transport 0.3.3
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.
- package/LICENSE +24 -0
- package/README.md +124 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1006 -0
- package/dist/index.js.map +1 -0
- package/dist/index.module.js +989 -0
- package/dist/index.module.js.map +1 -0
- package/package.json +43 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A,I,kC,a,U,S,I,A;I,I,gB,S,C,E,C;Q,gB,O,c,I,C;Y,W,E;Q,C,a,S,S,C,E,C;Y,E,S,G;Q,K,S,C,E,C;Y,I,I,K,E,I,O,S,C,c,C,I,C,G,I,C,C,E,G,C,C,E;Q;Q,O,c,G;I;I,O,S,C,E,C;Q,I,O,M,c,M,M,M,I,U,yB,O,K;Q,c,G;Q,S;Y,I,C,W,G;Q;Q,E,S,G,M,O,O,M,C,K,C,G,S,G,E,S,E,I,I;I;A;A,I,kC,a,U,S,I,S,O,E,U,E,C,E,S;I,S,M,K;Q,O,iB,I,Q,I,E,S,O;Y,Q;Q;I;I,O,I,C,K,C,I,O,C,E,S,O,E,M;Q,S,U,K;Y,I;gB,K,U,I,C;Y,E,O,G;gB,O;Y;Q;Q,S,S,K;Y,I;gB,K,S,C,Q,C;Y,E,O,G;gB,O;Y;Q;Q,S,K,M;Y,O,I,G,Q,O,K,I,M,O,K,E,I,C,W;Q;Q,K,A,C,Y,U,K,C,S,c,E,C,E,I;I;A;A,I,oC,a,U,W,I,S,O,E,I;I,I,I;Q,O;Q,M;Y,I,C,C,E,G,G,M,C,C,E;Y,O,C,C,E;Q;Q,M,E;Q,K,E;I,G,G,G,G,I,O,M,C,A,C,O,a,a,W,M,E,S;I,O,E,I,G,K,I,C,C,Q,G,K,I,C,C,S,G,K,I,O,W,c,C,C,C,O,Q,C,G;Q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KAAK,UAAU,IAAI,EAAE;YAC1C,QAAQ,KAAK,CAAC;YACd;QACF;QACA,IAAI,CAAC,KAAK;YACR,QAAQ,KAAK,CAAC;YACd;QACF;QACA,IAAI;YACF,MAAM,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,SAAS,CAAC;QACrC,EAAE,OAAO,GAAG;YACV,QAAQ,KAAK,CAAC,iBAAiB;QACjC;IACF;AACD;AAED,SAAS,0CAAoB,MAAc;IACzC,MAAM,eAAe,KAAK;IAC1B,MAAM,MAAM,aAAa,MAAM;IAC/B,MAAM,QAAQ,IAAI,WAAW;IAC7B,IAAK,IAAI,IAAI,GAAG,IAAI,KAAK,IACvB,KAAK,CAAC,EAAE,GAAG,aAAa,UAAU,CAAC;IAErC,OAAO,MAAM,MAAM;AACrB;AAEA,SAAS,0CAAoB,MAAmB;IAC9C,MAAM,QAAQ,IAAI,WAAW;IAC7B,IAAI,SAAS;IACb,IAAK,IAAI,IAAI,GAAG,IAAI,MAAM,UAAU,EAAE,IACpC,UAAU,OAAO,YAAY,CAAC,KAAK,CAAC,EAAE;IAExC,OAAO,KAAK;AACd;AAEA,SAAS,mCACP,UAAuB,EACvB,WAAwB;IAExB,MAAM,WAAW,IAAI,WACnB,WAAW,UAAU,GAAG,YAAY,UAAU;IAEhD,SAAS,GAAG,CAAC,IAAI,WAAW,aAAa;IACzC,SAAS,GAAG,CAAC,IAAI,WAAW,cAAc,WAAW,UAAU;IAC/D,OAAO,SAAS,MAAM;AACxB","sources":["transports/gemini-live-websocket-transport/src/index.ts","transports/gemini-live-websocket-transport/src/geminiLiveWebSocketTransport.ts","lib/websocket-utils/reconnectingWebSocket.ts"],"sourcesContent":["export * from \"./geminiLiveWebSocketTransport\";\n","import {\n DailyMediaManager,\n MediaManager,\n RealTimeWebsocketTransport,\n LLMServiceOptions,\n} from \"@pipecat-ai/realtime-websocket-transport\";\n\nimport { ReconnectingWebSocket } from \"../../../lib/websocket-utils/reconnectingWebSocket.js\";\nimport {\n RTVIMessage,\n RTVIMessageType,\n TransportStartError,\n} from \"@pipecat-ai/client-js\";\n\nconst HOST = `generativelanguage.googleapis.com`;\nconst BIDI_PATH = `google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent`;\nconst MODEL = \"models/gemini-2.0-flash-exp\";\n\nexport interface GeminiLLMServiceOptions extends LLMServiceOptions {\n initial_messages?: Array<{ content: string; role: string }>;\n api_key: string;\n generation_config?: {\n candidate_count?: number;\n maxOutput_tokens?: number;\n temperature?: number;\n top_p?: number;\n top_k?: number;\n presence_penalty?: number;\n frequency_penalty?: number;\n response_modalities?: string;\n speech_config?: {\n voice_config?: {\n prebuilt_voice_config?: {\n voice_name: \"Puck\" | \"Charon\" | \"Kore\" | \"Fenrir\" | \"Aoede\";\n // | \"Voice O\";\n };\n };\n };\n };\n}\n\nexport class GeminiLiveWebsocketTransport extends RealTimeWebsocketTransport {\n private declare _ws: ReconnectingWebSocket | null;\n private declare _botResponseID: number;\n private declare _botIsReadyResolve:\n | ((value: void | PromiseLike<void>) => void)\n | null;\n\n constructor(\n service_options: GeminiLLMServiceOptions,\n manager?: MediaManager\n ) {\n if (!manager) {\n manager = new DailyMediaManager();\n }\n super(service_options, manager);\n\n this._ws = null;\n\n this._botResponseID = 0;\n }\n\n initializeLLM(): void {\n const service_options = this._service_options as GeminiLLMServiceOptions;\n const apiKey = service_options.api_key;\n if (!apiKey) {\n console.error(\"!!! No API key provided in llm_service_optsion\");\n return;\n }\n const base_url = `wss://${HOST}/ws/${BIDI_PATH}`;\n this._ws = new ReconnectingWebSocket(`${base_url}?key=${apiKey}`);\n // don't run the keep alive interval until we determine if there's an api for it\n this._ws.keepAliveInterval = 0;\n }\n\n // This is called from super.initialize()\n attachLLMListeners(): void {\n if (!this._ws) {\n console.error(\n \"attachLLMListeners called before the websocket is initialized. Be sure to call initializeLLM() first.\"\n );\n return;\n }\n this._ws.on(\"open\", () => {});\n this._ws.on(\"message\", async (msg: any) => {\n const content = msg.serverContent;\n if (!content) {\n if (\"setupComplete\" in msg) {\n this.state = \"ready\";\n if (this._botIsReadyResolve) {\n this._botIsReadyResolve();\n this._botIsReadyResolve = null;\n }\n } else {\n console.log(\"received unknown message\", msg);\n }\n return;\n }\n if (content.modelTurn) {\n let result: ArrayBuffer | null = null;\n content.modelTurn.parts?.forEach((part: { inlineData: any }) => {\n if (part.inlineData?.data) {\n if (result) {\n mergeBuffers(result, base64ToArrayBuffer(part.inlineData.data));\n } else {\n result = base64ToArrayBuffer(part.inlineData.data);\n }\n }\n });\n if (result) {\n if (!this._botIsSpeaking) {\n this._botResponseID++;\n this.botStartedSpeaking();\n }\n this.bufferBotAudio(result, this._botResponseID.toString());\n }\n } else if (content.interrupted) {\n await this.userStartedSpeaking();\n } else if (content.turnComplete) {\n this.botStoppedSpeaking();\n } else {\n // console.log('unhandled message', content);\n }\n });\n this._ws.on(\"error\", (error: Error) => {\n this.connectionError(`websocket error: ${error}`);\n });\n this._ws.on(\"connection-timeout\", () => {\n this.connectionError(\"websocket connection timed out\");\n });\n this._ws.on(\"close\", (code: number) => {\n this.connectionError(`websocket connection closed. Code: ${code}`);\n });\n this._ws.on(\"reconnect-failed\", () => {\n this.connectionError(`websocket reconnect failed`);\n });\n }\n\n async connectLLM(): Promise<void> {\n if (!this._ws) {\n console.error(\n \"connectLLM called before the websocket is initialized. Be sure to call initializeLLM() first.\"\n );\n return;\n }\n try {\n await this._ws.connect();\n } catch (error) {\n const msg = `Failed to connect to LLM: ${error}`;\n console.error(msg);\n this.state = \"error\";\n throw new TransportStartError(msg);\n }\n\n const service_options = this._service_options as GeminiLLMServiceOptions;\n const model = service_options?.model ?? MODEL;\n const generation_config = service_options?.generation_config ?? {};\n let config = { setup: { model, generation_config } };\n await this._sendMsg(config);\n\n // For this bare-bones prototype, let's just see if we have any initial_messages in the params\n // we were constructed with.\n if (service_options?.initial_messages) {\n service_options.initial_messages.forEach(\n (msg: { content: string; role: string }) => {\n this._sendTextInput(msg.content, msg.role);\n }\n );\n }\n }\n\n async disconnectLLM(): Promise<void> {\n await this._ws?.close();\n }\n\n async sendReadyMessage(): Promise<void> {\n const p = new Promise<void>((resolve) => {\n if (this.state === \"ready\") {\n resolve();\n } else {\n this._botIsReadyResolve = resolve;\n }\n });\n await p;\n this._onMessage({\n type: RTVIMessageType.BOT_READY,\n data: {},\n } as RTVIMessage);\n }\n\n handleUserAudioStream(data: ArrayBuffer): void {\n if (this.state === \"ready\") {\n try {\n void this._sendAudioInput(data);\n } catch (error) {\n console.error(\"Error adding audio to stream player\", error);\n this.state = \"error\";\n // todo: should check this error more carefully, implement disconnect, implement\n // ping/ack connection monitoring and reconnection logic, etc.\n }\n }\n }\n\n sendMessage(message: RTVIMessage): void {\n if (message?.type === \"send-text\") {\n this._sendTextInput(message.data as string, \"user\");\n }\n }\n\n async _sendAudioInput(data: ArrayBuffer): Promise<void> {\n // TODO: pull this number from the media manager\n const sampleRate = 24000;\n const msg = {\n realtimeInput: {\n mediaChunks: [\n {\n mimeType: `audio/pcm;rate=${sampleRate}`,\n data: arrayBufferToBase64(data),\n },\n ],\n },\n };\n await this._sendMsg(msg);\n }\n\n async _sendTextInput(text: string, role: string): Promise<void> {\n const msg = {\n clientContent: {\n turns: [\n {\n role,\n parts: [{ text }],\n },\n ],\n turnComplete: true,\n },\n };\n await this._sendMsg(msg);\n }\n\n async _sendMsg(msg: unknown): Promise<void> {\n if (!this._ws) {\n console.error(\"sendMsg called but WS is null\");\n return;\n }\n if (this._ws.readyState !== WebSocket.OPEN) {\n console.error(\"attempt to send to closed socket\");\n return;\n }\n if (!msg) {\n console.error(\"need a msg to send a msg\");\n return;\n }\n try {\n await this._ws.send(JSON.stringify(msg));\n } catch (e) {\n console.error(\"sendMsg error\", e);\n }\n }\n}\n\nfunction base64ToArrayBuffer(base64: string): ArrayBuffer {\n const binaryString = atob(base64);\n const len = binaryString.length;\n const bytes = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes.buffer;\n}\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let binary = \"\";\n for (let i = 0; i < bytes.byteLength; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\nfunction mergeBuffers(\n leftBuffer: ArrayBuffer,\n rightBuffer: ArrayBuffer\n): ArrayBuffer {\n const tmpArray = new Uint8Array(\n leftBuffer.byteLength + rightBuffer.byteLength\n );\n tmpArray.set(new Uint8Array(leftBuffer), 0);\n tmpArray.set(new Uint8Array(rightBuffer), leftBuffer.byteLength);\n return tmpArray.buffer;\n}\n","import { EventEmitter } from \"events\";\n\nconst readyStates = [\"CONNECTING\", \"OPEN\", \"CLOSING\", \"CLOSED\"];\nconst KEEP_ALIVE_INTERVAL = 5000;\nconst KEEP_ALIVE_TIMEOUT = 15000;\n// client side code in soupSFU has a timeout of 15 seconds for command response\n// 5 seconds seems reasonable that it provides roughly 3 retry attempts\nconst WEBSOCKET_CONNECTION_TIMEOUT = 150 * 1000;\nconst DEFAULT_RECONNECT_ATTEMPTS = 2;\nconst MAX_RECONNECT_ATTEMPTS = 10;\nconst DEFAULT_RECONNECT_INTERVAL = 1000;\nconst MAX_RECONNECT_INTERVAL = 30 * 1000;\nconst DEFAULT_RECONNECT_DECAY = 1.5;\n\nconst WEBSOCKET_TIMEOUT_CODE = 4100;\n\nconst SIG_CONNECTION_CANCELED = \"SIG_CONNECTION_CANCELED\";\nconst WEBSOCKET_ERROR = \"WEBSOCKET_ERROR\";\n\nenum LOG_LEVEL {\n DEBUG,\n ERROR,\n INFO,\n WARN,\n}\n\nclass rWebSocket {\n private _ws: WebSocket;\n _closedManually: boolean = false;\n _errored: boolean = false;\n _rejected: boolean = false;\n _timed_out: boolean = false;\n _initialConnectionOk: string | boolean = false;\n\n constructor(url: string, protocols?: string | string[]) {\n this._ws = new WebSocket(url, protocols);\n }\n\n addEventListener(\n type: string,\n listener: (this: WebSocket, ev: Event) => any\n ) {\n this._ws.addEventListener(type, listener);\n }\n\n // Add other WebSocket methods as needed\n close(code?: number, reason?: string) {\n this._ws.close(code, reason);\n }\n\n send(data: string | ArrayBuffer | Blob | ArrayBufferView) {\n this._ws.send(data);\n }\n\n // Add getters for WebSocket properties\n get url() {\n return this._ws.url;\n }\n\n get readyState() {\n return this._ws.readyState;\n }\n}\n\n/**\n * Builds on top of Javascript Websockets\n *\n * This behaves like the Websocket library in every way, except if it fails to\n * connect or if it gets disconnected, it will try to reconnect depending on\n * the maximum number of reconnect attempts set. retry is not enabled for initial\n * connection. When initial connection fails it is best to check yourself before\n * you keep wreckin' yourself.\n *\n * It is API compatible, so when you have:\n * ws = new WebSocket('ws://....');\n * you can replace with:\n * ws = new ReconnectingWebSocket('ws://....');\n *\n * While it is API compatible with the NodeJS ws library, we provide the\n * following additional properties and events on the ReconnectingWebSocket.\n *\n * Events:\n *\n * connection-timeout\n * - Emitted when the web socket connection times out.\n *\n * reconnecting\n * - Emitted after a manual close of the web socket is done and before retrying\n * the connection.\n *\n * reconnect-failed\n * - Emitted when the number of connection attempts exceeds the set number of\n * reconnection attempts.\n *\n * keep-alive\n * - Emitted when the set keep alive interval elapses. This event may be used\n * to have ping pong keep-alive mechanism for web socket health.\n *\n * Properties:\n *\n * keepAliveTimeout\n * - The timeout for keep-alive. Default: 15000\n *\n * keepAliveInterval\n * - The interval at which to emit keep-alive event. Default: 5000\n *\n * shouldRetryFn\n * - A callback function which should return boolean to determine if a web\n * socket reconnection attempt should be made. When not set, connection is\n * always retried.\n *\n * connectionTimeout\n * - The timeout interval for considering whether the connection timed out.\n * Default: 20000 ms\n *\n * maxReconnectAttempts\n * - The maximum number of attempts to be made for reconnection. Default: 2\n *\n * reconnectInterval\n * - The interval to wait before attempting a reconnection. Default: 1000 ms\n */\nexport class ReconnectingWebSocket extends EventEmitter {\n /** The connection is not yet open. */\n static readonly CONNECTING: 0;\n /** The connection is open and ready to communicate. */\n static readonly OPEN: 1;\n /** The connection is in the process of closing. */\n static readonly CLOSING: 2;\n /** The connection is closed. */\n static readonly CLOSED: 3;\n\n private _ws: rWebSocket | null;\n\n _url: string;\n _protocols: string | string[] | undefined;\n\n private declare _keepAliveTimeout: number;\n private declare _keepAliveInterval: number;\n private declare _lastMsgRecvTime: number;\n private declare _lastMsgSendTime: number;\n private declare _disconnected: boolean;\n private declare _keepIntervalID: NodeJS.Timeout | null;\n private declare _connectionTimeout: number;\n private declare _connectionTimeoutID: NodeJS.Timeout | undefined;\n private declare _reconnectTimeoutID: NodeJS.Timeout | undefined;\n private declare _shouldRetryFn: (() => boolean) | null;\n private declare _reconnectAttempts: number;\n private declare _allowedReconnectAttempts: number;\n private declare _reconnectInterval: number;\n private declare _maxReconnectInterval: number;\n private declare _reconnectDecay: number;\n\n constructor(address: string, protocols?: string | string[]) {\n super();\n\n if (!address) {\n throw new Error(\"Need a valid WebSocket URL\");\n }\n\n this._ws = null;\n\n this._url = address;\n this._protocols = protocols;\n\n this.init();\n }\n\n private init() {\n this._keepAliveTimeout = KEEP_ALIVE_TIMEOUT;\n this._keepAliveInterval = KEEP_ALIVE_INTERVAL;\n this._disconnected = false;\n this._keepIntervalID = null;\n this._shouldRetryFn = null;\n this._connectionTimeout = WEBSOCKET_CONNECTION_TIMEOUT;\n this._reconnectAttempts = 0;\n this._allowedReconnectAttempts = DEFAULT_RECONNECT_ATTEMPTS;\n this._reconnectInterval = DEFAULT_RECONNECT_INTERVAL;\n this._maxReconnectInterval = MAX_RECONNECT_INTERVAL;\n this._reconnectDecay = DEFAULT_RECONNECT_DECAY;\n }\n\n public async connect() {\n return new Promise((resolve, reject) => {\n this._disconnected = false;\n this.clearReconnectTimeout();\n\n let ws: rWebSocket = new rWebSocket(this._url, this._protocols);\n this.setConnectionTimeout();\n\n ws.addEventListener(\"close\", (evt) => {\n const closeEvent = evt as CloseEvent;\n let code = ws._timed_out ? WEBSOCKET_TIMEOUT_CODE : closeEvent.code;\n let reason = ws._timed_out\n ? \"websocket connection timed out\"\n : closeEvent.reason;\n ws._timed_out = false;\n if (!ws._closedManually && ws._initialConnectionOk) {\n console.warn(\n `signaling socket closed unexpectedly: ${code}${\n reason ? \" \" + reason : \"\"\n }`\n );\n this._closeSocket();\n this.emit(\"close\", code, reason);\n } else {\n this.log(\"signaling socket closed\");\n }\n if (!ws._closedManually && (ws._errored || ws._timed_out)) {\n console.warn(\n `signaling socket closed on error: ${code}${\n reason ? \" \" + reason : \"\"\n }`\n );\n if (!ws._rejected) {\n ws._rejected = true;\n const err = new Error(\n `WebSocket connection error (${code}): ${reason}`\n );\n err.name = WEBSOCKET_ERROR;\n reject(err);\n }\n }\n });\n ws.addEventListener(\"open\", (evt) => {\n this.log(\"wss connection opened to\", LOG_LEVEL.DEBUG, this._url);\n this.clearConnectionTimeout();\n // now that the timeout closes the socket, in theory this onopen\n // callback should never happen in the first place, but seems\n // harmless to leave these safeguards in\n if (ws._rejected || ws._timed_out) {\n return;\n }\n if (ws._closedManually || (this._ws && this._ws !== ws)) {\n ws._rejected = true;\n ws.close();\n let err = Error(\n \"wss connection interrupted by disconnect or newer connection\"\n );\n err.name = SIG_CONNECTION_CANCELED;\n reject(err);\n return;\n }\n ws._initialConnectionOk = this._url;\n this._lastMsgRecvTime = Date.now();\n if (this._keepAliveInterval) {\n this._keepIntervalID = setInterval(\n () => this.checkSocketHealthAndSendKeepAlive(),\n this._keepAliveInterval\n );\n }\n this._ws = ws;\n this.emit(\"open\");\n resolve(ws);\n });\n ws.addEventListener(\"error\", (evt) => {\n // fyi: evt is an Event here, with 0 amount of helpful info. If there\n // happens to be info about the error, it's included in the\n // accompanying close event (because that make sense. shakes head)\n // SO. We do not reject here. Instead, we just set the _errored\n // flag on the socket so when the close event occurs, it knows to\n // reject the promise\n if (!ws._closedManually) {\n const wsTarget = evt.currentTarget as WebSocket;\n this.log(`websocket error event: ${wsTarget?.url}`);\n }\n ws._errored = true;\n });\n ws.addEventListener(\"message\", (msg) => {\n void this._handleMessage(msg as MessageEvent);\n });\n });\n }\n\n private setConnectionTimeout() {\n this._connectionTimeoutID = setTimeout(async () => {\n this.log(\"Connection reconnect attempt timed out.\");\n this.emit(\"connection-timeout\");\n this.clearConnectionTimeout();\n await this._closeSocket();\n }, this._connectionTimeout);\n }\n\n private clearConnectionTimeout() {\n clearTimeout(this._connectionTimeoutID);\n this._connectionTimeoutID = undefined;\n }\n\n private clearReconnectTimeout() {\n clearTimeout(this._reconnectTimeoutID);\n this._reconnectTimeoutID = undefined;\n }\n\n private clearKeepAliveInterval() {\n if (this._keepIntervalID) {\n clearInterval(this._keepIntervalID);\n this._keepIntervalID = null;\n }\n }\n\n private async checkSocketHealthAndSendKeepAlive() {\n if (!(this._ws && this._ws.readyState === WebSocket.OPEN)) {\n return;\n }\n\n if (!this._keepAliveTimeout || !this._keepAliveInterval) {\n return;\n }\n\n // See if we haven't gotten a message back recently, and if we\n // haven't, close the socket. the os timeouts to detect if a socket\n // has gone stale are longer than we want.\n if (Date.now() - this._lastMsgRecvTime > this._keepAliveTimeout) {\n this.log(\"Connection is stale, need to reconnect\", LOG_LEVEL.WARN);\n await this._closeSocket();\n return;\n }\n\n // Only emit the keep-alive event if we haven't sent anything else recently\n if (Date.now() - this._lastMsgSendTime < this._keepAliveInterval) {\n return;\n }\n\n this.log(\"Emitting keep-alive\", LOG_LEVEL.DEBUG);\n this.emit(\"keep-alive\");\n }\n\n // We use the word manually here to imply the application using this code\n // or this code itself will decide to close the socket.\n private async _closeSocket() {\n this.log(\"Closing\");\n try {\n this.clearKeepAliveInterval();\n this._lastMsgRecvTime = 0;\n\n if (this._ws) {\n this._ws._closedManually = true;\n this._ws.close();\n }\n\n // query retry function if we want to retry.\n const shouldRetry =\n this._ws?._initialConnectionOk &&\n this._shouldRetryFn &&\n this._shouldRetryFn();\n\n this._ws = null;\n\n if (shouldRetry) {\n this.log(\"Emitting reconnect\", LOG_LEVEL.DEBUG);\n this.emit(\"reconnecting\");\n await this.retryFailedConnection();\n }\n } catch (error) {\n this.log(`Error while closing and retrying: ${error}`, LOG_LEVEL.ERROR);\n }\n }\n\n private async retryFailedConnection() {\n if (this._reconnectAttempts < this._allowedReconnectAttempts) {\n if (this._reconnectTimeoutID) {\n this.log(\"Retry already scheduled\");\n return;\n }\n this.log(\"Retrying failed connection\");\n let timeout =\n // The timeout logic is taken from\n // https://github.com/joewalnes/reconnecting-websocket\n this._reconnectInterval *\n Math.pow(this._reconnectDecay, this._reconnectAttempts);\n timeout =\n timeout > this._maxReconnectInterval\n ? this._maxReconnectInterval\n : timeout;\n this.log(`Reconnecting in ${timeout / 1000} seconds`);\n\n this._reconnectAttempts += 1;\n this._reconnectTimeoutID = setTimeout(() => this.connect(), timeout);\n } else {\n this.log(\"Maximum connection retry attempts exceeded\", LOG_LEVEL.ERROR);\n this.emit(\"reconnect-failed\");\n }\n }\n\n private log(\n msg: string,\n log_level: LOG_LEVEL = LOG_LEVEL.DEBUG,\n ...args: any\n ) {\n switch (log_level) {\n case LOG_LEVEL.DEBUG:\n console.debug(`websocket: ${msg}`, ...args);\n break;\n case LOG_LEVEL.ERROR:\n console.error(`websocket: ${msg}`, ...args);\n break;\n case LOG_LEVEL.WARN:\n console.warn(`websocket: ${msg}`, ...args);\n break;\n case LOG_LEVEL.INFO:\n default:\n console.log(`websocket: ${msg}`, ...args);\n break;\n }\n }\n\n async send(data: any) {\n try {\n if (this._ws && this._ws.readyState === WebSocket.OPEN) {\n this._lastMsgSendTime = Date.now();\n this._ws.send(data);\n } else {\n this.log(`Failed to send data, web socket not open.`, LOG_LEVEL.ERROR);\n }\n } catch (error) {\n this.log(`Failed to send data. ${error}`, LOG_LEVEL.ERROR);\n }\n }\n\n async close() {\n try {\n this.log(\"Closing websocket\");\n this._disconnected = true;\n this.clearReconnectTimeout();\n this._closeSocket();\n } catch (error) {\n this.log(`Failed to close websocket. ${error}`);\n }\n }\n\n get readyState(): number {\n return this._ws?.readyState ?? WebSocket.CLOSED;\n }\n\n get url(): string {\n return this._url;\n }\n\n get keepAliveTimeout(): number {\n return this._keepAliveTimeout;\n }\n\n set keepAliveTimeout(keepAliveTimeout: number) {\n if (typeof keepAliveTimeout === \"number\") {\n this.log(`Setting ACK freshness timeout to ${keepAliveTimeout}`);\n this._keepAliveTimeout = keepAliveTimeout;\n }\n }\n\n get keepAliveInterval(): number {\n return this._keepAliveInterval;\n }\n\n set keepAliveInterval(keepAliveInterval: number) {\n if (typeof keepAliveInterval === \"number\") {\n this.log(`Setting keep-alive interval to ${keepAliveInterval}`);\n this._keepAliveInterval = keepAliveInterval;\n }\n }\n\n set shouldRetryFn(cb: () => boolean) {\n if (typeof cb === \"function\") {\n this._shouldRetryFn = cb;\n }\n }\n\n get connectionTimeout(): number {\n return this._connectionTimeout;\n }\n\n set connectionTimeout(timeout: number) {\n if (typeof timeout === \"number\") {\n this._connectionTimeout = timeout;\n }\n }\n\n get maxReconnectAttempts(): number {\n return this._allowedReconnectAttempts;\n }\n\n set maxReconnectAttempts(attempts: number) {\n if (attempts > 0 && attempts < MAX_RECONNECT_ATTEMPTS) {\n this.log(`Setting maximum connection retry attempts to ${attempts}`);\n this._allowedReconnectAttempts = attempts;\n } else {\n this._allowedReconnectAttempts = DEFAULT_RECONNECT_ATTEMPTS;\n }\n }\n\n get reconnectInterval(): number {\n return this._reconnectInterval;\n }\n\n set reconnectInterval(interval: number) {\n if (typeof interval === \"number\") {\n this._reconnectInterval =\n interval < this._maxReconnectInterval\n ? interval\n : this._maxReconnectInterval;\n }\n }\n\n async _handleMessage(event: MessageEvent) {\n this._lastMsgRecvTime = Date.now();\n const data = event.data;\n\n const _parsePromise = new Promise((resolve, reject) => {\n if (typeof data === \"string\") {\n // Handle text message\n resolve(data);\n } else if (data instanceof ArrayBuffer) {\n // Handle binary message\n const arrayBuffer = data;\n // Parse the ArrayBuffer as needed\n // Example: Convert ArrayBuffer to Uint8Array\n resolve(new Uint8Array(arrayBuffer));\n // Process the Uint8Array as needed\n } else if (data instanceof Blob) {\n // Handle Blob message\n const blob = data;\n // Convert Blob to ArrayBuffer\n const reader = new FileReader();\n reader.onload = () => {\n const text = reader.result as string;\n try {\n const json = JSON.parse(text);\n resolve(json);\n } catch (e) {\n console.error(\"Failed to parse JSON from Blob:\", e);\n }\n };\n reader.readAsText(blob);\n }\n });\n\n let msg = await _parsePromise;\n\n this.emit(\"message\", msg);\n }\n}\n\n[\n \"binaryType\",\n \"bufferedAmount\",\n \"extensions\",\n \"protocol\",\n \"readyState\",\n \"url\",\n \"keepAliveTimeout\",\n \"keepAliveInterval\",\n \"shouldRetryFn\",\n \"connectionTimeout\",\n \"maxReconnectAttempts\",\n \"reconnectInterval\",\n].forEach((property) => {\n Object.defineProperty(ReconnectingWebSocket.prototype, property, {\n enumerable: true,\n });\n});\n\n[\"CONNECTING\", \"OPEN\", \"CLOSING\", \"CLOSED\"].forEach((property) => {\n Object.defineProperty(ReconnectingWebSocket.prototype, property, {\n enumerable: true,\n value: readyStates.indexOf(property),\n });\n});\n\n[\"CONNECTING\", \"OPEN\", \"CLOSING\", \"CLOSED\"].forEach((property) => {\n Object.defineProperty(ReconnectingWebSocket, property, {\n enumerable: true,\n value: readyStates.indexOf(property),\n });\n});\n"],"names":[],"version":3,"file":"index.js.map"}
|