/** * The X-Haven WebSocket client (PLAN.md section 3.5). * * Responsibilities: * - the `hello` handshake (the session id rides in the cookie, set by the * `/session` endpoint / the upgrade request) * - a keepalive `ping` so the server's dead-connection sweep never closes a * live tab * - automatic reconnect with exponential backoff; every (re)connect re-sends * `hello`, which the server answers with a full `welcome` — that is the * resync * - typed dispatch of `welcome` / `update` / `seats` / `error` / `pong` * - outbound command / claim / undo / redo helpers * * The [WebSocket]-compatible transport is injectable so the reconnect and * resync behaviour can be exercised in unit tests with a fake socket. */ import type { ErrorMessage, ServerMessage } from './types'; import { claimMessage, helloMessage, pingMessage } from './types'; export type ConnectionStatus = | 'connecting' | 'open' | 'reconnecting' | 'closed'; /** A `WebSocket`-compatible surface (enough for the tests' fake). */ export interface Transport { onopen: ((ev?: unknown) => void) | null; onclose: ((ev?: unknown) => void) | null; onerror: ((ev?: unknown) => void) | null; onmessage: ((ev: { data: unknown }) => void) | null; send(data: string): void; close(): void; readyState: number; // 0 OPEN } export interface ConnectionOptions { /** Absolute `ws://` / `wss://` URL. Defaults to the page origin `/ws`. */ url?: string; /** Inject a transport factory (tests). Defaults to `new WebSocket(url)`. */ transport?: (url: string) => Transport; /** Reconnect base delay in ms (doubles each attempt, capped). */ reconnectBaseMs?: number; reconnectMaxMs?: number; /** Keepalive ping interval in ms. */ pingIntervalMs?: number; } const OPEN = 0; export class GameConnection { status: ConnectionStatus = 'connecting'; /** The session id from the last `welcome` (null before the handshake). */ session: string | null = null; onStatus: ((status: ConnectionStatus) => void) | null = null; /** Every server message, in order (including `pong`). */ onMessage: ((message: ServerMessage) => void) | null = null; /** Convenience hook for `error` messages only. */ onError: ((error: ErrorMessage) => void) | null = null; private ws: Transport | null = null; private readonly options: Required< Pick< ConnectionOptions, 'reconnectBaseMs' | 'reconnectMaxMs' | 'pingIntervalMs' > > & ConnectionOptions; private readonly url: string; private intentionalClose = false; private reconnectDelay = 0; private reconnectTimer: ReturnType | null = null; private pingTimer: ReturnType | null = null; private disposed = false; constructor(options: ConnectionOptions = {}) { this.options = { reconnectBaseMs: 500, reconnectMaxMs: 15_000, pingIntervalMs: 25_000, ...options }; const explicit = options.url; if (explicit) { this.url = explicit; } else { const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'; this.url = `${proto}://${window.location.host}/ws`; } } private makeTransport(): Transport { if (this.options.transport) return this.options.transport(this.url); return new WebSocket(this.url) as unknown as Transport; } connect(): void { this.intentionalClose = false; this.openSocket(); } /** Stop connecting and never reconnect (page teardown). */ disconnect(): void { this.disposed = true; this.intentionalClose = true; this.clearTimers(); this.ws?.close(); this.ws = null; } private setStatus(status: ConnectionStatus) { this.status = status; this.onStatus?.(status); } private openSocket() { if (this.disposed) return; this.setStatus(this.ws === null && this.session === null ? 'connecting' : 'reconnecting'); const ws = this.makeTransport(); this.ws = ws; ws.onopen = () => { this.setStatus('open'); this.sendRaw(helloMessage()); this.startPing(); }; ws.onmessage = (ev) => { const text = typeof ev.data === 'string' ? ev.data : ''; let message: ServerMessage; try { message = JSON.parse(text) as ServerMessage; } catch { return; // ignore non-JSON frames } if (message.t === 'welcome') { this.session = message.session; // A real resync landed: the connection is healthy, so the // backoff starts fresh from the base on the next drop. this.reconnectDelay = 0; } this.onMessage?.(message); if (message.t === 'error') this.onError?.(message); }; ws.onclose = () => { this.stopPing(); if (this.disposed || this.intentionalClose) { this.setStatus('closed'); return; } this.scheduleReconnect(); }; // onerror is always followed by onclose in the browser; nothing to do. ws.onerror = () => {}; } private scheduleReconnect() { this.setStatus('reconnecting'); const delay = this.reconnectDelay || this.options.reconnectBaseMs; this.reconnectDelay = Math.min( delay * 2, this.options.reconnectMaxMs ); this.reconnectTimer = setTimeout(() => this.openSocket(), delay); } private clearTimers() { if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } this.stopPing(); } private startPing() { this.stopPing(); this.pingTimer = setInterval(() => { if (this.ws && this.ws.readyState === OPEN) this.sendRaw(pingMessage()); }, this.options.pingIntervalMs); } private stopPing() { if (this.pingTimer) { clearInterval(this.pingTimer); this.pingTimer = null; } } private sendRaw(message: object) { if (this.ws && this.ws.readyState === OPEN) { this.ws.send(JSON.stringify(message)); } } /** Execute a registered command (players only on the server side). */ sendCmd(name: string, args: Record = {}): void { this.sendRaw({ t: 'cmd', name, args }); } /** Claim (or re-assert) a character seat. */ claim(characterId: string): void { this.sendRaw(claimMessage(characterId)); } undo(): void { this.sendRaw({ t: 'undo' }); } redo(): void { this.sendRaw({ t: 'redo' }); } /** Re-request a full resync (the server re-answers with a `welcome`). */ resync(): void { this.sendRaw(helloMessage()); } }