import{A as v}from"./contracts.generated-BpQhIfeJ.js";import{aO as d,r as o,x as f,W as E,ad as i}from"./jwt-decode.esm-CuqABuF0.js";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},e=new Error().stack;e&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[e]="17f65d6f-c832-42f9-8930-790660fb3ba5",t._sentryDebugIdIdentifier="sentry-dbid-17f65d6f-c832-42f9-8930-790660fb3ba5")}catch{}})();class n{static instance=null;ws=null;reconnectTimer;keepaliveInterval;messageHandlers=new Set;KEEPALIVE_INTERVAL=3e4;RECONNECT_DELAY=1e3;constructor(){this.connect()}static getInstance(){return n.instance||(n.instance=new n),n.instance}get url(){return"/_editor/api/codebase/events"}handleMessage(e){try{const s=JSON.parse(e.data),r=v.parse(s);this.messageHandlers.forEach(c=>{try{c(r)}catch(a){d(a)}})}catch(s){d(s)}}handleClose(){this.clearTimers(),this.scheduleReconnect()}handleError(){this.clearTimers(),this.scheduleReconnect()}clearTimers(){this.keepaliveInterval&&(clearInterval(this.keepaliveInterval),this.keepaliveInterval=void 0),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0)}scheduleReconnect(){this.reconnectTimer||(this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.connect()},this.RECONNECT_DELAY))}startKeepalive(){this.keepaliveInterval=setInterval(()=>{this.sendKeepalive()},this.KEEPALIVE_INTERVAL)}sendKeepalive(){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.handleError();return}try{this.ws.send(JSON.stringify({type:"keepalive"}))}catch(e){console.error("CodebaseEventsService: Failed to send keepalive:",e),this.handleError()}}async connect(){if(this.ws?.readyState!==WebSocket.OPEN)try{this.ws=new WebSocket(this.url),this.ws.onopen=()=>this.startKeepalive(),this.ws.onclose=()=>this.handleClose(),this.ws.onerror=()=>this.handleError(),this.ws.onmessage=e=>this.handleMessage(e)}catch(e){console.error("CodebaseEventsService: Failed to create WebSocket:",e),this.scheduleReconnect()}}subscribe(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}isConnected(){return this.ws?.readyState===WebSocket.OPEN}}function m(){const t=o(!1),e=o(null),s=o(null),r=n.getInstance(),c=u=>{e.value=u},a=()=>{t.value=r.isConnected()};let l;const h=setInterval(a,1e3);return f(()=>{l(),clearInterval(h)}),E(()=>{l=r.subscribe(c),a()}),{isConnected:i(t),lastEvent:i(e),error:i(s),service:i(r)}}export{m as u};
//# sourceMappingURL=useCodebaseEvents-DR3Kflua.js.map
