summaryrefslogtreecommitdiff
path: root/web/src/lib/protocol/connection.ts
blob: 0826a3c3ffde13ebd581ba3458d1606d59b64ae2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
 * Client side of the X-Haven wire protocol (PLAN.md section 3.5).
 *
 * Phase 0 scope: connect to `/ws`, send the `hello` handshake, surface the
 * `welcome` message and connection status. Reconnect/resync, commands, claims
 * and state updates arrive in later phases.
 */

export interface Welcome {
	t: 'welcome';
	v: number;
	session: string;
	role: 'player' | 'spectator';
	index: number;
	description: string | null;
	event: unknown;
	state: Record<string, unknown>;
	seats: Record<string, unknown>;
}

export type ConnectionStatus = 'connecting' | 'open' | 'closed';

/** The handshake message sent right after the WebSocket opens. */
export function buildHello(): Record<string, unknown> {
	return { t: 'hello', v: 1 };
}

export class GameConnection {
	private ws: WebSocket | null = null;

	onWelcome: ((welcome: Welcome) => void) | null = null;
	onStatus: ((status: ConnectionStatus) => void) | null = null;

	connect(): void {
		const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
		const ws = new WebSocket(`${proto}://${window.location.host}/ws`);
		this.ws = ws;

		ws.onopen = () => {
			this.onStatus?.('open');
			ws.send(JSON.stringify(buildHello()));
		};
		ws.onclose = () => this.onStatus?.('closed');
		ws.onerror = () => this.onStatus?.('closed');
		ws.onmessage = (event) => {
			const message = JSON.parse(String(event.data)) as { t: string };
			if (message.t === 'welcome') {
				this.onWelcome?.(message as unknown as Welcome);
			}
		};
	}

	close(): void {
		this.ws?.close();
		this.ws = null;
	}
}