// The live client must behave exactly like the waiter's original useWebSocket hook. import assert from 'node:assert/strict' import { test } from 'node:test' import { createLiveClient, wsUrlFor } from '../src/live.js' class FakeWS { static all = [] constructor(url) { this.url = url; this.sent = []; this.readyState = 0; this.closed = false; FakeWS.all.push(this) } send(s) { this.sent.push(JSON.parse(s)) } close() { this.closed = true; this.readyState = 3 } // server side helpers open() { this.readyState = 1; this.onopen?.() } msg(obj) { this.onmessage?.({ data: typeof obj === 'string' ? obj : JSON.stringify(obj) }) } drop() { this.readyState = 3; this.onerror?.(); this.onclose?.() } } function fakeTimers() { const pending = [] return { pending, setTimeout(fn, ms) { const t = { fn, ms }; pending.push(t); return t }, clearTimeout(t) { const i = pending.indexOf(t); if (i >= 0) pending.splice(i, 1) }, fire() { const t = pending.shift(); t.fn(); return t.ms }, } } class FakeWindow { listeners = {} addEventListener(n, f) { (this.listeners[n] ||= new Set()).add(f) } removeEventListener(n, f) { this.listeners[n]?.delete(f) } emit(n) { for (const f of this.listeners[n] || []) f() } } function setup({ saved = 0 } = {}) { FakeWS.all = [] const events = [] const log = [] const saves = [] const timers = fakeTimers() const win = new FakeWindow() const live = createLiveClient({ url: () => 'ws://venue/api/ws/connect?token=t', cursor: { load: async () => saved, save: s => saves.push(s) }, onEvent: (type, data) => events.push([type, data]), onReady: () => log.push('ready'), onDisconnect: () => log.push('disconnect'), WebSocketImpl: FakeWS, windowTarget: win, timers, }) return { live, events, log, saves, timers, win, last: () => FakeWS.all.at(-1) } } test('sends the saved cursor on open, replays, then goes live', async () => { const s = setup({ saved: 41 }) await s.live.start() const ws = s.last() assert.equal(ws.url, 'ws://venue/api/ws/connect?token=t') ws.open() assert.deepEqual(ws.sent, [{ cursor: 41 }]) ws.msg({ seq: 42, type: 'order_created', data: { id: 1 } }) // replayed ws.msg({ type: 'ready' }) ws.msg({ type: 'ping' }) ws.msg({ seq: 43, type: 'order_updated', data: { id: 1 } }) // live ws.msg('not json') assert.deepEqual(s.events, [['order_created', { id: 1 }], ['order_updated', { id: 1 }]]) assert.deepEqual(s.log, ['ready']) assert.deepEqual(s.saves, [42, 43]) assert.equal(s.live.lastSeq, 43) }) test('the cursor never goes back; events without seq still arrive', async () => { const s = setup({ saved: 10 }) await s.live.start(); s.last().open() s.last().msg({ seq: 5, type: 'x', data: {} }) s.last().msg({ type: 'y', data: null }) s.last().msg({ type: 'z' }) // no data → ignored assert.equal(s.live.lastSeq, 10) assert.deepEqual(s.saves, []) assert.deepEqual(s.events.map(e => e[0]), ['x', 'y']) }) test('reconnect backoff: 2 s, 3 s, 4.5 s … capped at 30 s; a good open resets it', async () => { const s = setup() await s.live.start() const waits = [] for (let i = 0; i < 9; i++) { s.last().drop(); waits.push(s.timers.fire()) } assert.deepEqual(waits, [2000, 3000, 4500, 6750, 10125, 15187.5, 22781.25, 30000, 30000]) assert.equal(FakeWS.all.length, 10) s.last().open() s.last().drop() assert.equal(s.timers.fire(), 2000) assert.equal(s.log.filter(l => l === 'disconnect').length, 10) }) test('reconnects with the last cursor seen', async () => { const s = setup() await s.live.start(); s.last().open() s.last().msg({ seq: 7, type: 'a', data: {} }) s.last().drop(); s.timers.fire() s.last().open() assert.deepEqual(s.last().sent, [{ cursor: 7 }]) }) test('the browser coming online reconnects at once with the backoff reset', async () => { const s = setup() await s.live.start() s.last().drop(); s.timers.fire(); s.last().drop() // delay is now 3 s assert.equal(s.timers.pending.length, 1) s.win.emit('online') assert.equal(s.timers.pending.length, 0, 'the pending retry is cancelled') assert.equal(FakeWS.all.length, 3) s.last().drop() assert.equal(s.timers.fire(), 2000) }) test('reconnect() replaces the socket without a double reconnect', async () => { const s = setup() await s.live.start(); s.last().open() const first = s.last() s.live.reconnect() assert.ok(first.closed) assert.equal(first.onclose, null) assert.equal(FakeWS.all.length, 2) assert.equal(s.timers.pending.length, 0) }) test('stop() closes for good and stops listening', async () => { const s = setup() await s.live.start(); s.last().open() const ws = s.last() s.live.stop() assert.ok(ws.closed) assert.equal(s.timers.pending.length, 0) s.win.emit('online') assert.equal(FakeWS.all.length, 1) assert.equal(s.win.listeners.online.size, 0) }) test('stop() during the cursor load: never connects', async () => { const s = setup() const p = s.live.start() s.live.stop() await p assert.equal(FakeWS.all.length, 0) }) test('a failing cursor store starts from 0', async () => { FakeWS.all = [] const live = createLiveClient({ url: 'ws://x', cursor: { load: async () => { throw new Error('idb') } }, WebSocketImpl: FakeWS, windowTarget: null, timers: fakeTimers(), }) await live.start(); FakeWS.all[0].open() assert.deepEqual(FakeWS.all[0].sent, [{ cursor: 0 }]) }) test('wsUrlFor', () => { assert.equal(wsUrlFor('/api/ws/connect?token=a', 'https://10.0.2.2:18443'), 'wss://10.0.2.2:18443/api/ws/connect?token=a') assert.equal(wsUrlFor('/api/ws/connect', 'http://192.168.1.5'), 'ws://192.168.1.5/api/ws/connect') }) test('credentials go in the first frame (empty ones left out); refusals reach onRefused', async () => { FakeWS.all = [] const refused = [] const events = [] const live = createLiveClient({ url: 'ws://venue/api/ws/connect', credentials: () => ({ device: 'dev-token', token: null }), onEvent: (type, data) => events.push([type, data]), onRefused: code => refused.push(code), WebSocketImpl: FakeWS, windowTarget: new FakeWindow(), timers: fakeTimers(), }) await live.start() const ws = FakeWS.all.at(-1) assert.equal(ws.url, 'ws://venue/api/ws/connect') ws.open() assert.deepEqual(ws.sent, [{ cursor: 0, device: 'dev-token' }]) ws.msg({ type: 'refused', data: { code: 'device.revoked' } }) ws.msg({ type: 'device.updated', data: { device_id: 3 } }) assert.deepEqual(refused, ['device.revoked']) assert.deepEqual(events, [['device.updated', { device_id: 3 }]]) live.stop() })