import{i as e}from"./useAnalytics-D7ict_xi.js";import{n as t}from"./events-Bc6cZn5G.js";var n=1e3,r=3e4,i=1e3,a=e(`websocket`,{state(){return{socket:null,isConnected:!1,messages:[],latestMessage:``,reconnectError:!1,url:null,reconnectAttempts:0,reconnectTimer:null,manualDisconnect:!1}},getters:{getSocket:e=>e.socket,getIsConnected:e=>e.isConnected,getLatestMessage:e=>e.messages[e.messages.length-1],getMessages:e=>e.messages,getReconnectError:e=>e.reconnectError},actions:{_establishConnection(){return this.url?(this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.close()),this.socket=new WebSocket(this.url),new Promise((e,n)=>{this.socket.onopen=()=>{console.log(`WebSocket connection established.`),this.isConnected=!0,this.reconnectAttempts=0,this.reconnectError=!1,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),e()},this.socket.onmessage=e=>{if(e.data!==`KeepAlive`){this.messages.length>100&&this.messages.shift(),this.messages.push(e.data),this.latestMessage=e.data;try{let n=JSON.parse(e.data);if(!n.type)return;t.emit(`ws:message`,n)}catch(e){console.error(`Failed to parse WebSocket message:`,e)}}},this.socket.onclose=()=>{this.isConnected=!1,this.socket=null,console.log(`WebSocket connection closed.`),this.manualDisconnect||(this.reconnectError=!0,this._reconnect())},this.socket.onerror=e=>{console.error(`WebSocket error:`,e),this.reconnectError=!0,n(e)}})):Promise.reject(Error(`WebSocket URL is not set.`))},_reconnect(){if(this.reconnectTimer)return;this.reconnectAttempts++;let e=Math.min(r,2**this.reconnectAttempts*n+Math.random()*i);console.log(`WebSocket disconnected. Attempting to reconnect in ${Math.round(e/1e3)}s... (Attempt ${this.reconnectAttempts})`),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this._establishConnection().catch(e=>{console.error(`Reconnect attempt ${this.reconnectAttempts} failed:`,e)})},e)},connect(e){return this.url=e,this.manualDisconnect=!1,this.reconnectAttempts=0,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this._establishConnection()},sendMessage(e){this.socket&&this.isConnected?this.socket.send(e):console.warn(`Cannot send message: WebSocket is not connected.`)},sendObject(e){if(this.socket&&this.isConnected){let t=JSON.stringify(e);this.socket.send(t)}else console.warn(`Cannot send object: WebSocket is not connected.`)},disconnect(){console.log(`Manual WebSocket disconnect requested.`),this.manualDisconnect=!0,this.reconnectTimer&&=(clearTimeout(this.reconnectTimer),null),this.socket&&this.socket.close(),this.isConnected=!1,this.socket=null,this.reconnectAttempts=0,this.reconnectError=!1}}});export{a as t};