import { WebSocketServer } from 'ws';
export class WsGateway {
    wss;
    clients = new Set();
    constructor(server) {
        this.wss = new WebSocketServer({ noServer: true });
        server.on('upgrade', (req, socket, head) => {
            if (req.url !== '/ws')
                return;
            this.wss.handleUpgrade(req, socket, head, (ws) => {
                this.clients.add(ws);
                ws.on('close', () => this.clients.delete(ws));
                this.send(ws, { kind: 'hello', ts: Date.now() });
            });
        });
    }
    broadcast(event) {
        const payload = JSON.stringify(event);
        for (const ws of this.clients) {
            if (ws.readyState === ws.OPEN)
                ws.send(payload);
        }
    }
    send(ws, event) {
        if (ws.readyState === ws.OPEN)
            ws.send(JSON.stringify(event));
    }
    async close() {
        for (const ws of this.clients)
            ws.close();
        this.clients.clear();
        await new Promise((resolve) => this.wss.close(() => resolve()));
    }
}
//# sourceMappingURL=gateway.js.map