var C=Object.defineProperty;var m=(s,n,e)=>n in s?C(s,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[n]=e;var b=(s,n,e)=>(m(s,typeof n!="symbol"?n+"":n,e),e);import{R as y,u as R,C as k}from"./index-b983ad9b.js";import{r as h}from"./react-b0e0d18a.js";class v extends y{constructor(e){super(o=>{const r=this.socket;if(r&&r.readyState===1){const u=JSON.stringify(o);r.send(u)}},{logger:e==null?void 0:e.logger});b(this,"socket");b(this,"context",{});this.setReady(!1),this.setContext(e)}setContext(e){this.context={...this.context,...e},e!=null&&e.address&&this.connect()}connect(){const{address:e,protocols:o,open:r,close:u,logger:t}=this.context;if(!e)return;this.close(),t==null||t.debug(`ClientRPC connecting to ${e}...`);const a=new WebSocket(e,o);a.addEventListener("error",d=>{t==null||t.debug(`ClientRPC error: ${d.message}`),a.close()}),a.addEventListener("open",()=>{t==null||t.debug("ClientRPC connected"),this.setReady(!0),r&&r()}),a.addEventListener("message",({data:d})=>{if(d instanceof Blob){const f=new FileReader,l=()=>{f.DONE&&this.receive(String(f.result)),f.removeEventListener("loadend",l)};f.addEventListener("loadend",l),f.readAsArrayBuffer(d)}else this.receive(d)}),a.addEventListener("close",({code:d})=>{this.setReady(!1),d===1e3?(t==null||t.debug("ClientRPC closed normally"),u&&u()):(t==null||t.debug("ClientRPC closed unexpectedly"),setTimeout(()=>{this.connect()},5e3))}),this.socket=a}close(){this.socket&&(this.socket.close(),this.socket=void 0)}}const i={};function E(s,n){typeof s=="string"&&(s=s.split(","));const e=[];return s.forEach(o=>{i[o]||(i[o]=[],e.push(o)),i[o].push(n)}),e.length>0&&(console.debug(`messenger.subscribe ${e.join(",")}`),c==null||c.notify("subscribe",e)),()=>{const o=[];s.forEach(r=>{i[r]=i[r].filter(u=>u!==n),i[r].length===0&&(o.push(r),delete i[r])}),o.length>0&&(console.debug(`messenger.unsubscribe ${o.join(",")}`),c==null||c.notify("unsubscribe",o))}}const c=new v;c.on("message",(s,...n)=>{i[s]&&i[s].map(e=>e(...n))});function S(){const{accessToken:s}=R(),n=h.useRef();return h.useEffect(()=>{!s||n.current===s||(n.current=s,c.setContext({address:`${k.wsAddress}/ws/v1/messenger`,async open(){c.notify("authorize",[n.current]),c.notify("subscribe",Object.keys(i))}}))},[s]),{subscribe:E}}export{S as u};
