/ opencodehub / src / lib / realtime-client.ts
Swadhin Biswas fix(ts): eliminate all 127 TypeScript errors · 4/21/2026
18087d6
74 lines · 2.2 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { logger } from "@/lib/logger";

export class RealtimeClient {
    private eventSource: EventSource | null = null;
    private listeners: Map<string, Function[]> = new Map();
    private reconnectAttempts = 0;
    private maxReconnectAttempts = 5;

    constructor(private url: string = "/api/realtime/events") { }

    connect() {
        if (this.eventSource) return;

        this.eventSource = new EventSource(this.url);

        this.eventSource.onopen = () => {
            logger.info("Realtime connection established");
            this.reconnectAttempts = 0;
            this.emit("connected", {});
        };

        this.eventSource.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                this.emit(data.type, data.data);
                this.emit("message", data);
            } catch (e) {
                logger.error("Failed to parse realtime message", e);
            }
        };

        this.eventSource.onerror = (err) => {
            logger.error("Realtime connection error", err);
            this.eventSource?.close();
            this.eventSource = null;
            this.reconnect();
        };
    }

    private reconnect() {
        if (this.reconnectAttempts >= this.maxReconnectAttempts) {
            logger.error("Max reconnect attempts reached");
            return;
        }

        this.reconnectAttempts++;
        const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
        setTimeout(() => this.connect(), delay);
    }

    on(event: string, callback: Function) {
        if (!this.listeners.has(event)) {
            this.listeners.set(event, []);
        }
        this.listeners.get(event)!.push(callback);
        return () => this.off(event, callback);
    }

    off(event: string, callback: Function) {
        if (!this.listeners.has(event)) return;
        this.listeners.set(
            event,
            this.listeners.get(event)!.filter((cb) => cb !== callback)
        );
    }

    private emit(event: string, data: any) {
        const callbacks = this.listeners.get(event) || [];
        callbacks.forEach((cb) => cb(data));
    }
}

export const realtime = new RealtimeClient();