(url: string, protocols?: string[])
| 81 | } |
| 82 | |
| 83 | function openConn(url: string, protocols?: string[]): Promise<Conn> { |
| 84 | return new Promise((resolve, reject) => { |
| 85 | const ws = new WebSocket(url, protocols); |
| 86 | const queue: WsFrame[] = []; |
| 87 | const waiters: Array<(frame: WsFrame) => void> = []; |
| 88 | let closedResolve: (v: { code: number; reason: string }) => void; |
| 89 | const closed = new Promise<{ code: number; reason: string }>((res) => { |
| 90 | closedResolve = res; |
| 91 | }); |
| 92 | // Attach the message listener BEFORE 'open' can fire so the immediate |
| 93 | // `server_hello` frame is never dropped. |
| 94 | ws.on('message', (data: RawData) => { |
| 95 | try { |
| 96 | const frame = JSON.parse(rawDataToString(data)) as WsFrame; |
| 97 | if (waiters.length > 0) waiters.shift()?.(frame); |
| 98 | else queue.push(frame); |
| 99 | } catch { |
| 100 | // ignore non-JSON frames |
| 101 | } |
| 102 | }); |
| 103 | ws.on('close', (code, reason) => closedResolve({ code, reason: String(reason) })); |
| 104 | ws.once('open', () => resolve({ ws, queue, waiters, closed })); |
| 105 | ws.once('error', reject); |
| 106 | }); |
| 107 | } |
| 108 | |
| 109 | function receive(conn: Conn, timeoutMs: number): Promise<WsFrame> { |
| 110 | return new Promise((resolve, reject) => { |
no test coverage detected