UNPKG

@cruxstack/browser-sdk

Version:

A lightweight, privacy-focused JavaScript SDK for web analytics and event tracking. Built with TypeScript, featuring automatic event capture, event-time environment snapshots, intelligent queuing, and robust error handling.

66 lines (65 loc) 2.34 kB
import { captureEnvSnapshot } from './utils/env'; export class EventTracker { constructor(apiClient, eventQueue, sessionManager, clientId, customerId, customerName) { this.apiClient = apiClient; this.eventQueue = eventQueue; this.sessionManager = sessionManager; this.clientId = clientId; this.customerId = customerId; this.customerName = customerName; } async track(eventData) { // Create complete event with session data const event = { ...eventData, clientId: this.clientId, customerId: this.customerId || "cust-012345", customerName: this.customerName || "Default Customer", sessionId: this.sessionManager.getSessionId(), userId: this.sessionManager.getUserId(), timestamp: Date.now(), env: captureEnvSnapshot(this.sessionManager.getUserId(), this.apiClient.getCachedIp?.() ?? null) }; try { // First attempt to send immediately const success = await this.apiClient.sendEvent(event); if (!success) { // 400 errors are handled and logged in sendEvent return; } } catch (error) { // On any error, persist once; flushing handles batches this.eventQueue.add(event); } } // Method to manually flush the queue async flushQueue() { while (true) { const batch = this.eventQueue.getBatch(); if (batch.length === 0) return; try { const success = await this.apiClient.sendEventsBatch(batch); if (!success) { // Put the batch back once and stop to avoid tight loop this.eventQueue.addMany(batch); return; } } catch (error) { // Put the batch back once and stop; user/app can retry later this.eventQueue.addMany(batch); return; } } } // Debug method to check queue status getQueueStatus() { return this.eventQueue.getQueueStatus(); } // Debug method to clear queue clearQueue() { this.eventQueue.clearQueue(); } }