user-analytics-tracker 1.7.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -83,6 +83,7 @@ interface IPLocation {
83
83
  as?: string;
84
84
  query?: string;
85
85
  }
86
+ type LogLevel$1 = 'silent' | 'error' | 'warn' | 'info' | 'debug';
86
87
  interface AnalyticsConfig {
87
88
  apiEndpoint: string;
88
89
  autoSend?: boolean;
@@ -93,6 +94,14 @@ interface AnalyticsConfig {
93
94
  enableAttribution?: boolean;
94
95
  sessionStoragePrefix?: string;
95
96
  localStoragePrefix?: string;
97
+ batchSize?: number;
98
+ batchInterval?: number;
99
+ maxQueueSize?: number;
100
+ maxRetries?: number;
101
+ retryDelay?: number;
102
+ sessionTimeout?: number;
103
+ logLevel?: LogLevel$1;
104
+ enableMetrics?: boolean;
96
105
  }
97
106
  interface AnalyticsEvent {
98
107
  sessionId: string;
@@ -198,44 +207,175 @@ declare class AttributionDetector {
198
207
  private static getDefaultAttribution;
199
208
  }
200
209
 
210
+ /**
211
+ * Metrics collection for analytics tracker
212
+ * Tracks performance and usage statistics
213
+ */
214
+ interface AnalyticsMetrics {
215
+ eventsSent: number;
216
+ eventsQueued: number;
217
+ eventsFailed: number;
218
+ eventsFiltered: number;
219
+ averageSendTime: number;
220
+ retryCount: number;
221
+ queueSize: number;
222
+ lastFlushTime: number | null;
223
+ errors: Array<{
224
+ timestamp: number;
225
+ error: string;
226
+ }>;
227
+ }
228
+
229
+ /**
230
+ * Queue Manager for Analytics Events
231
+ * Handles batching, persistence, and offline support
232
+ */
233
+
234
+ interface QueuedEvent {
235
+ event: AnalyticsEvent;
236
+ retries: number;
237
+ timestamp: number;
238
+ id: string;
239
+ }
240
+ interface QueueConfig {
241
+ batchSize: number;
242
+ batchInterval: number;
243
+ maxQueueSize: number;
244
+ storageKey: string;
245
+ }
246
+ declare class QueueManager {
247
+ private queue;
248
+ private flushTimer;
249
+ private isFlushing;
250
+ private config;
251
+ private flushCallback;
252
+ constructor(config: QueueConfig);
253
+ /**
254
+ * Set the callback function to flush events
255
+ */
256
+ setFlushCallback(callback: (events: AnalyticsEvent[]) => Promise<void>): void;
257
+ /**
258
+ * Add an event to the queue
259
+ */
260
+ enqueue(event: AnalyticsEvent): boolean;
261
+ /**
262
+ * Flush events from the queue
263
+ */
264
+ flush(): Promise<void>;
265
+ /**
266
+ * Get current queue size
267
+ */
268
+ getQueueSize(): number;
269
+ /**
270
+ * Get all queued events (for debugging)
271
+ */
272
+ getQueue(): QueuedEvent[];
273
+ /**
274
+ * Clear the queue
275
+ */
276
+ clear(): void;
277
+ /**
278
+ * Load queue from localStorage
279
+ */
280
+ private loadFromStorage;
281
+ /**
282
+ * Save queue to localStorage
283
+ */
284
+ private saveToStorage;
285
+ /**
286
+ * Start auto-flush timer
287
+ */
288
+ private startAutoFlush;
289
+ /**
290
+ * Setup page unload handler to flush events
291
+ */
292
+ private setupPageUnloadHandler;
293
+ /**
294
+ * Get endpoint for sendBeacon
295
+ */
296
+ private getEndpointFromCallback;
297
+ /**
298
+ * Update storage key (for configuration changes)
299
+ */
300
+ updateConfig(config: Partial<QueueConfig>): void;
301
+ /**
302
+ * Cleanup resources
303
+ */
304
+ destroy(): void;
305
+ }
306
+
201
307
  /**
202
308
  * Analytics Service
203
309
  * Sends analytics events to your backend API
204
310
  *
205
311
  * Supports both relative paths (e.g., '/api/analytics') and full URLs (e.g., 'https://your-server.com/api/analytics')
312
+ *
313
+ * Features:
314
+ * - Event batching and queueing
315
+ * - Automatic retry with exponential backoff
316
+ * - Offline support with localStorage persistence
317
+ * - Configurable logging levels
206
318
  */
207
319
  declare class AnalyticsService {
208
320
  private static apiEndpoint;
321
+ private static queueManager;
322
+ private static config;
323
+ private static isInitialized;
209
324
  /**
210
- * Configure the analytics API endpoint
325
+ * Configure the analytics service
211
326
  *
212
327
  * @param config - Configuration object
213
328
  * @param config.apiEndpoint - Your backend API endpoint URL
214
- * - Relative path: '/api/analytics' (sends to same domain)
215
- * - Full URL: 'https://your-server.com/api/analytics' (sends to your server)
329
+ * @param config.batchSize - Events per batch (default: 10)
330
+ * @param config.batchInterval - Flush interval in ms (default: 5000)
331
+ * @param config.maxQueueSize - Max queued events (default: 100)
332
+ * @param config.maxRetries - Max retry attempts (default: 3)
333
+ * @param config.retryDelay - Initial retry delay in ms (default: 1000)
334
+ * @param config.logLevel - Logging verbosity (default: 'warn')
216
335
  *
217
336
  * @example
218
337
  * ```typescript
219
- * // Use your own server
338
+ * // Basic configuration
220
339
  * AnalyticsService.configure({
221
340
  * apiEndpoint: 'https://api.yourcompany.com/analytics'
222
341
  * });
223
342
  *
224
- * // Or use relative path (same domain)
343
+ * // Advanced configuration
225
344
  * AnalyticsService.configure({
226
- * apiEndpoint: '/api/analytics'
345
+ * apiEndpoint: '/api/analytics',
346
+ * batchSize: 20,
347
+ * batchInterval: 10000,
348
+ * maxRetries: 5,
349
+ * logLevel: 'info'
227
350
  * });
228
351
  * ```
229
352
  */
230
- static configure(config: {
353
+ static configure(config: Partial<AnalyticsConfig> & {
231
354
  apiEndpoint: string;
232
355
  }): void;
356
+ /**
357
+ * Initialize the queue manager
358
+ */
359
+ private static initializeQueue;
360
+ /**
361
+ * Get queue manager instance
362
+ */
363
+ static getQueueManager(): QueueManager | null;
233
364
  /**
234
365
  * Generate a random event ID
235
366
  */
236
367
  private static generateEventId;
368
+ /**
369
+ * Send a batch of events with retry logic
370
+ */
371
+ private static sendBatch;
372
+ /**
373
+ * Sleep utility for retry delays
374
+ */
375
+ private static sleep;
237
376
  /**
238
377
  * Track user journey/analytics event
378
+ * Events are automatically queued and batched
239
379
  */
240
380
  static trackEvent(event: Omit<AnalyticsEvent, 'eventId' | 'timestamp'>): Promise<void>;
241
381
  /**
@@ -308,6 +448,23 @@ declare class AnalyticsService {
308
448
  * ```
309
449
  */
310
450
  static trackPageView(pageName?: string, parameters?: Record<string, any>): Promise<void>;
451
+ /**
452
+ * Manually flush the event queue
453
+ * Useful for ensuring events are sent before page unload
454
+ */
455
+ static flushQueue(): Promise<void>;
456
+ /**
457
+ * Get current queue size
458
+ */
459
+ static getQueueSize(): number;
460
+ /**
461
+ * Clear the event queue
462
+ */
463
+ static clearQueue(): void;
464
+ /**
465
+ * Get metrics (if enabled)
466
+ */
467
+ static getMetrics(): AnalyticsMetrics | null;
311
468
  }
312
469
 
313
470
  interface UseAnalyticsOptions {
@@ -349,6 +506,36 @@ declare function getOrCreateUserId(length?: number): string;
349
506
  * Track page visits with localStorage
350
507
  */
351
508
  declare function trackPageVisit(): number;
509
+ /**
510
+ * Session management utilities
511
+ */
512
+ interface SessionInfo {
513
+ sessionId: string;
514
+ startTime: number;
515
+ lastActivity: number;
516
+ pageViews: number;
517
+ }
518
+ /**
519
+ * Get or create a session
520
+ */
521
+ declare function getOrCreateSession(timeout?: number): SessionInfo;
522
+ /**
523
+ * Update session activity
524
+ */
525
+ declare function updateSessionActivity(): void;
526
+ /**
527
+ * Get current session info
528
+ */
529
+ declare function getSession(): SessionInfo | null;
530
+ /**
531
+ * Clear session
532
+ */
533
+ declare function clearSession(): void;
534
+
535
+ /**
536
+ * Initialize debug utilities (only in development)
537
+ */
538
+ declare function initDebug(): void;
352
539
 
353
540
  /**
354
541
  * Location Consent Manager
@@ -411,5 +598,24 @@ declare function getIPLocation(ip: string): Promise<IPLocation | null>;
411
598
  */
412
599
  declare function getIPFromRequest(req: Request | any): string;
413
600
 
414
- export { AnalyticsService, AttributionDetector, DeviceDetector, LocationDetector, NetworkDetector, checkAndSetLocationConsent, clearLocationConsent, useAnalytics as default, getIPFromRequest, getIPLocation, getLocationConsentTimestamp, getOrCreateUserId, getPublicIP, hasLocationConsent, loadJSON, loadSessionJSON, saveJSON, saveSessionJSON, setLocationConsentGranted, trackPageVisit, useAnalytics };
415
- export type { AnalyticsConfig, AnalyticsEvent, AttributionInfo, DeviceInfo, DeviceType, IPLocation, LocationInfo, NetworkInfo, NetworkType, UseAnalyticsOptions, UseAnalyticsReturn };
601
+ /**
602
+ * Logger utility for analytics tracker
603
+ * Provides configurable logging levels for development and production
604
+ */
605
+ type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug';
606
+ declare class Logger {
607
+ private level;
608
+ private isDevelopment;
609
+ constructor();
610
+ setLevel(level: LogLevel): void;
611
+ getLevel(): LogLevel;
612
+ private shouldLog;
613
+ error(message: string, ...args: any[]): void;
614
+ warn(message: string, ...args: any[]): void;
615
+ info(message: string, ...args: any[]): void;
616
+ debug(message: string, ...args: any[]): void;
617
+ }
618
+ declare const logger: Logger;
619
+
620
+ export { AnalyticsService, AttributionDetector, DeviceDetector, LocationDetector, NetworkDetector, QueueManager, checkAndSetLocationConsent, clearLocationConsent, clearSession, useAnalytics as default, getIPFromRequest, getIPLocation, getLocationConsentTimestamp, getOrCreateSession, getOrCreateUserId, getPublicIP, getSession, hasLocationConsent, initDebug, loadJSON, loadSessionJSON, logger, saveJSON, saveSessionJSON, setLocationConsentGranted, trackPageVisit, updateSessionActivity, useAnalytics };
621
+ export type { AnalyticsConfig, AnalyticsEvent, AttributionInfo, DeviceInfo, DeviceType, IPLocation, LocationInfo, LogLevel$1 as LogLevel, NetworkInfo, NetworkType, QueueConfig, QueuedEvent, SessionInfo, UseAnalyticsOptions, UseAnalyticsReturn };