4 lines
1.7 KiB
JavaScript
4 lines
1.7 KiB
JavaScript
function e(){try{return localStorage.getItem(`sync_live_token`)||``}catch{return``}}function t(){let t=e();return t?{Authorization:`Bearer ${t}`}:{}}function n(e){let t=[],n=e;for(;;){let e=n.indexOf(`
|
|
|
|
`);if(e===-1)break;let r=n.slice(0,e);if(n=n.slice(e+2),!r.trim()||r.startsWith(`:`))continue;let i=`message`,a=``;for(let e of r.split(`
|
|
`))e.startsWith(`event:`)?i=e.slice(6).trim():e.startsWith(`data:`)&&(a+=e.slice(5).trim());a&&t.push({event:i,data:a})}return{events:t,rest:n}}async function r(e,r,i,a){i?.(!1);let o=0;for(;!a?.aborted;){try{let s=await fetch(e,{method:`POST`,headers:{Accept:`text/event-stream`,...t()},credentials:`same-origin`,signal:a});if(!s.ok){let e=await s.text().catch(()=>``);throw Error(e||`SSE POST ${s.status}`)}if(!s.body)throw Error(`no body`);i?.(!0),o=0;let c=s.body.getReader(),l=new TextDecoder,u=``;for(;!a?.aborted;){let{value:e,done:t}=await c.read();if(t)break;u+=l.decode(e,{stream:!0});let{events:i,rest:a}=n(u);u=a;for(let e of i)r(e.event,e.data)}i?.(!1)}catch{if(a?.aborted)break;i?.(!1),o+=1;let e=Math.min(15e3,500*2**Math.min(o,5));await new Promise(t=>setTimeout(t,e));continue}if(a?.aborted)break;await new Promise(e=>setTimeout(e,800))}}function i(e,t){let n=new AbortController;return r(`/api/room/${encodeURIComponent(e)}/events`,(e,n)=>{if(e===`room`)try{t(JSON.parse(n))}catch{}},void 0,n.signal),()=>n.abort()}function a(e,t){let n=new AbortController;return r(`/api/rooms/events`,(t,n)=>{if(t===`rooms`)try{e(JSON.parse(n))}catch{}},t,n.signal),()=>n.abort()}function o(e,t,n){let i=new AbortController;return r(`/api/room/${encodeURIComponent(e)}/chat/subscribe`,(e,n)=>{if(e===`chat`)try{t(JSON.parse(n))}catch{}},n,i.signal),()=>i.abort()}export{i as n,a as r,o as t}; |