1const sockets = new Map();
2let next = 1;
3
4export function liveConnect(url, message, closed) {
5 const id = next++;
6 const socket = new WebSocket(url);
7 socket.binaryType = 'arraybuffer';
8 socket.onmessage = event => message(event.data);
9 socket.onclose = () => {
10 if (!sockets.has(id)) return;
11 liveClose(id);
12 closed();
13 };
14 sockets.set(id, socket);
15 return id;
16}
17
18export function liveSend(id, bytes) {
19 const socket = sockets.get(id);
20 try {
21 if (!socket || socket.readyState !== WebSocket.OPEN) throw new Error('Relay disconnected');
22 if (socket.bufferedAmount > 1048576) throw new Error('Relay cannot keep up');
23 socket.send(bytes);
24 } catch (error) {
25 socket?.onclose?.();
26 throw error;
27 }
28}
29
30export function liveClose(id) {
31 const socket = sockets.get(id);
32 sockets.delete(id);
33 if (!socket) return;
34 socket.onmessage = socket.onclose = null;
35 socket.close();
36}