File size: 5,921 Bytes
cdf3420
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
class AnalyticsTracker {
    constructor(options = {}) {
        this.endpoint = options.endpoint || '/report';
        this.bufferSize = options.bufferSize || 5;
        this.flushInterval = options.flushInterval || 3000;
        this.maxRetries = options.maxRetries || 3;
        this.baseBackoff = options.baseBackoff || 1000;
        this.onSuccess = options.onSuccess || (() => {});

        this.buffer = [];
        this.timer = null;
        this.isSending = false;
        
        // Auto-start timer
        this.startTimer();

        // Initialize auto-tracking
        if (options.trackErrors !== false) this.initErrorTracking();
        if (options.trackPerformance !== false) this.initPerformanceTracking();
    }

    log(type, data = {}) {
        const event = {
            type,
            data,
            timestamp: Date.now(),
            uuid: crypto.randomUUID()
        };
        
        console.log(`[Tracker] Queued event: ${type}`, event);
        this.buffer.push(event);

        if (this.buffer.length >= this.bufferSize) {
            this.flush();
        }
    }

    startTimer() {
        if (this.timer) clearInterval(this.timer);
        this.timer = setInterval(() => {
            if (this.buffer.length > 0) {
                this.flush();
            }
        }, this.flushInterval);
    }

    async flush() {
        if (this.buffer.length === 0 || this.isSending) return;

        const eventsToSend = [...this.buffer];
        this.buffer = []; // Clear buffer immediately to allow new events
        this.isSending = true;

        this._send(eventsToSend, 0);
    }

    async _send(events, retryCount) {
        try {
            console.log(`[Tracker] Sending batch of ${events.length} events... (Attempt ${retryCount + 1})`);
            
            const response = await fetch(this.endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ events })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            console.log('[Tracker] Upload success:', result);
            this.isSending = false;
            
            // Trigger UI callback
            this.onSuccess(events, result);

        } catch (error) {
            console.error('[Tracker] Upload failed:', error);
            
            if (retryCount < this.maxRetries) {
                const backoff = this.baseBackoff * Math.pow(2, retryCount);
                console.log(`[Tracker] Retrying in ${backoff}ms...`);
                setTimeout(() => {
                    this._send(events, retryCount + 1);
                }, backoff);
            } else {
                console.error('[Tracker] Max retries reached. Dropping events.');
                this.isSending = false;
                // Optionally put them back in buffer or separate failed queue
            }
        }
    }

    // --- Specific Trackers ---

    trackExposure(element, data = {}) {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    this.log('exposure', { ...data, target: element.id || element.tagName });
                    observer.unobserve(element); // Only track once per session usually
                }
            });
        });
        observer.observe(element);
    }

    trackInteraction(element, eventType, data = {}) {
        element.addEventListener(eventType, (e) => {
            this.log('interaction', { 
                eventType, 
                target: element.id || element.tagName, 
                ...data 
            });
        });
    }

    initErrorTracking() {
        // JS Errors
        window.addEventListener('error', (event) => {
            this.log('error', {
                message: event.message,
                filename: event.filename,
                lineno: event.lineno,
                colno: event.colno
            });
        });

        // Promise Rejections
        window.addEventListener('unhandledrejection', (event) => {
            this.log('error', {
                type: 'unhandledrejection',
                reason: event.reason ? event.reason.toString() : 'Unknown'
            });
        });
    }

    initPerformanceTracking() {
        window.addEventListener('load', () => {
            // Basic Navigation Timing
            const navEntry = performance.getEntriesByType('navigation')[0];
            if (navEntry) {
                this.log('performance', {
                    loadTime: navEntry.loadEventEnd - navEntry.startTime,
                    domReady: navEntry.domContentLoadedEventEnd - navEntry.startTime,
                    ttfb: navEntry.responseStart - navEntry.startTime
                });
            }
            
            // Web Vitals (Simplified)
            // LCP
            new PerformanceObserver((entryList) => {
                for (const entry of entryList.getEntries()) {
                    this.log('performance', { metric: 'LCP', value: entry.startTime });
                }
            }).observe({type: 'largest-contentful-paint', buffered: true});

            // CLS
            let clsValue = 0;
            new PerformanceObserver((entryList) => {
                for (const entry of entryList.getEntries()) {
                    if (!entry.hadRecentInput) {
                        clsValue += entry.value;
                    }
                }
                // Report CLS periodically or on visibility change, here we just log updates
                this.log('performance', { metric: 'CLS', value: clsValue });
            }).observe({type: 'layout-shift', buffered: true});
        });
    }
}