import{r as t}from"./react-vendor-MPLM8hiW.js";const B=1e3,O=3e4;function I(h,g,b={}){const{enabled:S=!0,initialBackoffMs:_=B,maxBackoffMs:v=O,maxAttempts:y=-1,onMessage:A}=b,m=t.useRef(g),E=t.useRef(A);m.current=g,E.current=A;const[k,o]=t.useState("idle"),[w,f]=t.useState(0),[F,T]=t.useState(0),d=t.useRef(null),p=t.useRef(null),r=t.useRef(0),u=t.useCallback(()=>{if(p.current!==null&&(clearTimeout(p.current),p.current=null),d.current){const n=d.current;d.current=null;const l=n.__teardown;try{l==null||l(),n.close()}catch{}}},[]);t.useEffect(()=>{if(!S||!h||typeof window>"u"||!("EventSource"in window)){u(),o("idle"),r.current=0,f(0);return}let n=!1;const l=(e,R)=>{let s;try{const i=JSON.parse(R);s=i&&typeof i=="object"&&"type"in i?i:{type:e,data:i,channel:"",timestamp:""}}catch{return}const a=m.current[e]??(s.type?m.current[s.type]:void 0);a?a(s):E.current&&E.current(s)},M=()=>{if(n)return;if(u(),y!==-1&&r.current>=y){o("offline");return}r.current+=1,f(r.current);const e=Math.min(v,_*2**(r.current-1));o("reconnecting"),p.current=setTimeout(L,e)};function L(){if(n)return;u(),o(r.current===0?"connecting":"reconnecting");let e;try{e=new EventSource(h)}catch{M();return}d.current=e,e.onopen=()=>{n||(r.current=0,f(0),o("online"))},e.onerror=()=>{n||d.current!==e||M()};const R=c=>{l("message",c.data)};e.addEventListener("message",R);const s=[];for(const c of Object.keys(m.current)){if(c==="message")continue;const a=i=>{l(c,i.data)};e.addEventListener(c,a),s.push([c,a])}e.__teardown=()=>{e.removeEventListener("message",R);for(const[c,a]of s)e.removeEventListener(c,a)}}return r.current=0,f(0),L(),()=>{n=!0,u(),o("idle")}},[u,S,_,F,y,v,h]);const C=t.useCallback(()=>{u(),o("idle")},[u]),x=t.useCallback(()=>{r.current=0,f(0),T(n=>n+1)},[]);return{status:k,reconnectAttempt:w,close:C,reconnect:x}}export{I as u};
