itty-sockets
Version:
Tiny realtime messaging client in under 450 bytes. No backend needed.
2 lines (1 loc) • 760 B
JavaScript
;exports.connect=(e,s={})=>{let t,o=0,n=[],r={},a=()=>(t||(t=new WebSocket(/^wss?:/.test(e)?e:"wss://ittysockets.io/c/"+e+"?"+new URLSearchParams(s)),t.onclose=()=>{o=0,t=null;for(let e of r.close??[])e()},t.onopen=()=>{for(;n.length;)t?.send(n.shift());for(let e of r.open??[])e();o&&t?.close()},t.onmessage=(e,s=JSON.parse(e.data))=>{for(let e of r[s.type??"message"]??[])e({...s,date:new Date(s.date)})}),c);const c=new Proxy(a,{get:(e,s)=>({close:()=>(1==t?.readyState?t.close():o=1,c),open:a,send:(e,s)=>(e=JSON.stringify(e),e=s?"@@"+s+"@@"+e:e,1==t?.readyState?(t.send(e),c):(n.push(e),a())),push:(e,s)=>(o=1,c.send(e,s)),on:(e,s)=>((r[e]??=[]).push(s),a()),remove:(e,s,t=r[e],o=t?.indexOf(s)??-1)=>(~o&&t?.splice(o,1),a())}[s])});return c};