export class GameSocket { constructor (url, onMessage, { onClose } = {}) { this.url = url; this.onMessage = onMessage; this.onClose = onClose; this.socket = null; } connect () { this.socket = new WebSocket(this.url); this.socket.addEventListener("message", (event) => { this.onMessage(JSON.parse(event.data)); }); this.socket.addEventListener("close", (event) => { this.onClose?.(event); }); return new Promise((resolve, reject) => { this.socket.addEventListener("open", resolve, { once: true }); this.socket.addEventListener("error", () => reject(new Error("WebSocket failed")), { once: true }); }); } send (payload) { this.socket.send(JSON.stringify(payload)); } } export function defaultSocketUrl () { const protocol = location.protocol === "https:" ? "wss:" : "ws:"; return `${protocol}//${location.host}/ws`; }