// @bun
var{defineProperty:O,getOwnPropertyNames:h,getOwnPropertyDescriptor:C}=Object,w=Object.prototype.hasOwnProperty;function m(B){return this[B]}var b=(B)=>{var F=(W??=new WeakMap).get(B),K;if(F)return F;if(F=O({},"__esModule",{value:!0}),B&&typeof B==="object"||typeof B==="function"){for(var G of h(B))if(!w.call(F,G))O(F,G,{get:m.bind(B,G),enumerable:!(K=C(B,G))||K.enumerable})}return W.set(B,F),F},W;var g=(B)=>B;function y(B,F){this[B]=g.bind(null,F)}var d=(B,F)=>{for(var K in F)O(B,K,{get:F[K],enumerable:!0,configurable:!0,set:y.bind(F,K)})};var u=(B,F)=>()=>(B&&(F=B(B=0)),F);var f=import.meta.require;function p(){return typeof window<"u"&&"WebSocket"in window}function v(B,F={}){let{protocols:K,autoReconnect:G=!1,heartbeat:U=!1,immediate:S=!0,onOpen:x,onMessage:D,onClose:H,onError:I}=F,Z=new Set,Q=new Map,A={status:"closed",data:null,error:null,ws:null},V=0,X=null,N=null,_=!1;function P(){Z.forEach((j)=>j(A))}function Y(j,z){let J=Q.get(j);if(J)J.forEach((M)=>M(z))}function $(){if(X)clearInterval(X),X=null;if(N)clearTimeout(N),N=null}function k(j){if(!U)return;let z=typeof U==="object"?U:{message:"ping",interval:30000,pongTimeout:1e4};$(),X=setInterval(()=>{if(j.readyState===WebSocket.OPEN)j.send(z.message||"ping"),N=setTimeout(()=>{j.close()},z.pongTimeout||1e4)},z.interval||30000)}function E(){if(typeof G==="object")return{retries:G.retries??3,delay:G.delay??1000,maxDelay:G.maxDelay??1e4,onFailed:G.onFailed};return{retries:3,delay:1000,maxDelay:1e4,onFailed:void 0}}function q(){if(!p())return;_=!1,A={...A,status:"connecting"},P();try{let j=new WebSocket(B,K);A={...A,ws:j},j.onopen=(z)=>{A={...A,status:"open"},V=0,P(),k(j),Y("open",z),x?.(z)},j.onmessage=(z)=>{if(U&&N)clearTimeout(N),N=null;let J;try{J=JSON.parse(z.data)}catch{J=z.data}A={...A,data:J},P(),Y("message",z),D?.(z)},j.onclose=(z)=>{if($(),A={...A,status:"closed",ws:null},P(),Y("close",z),H?.(z),G&&!_){let J=E();if(V<J.retries){let M=Math.min(J.delay*2**V,J.maxDelay);V++,setTimeout(q,M)}else J.onFailed?.()}},j.onerror=(z)=>{A={...A,error:z},P(),Y("error",z),I?.(z)}}catch(j){A={...A,status:"closed",error:j},P()}}function L(j){if(A.ws&&A.status==="open"){let z=typeof j==="object"&&!(j instanceof ArrayBuffer)&&!(j instanceof Blob)?JSON.stringify(j):j;return A.ws.send(z),!0}return!1}function R(j,z){if(_=!0,$(),A.ws)A={...A,status:"closing"},P(),A.ws.close(j,z)}function T(j,z){if(!Q.has(j))Q.set(j,new Set);return Q.get(j).add(z),()=>{Q.get(j)?.delete(z)}}if(S)q();return{get:()=>A,subscribe:(j)=>{return Z.add(j),j(A),()=>{Z.delete(j)}},send:L,open:q,close:R,ws:()=>A.ws,on:T}}export{v as useWebSocket,p as isWebSocketSupported};
