/** WebSocket client wrapper. */
export class WsClient {
#ws = null;
#sessionId = null;
#handlers = {};
connect(sessionId, handlers) {
this.disconnect();
this.#sessionId = sessionId;
this.#handlers = handlers;
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
this.#ws = new WebSocket(`${proto}://${location.host}/ws/sessions/${sessionId}`);
this.#ws.onopen = () => handlers.onOpen?.();
this.#ws.onclose = (e) => handlers.onClose?.(e);
this.#ws.onerror = (e) => handlers.onError?.(e);
this.#ws.onmessage = (e) => handlers.onMessage?.(JSON.parse(e.data));
}
send(content) {
if (this.#ws?.readyState === WebSocket.OPEN) {
this.#ws.send(JSON.stringify({ type: 'message', content }));
return true;
}
return false;
}
disconnect() {
this.#ws?.close();
this.#ws = null;
this.#sessionId = null;
}
get ready() {
return this.#ws?.readyState === WebSocket.OPEN;
}
}