user-analytics-tracker 1.7.0 → 2.1.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
@@ -68,21 +68,53 @@ interface AttributionInfo {
68
68
  firstTouch?: Record<string, string | null> | null;
69
69
  lastTouch?: Record<string, string | null> | null;
70
70
  }
71
- interface IPLocation {
71
+ interface IPLocation extends Record<string, any> {
72
72
  ip: string;
73
+ success?: boolean;
74
+ type?: string;
75
+ continent?: string;
76
+ continent_code?: string;
73
77
  country?: string;
74
- countryCode?: string;
78
+ country_code?: string;
75
79
  region?: string;
76
- regionName?: string;
80
+ region_code?: string;
77
81
  city?: string;
82
+ latitude?: number;
83
+ longitude?: number;
84
+ is_eu?: boolean;
85
+ postal?: string;
86
+ calling_code?: string;
87
+ capital?: string;
88
+ borders?: string;
89
+ flag?: {
90
+ img?: string;
91
+ emoji?: string;
92
+ emoji_unicode?: string;
93
+ };
94
+ connection?: {
95
+ asn?: number;
96
+ org?: string;
97
+ isp?: string;
98
+ domain?: string;
99
+ };
100
+ timezone?: {
101
+ id?: string;
102
+ abbr?: string;
103
+ is_dst?: boolean;
104
+ offset?: number;
105
+ utc?: string;
106
+ current_time?: string;
107
+ };
108
+ countryCode?: string;
109
+ regionName?: string;
78
110
  lat?: number;
79
111
  lon?: number;
80
- timezone?: string;
81
112
  isp?: string;
82
113
  org?: string;
83
114
  as?: string;
84
115
  query?: string;
85
116
  }
117
+ type LogLevel$1 = 'silent' | 'error' | 'warn' | 'info' | 'debug';
86
118
  interface AnalyticsConfig {
87
119
  apiEndpoint: string;
88
120
  autoSend?: boolean;
@@ -93,6 +125,14 @@ interface AnalyticsConfig {
93
125
  enableAttribution?: boolean;
94
126
  sessionStoragePrefix?: string;
95
127
  localStoragePrefix?: string;
128
+ batchSize?: number;
129
+ batchInterval?: number;
130
+ maxQueueSize?: number;
131
+ maxRetries?: number;
132
+ retryDelay?: number;
133
+ sessionTimeout?: number;
134
+ logLevel?: LogLevel$1;
135
+ enableMetrics?: boolean;
96
136
  }
97
137
  interface AnalyticsEvent {
98
138
  sessionId: string;
@@ -180,7 +220,8 @@ declare class LocationDetector {
180
220
  /**
181
221
  * Get location from IP-based public API (client-side)
182
222
  * Works without user permission, good fallback when GPS is unavailable
183
- * Uses ip-api.com free tier (no API key required, 45 requests/minute)
223
+ * Uses ipwho.is API (no API key required)
224
+ * Stores all keys dynamically from the API response
184
225
  */
185
226
  private static getIPBasedLocation;
186
227
  /**
@@ -198,44 +239,175 @@ declare class AttributionDetector {
198
239
  private static getDefaultAttribution;
199
240
  }
200
241
 
242
+ /**
243
+ * Metrics collection for analytics tracker
244
+ * Tracks performance and usage statistics
245
+ */
246
+ interface AnalyticsMetrics {
247
+ eventsSent: number;
248
+ eventsQueued: number;
249
+ eventsFailed: number;
250
+ eventsFiltered: number;
251
+ averageSendTime: number;
252
+ retryCount: number;
253
+ queueSize: number;
254
+ lastFlushTime: number | null;
255
+ errors: Array<{
256
+ timestamp: number;
257
+ error: string;
258
+ }>;
259
+ }
260
+
261
+ /**
262
+ * Queue Manager for Analytics Events
263
+ * Handles batching, persistence, and offline support
264
+ */
265
+
266
+ interface QueuedEvent {
267
+ event: AnalyticsEvent;
268
+ retries: number;
269
+ timestamp: number;
270
+ id: string;
271
+ }
272
+ interface QueueConfig {
273
+ batchSize: number;
274
+ batchInterval: number;
275
+ maxQueueSize: number;
276
+ storageKey: string;
277
+ }
278
+ declare class QueueManager {
279
+ private queue;
280
+ private flushTimer;
281
+ private isFlushing;
282
+ private config;
283
+ private flushCallback;
284
+ constructor(config: QueueConfig);
285
+ /**
286
+ * Set the callback function to flush events
287
+ */
288
+ setFlushCallback(callback: (events: AnalyticsEvent[]) => Promise<void>): void;
289
+ /**
290
+ * Add an event to the queue
291
+ */
292
+ enqueue(event: AnalyticsEvent): boolean;
293
+ /**
294
+ * Flush events from the queue
295
+ */
296
+ flush(): Promise<void>;
297
+ /**
298
+ * Get current queue size
299
+ */
300
+ getQueueSize(): number;
301
+ /**
302
+ * Get all queued events (for debugging)
303
+ */
304
+ getQueue(): QueuedEvent[];
305
+ /**
306
+ * Clear the queue
307
+ */
308
+ clear(): void;
309
+ /**
310
+ * Load queue from localStorage
311
+ */
312
+ private loadFromStorage;
313
+ /**
314
+ * Save queue to localStorage
315
+ */
316
+ private saveToStorage;
317
+ /**
318
+ * Start auto-flush timer
319
+ */
320
+ private startAutoFlush;
321
+ /**
322
+ * Setup page unload handler to flush events
323
+ */
324
+ private setupPageUnloadHandler;
325
+ /**
326
+ * Get endpoint for sendBeacon
327
+ */
328
+ private getEndpointFromCallback;
329
+ /**
330
+ * Update storage key (for configuration changes)
331
+ */
332
+ updateConfig(config: Partial<QueueConfig>): void;
333
+ /**
334
+ * Cleanup resources
335
+ */
336
+ destroy(): void;
337
+ }
338
+
201
339
  /**
202
340
  * Analytics Service
203
341
  * Sends analytics events to your backend API
204
342
  *
205
343
  * Supports both relative paths (e.g., '/api/analytics') and full URLs (e.g., 'https://your-server.com/api/analytics')
344
+ *
345
+ * Features:
346
+ * - Event batching and queueing
347
+ * - Automatic retry with exponential backoff
348
+ * - Offline support with localStorage persistence
349
+ * - Configurable logging levels
206
350
  */
207
351
  declare class AnalyticsService {
208
352
  private static apiEndpoint;
353
+ private static queueManager;
354
+ private static config;
355
+ private static isInitialized;
209
356
  /**
210
- * Configure the analytics API endpoint
357
+ * Configure the analytics service
211
358
  *
212
359
  * @param config - Configuration object
213
360
  * @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)
361
+ * @param config.batchSize - Events per batch (default: 10)
362
+ * @param config.batchInterval - Flush interval in ms (default: 5000)
363
+ * @param config.maxQueueSize - Max queued events (default: 100)
364
+ * @param config.maxRetries - Max retry attempts (default: 3)
365
+ * @param config.retryDelay - Initial retry delay in ms (default: 1000)
366
+ * @param config.logLevel - Logging verbosity (default: 'warn')
216
367
  *
217
368
  * @example
218
369
  * ```typescript
219
- * // Use your own server
370
+ * // Basic configuration
220
371
  * AnalyticsService.configure({
221
372
  * apiEndpoint: 'https://api.yourcompany.com/analytics'
222
373
  * });
223
374
  *
224
- * // Or use relative path (same domain)
375
+ * // Advanced configuration
225
376
  * AnalyticsService.configure({
226
- * apiEndpoint: '/api/analytics'
377
+ * apiEndpoint: '/api/analytics',
378
+ * batchSize: 20,
379
+ * batchInterval: 10000,
380
+ * maxRetries: 5,
381
+ * logLevel: 'info'
227
382
  * });
228
383
  * ```
229
384
  */
230
- static configure(config: {
385
+ static configure(config: Partial<AnalyticsConfig> & {
231
386
  apiEndpoint: string;
232
387
  }): void;
388
+ /**
389
+ * Initialize the queue manager
390
+ */
391
+ private static initializeQueue;
392
+ /**
393
+ * Get queue manager instance
394
+ */
395
+ static getQueueManager(): QueueManager | null;
233
396
  /**
234
397
  * Generate a random event ID
235
398
  */
236
399
  private static generateEventId;
400
+ /**
401
+ * Send a batch of events with retry logic
402
+ */
403
+ private static sendBatch;
404
+ /**
405
+ * Sleep utility for retry delays
406
+ */
407
+ private static sleep;
237
408
  /**
238
409
  * Track user journey/analytics event
410
+ * Events are automatically queued and batched
239
411
  */
240
412
  static trackEvent(event: Omit<AnalyticsEvent, 'eventId' | 'timestamp'>): Promise<void>;
241
413
  /**
@@ -308,6 +480,23 @@ declare class AnalyticsService {
308
480
  * ```
309
481
  */
310
482
  static trackPageView(pageName?: string, parameters?: Record<string, any>): Promise<void>;
483
+ /**
484
+ * Manually flush the event queue
485
+ * Useful for ensuring events are sent before page unload
486
+ */
487
+ static flushQueue(): Promise<void>;
488
+ /**
489
+ * Get current queue size
490
+ */
491
+ static getQueueSize(): number;
492
+ /**
493
+ * Clear the event queue
494
+ */
495
+ static clearQueue(): void;
496
+ /**
497
+ * Get metrics (if enabled)
498
+ */
499
+ static getMetrics(): AnalyticsMetrics | null;
311
500
  }
312
501
 
313
502
  interface UseAnalyticsOptions {
@@ -349,6 +538,36 @@ declare function getOrCreateUserId(length?: number): string;
349
538
  * Track page visits with localStorage
350
539
  */
351
540
  declare function trackPageVisit(): number;
541
+ /**
542
+ * Session management utilities
543
+ */
544
+ interface SessionInfo {
545
+ sessionId: string;
546
+ startTime: number;
547
+ lastActivity: number;
548
+ pageViews: number;
549
+ }
550
+ /**
551
+ * Get or create a session
552
+ */
553
+ declare function getOrCreateSession(timeout?: number): SessionInfo;
554
+ /**
555
+ * Update session activity
556
+ */
557
+ declare function updateSessionActivity(): void;
558
+ /**
559
+ * Get current session info
560
+ */
561
+ declare function getSession(): SessionInfo | null;
562
+ /**
563
+ * Clear session
564
+ */
565
+ declare function clearSession(): void;
566
+
567
+ /**
568
+ * Initialize debug utilities (only in development)
569
+ */
570
+ declare function initDebug(): void;
352
571
 
353
572
  /**
354
573
  * Location Consent Manager
@@ -380,11 +599,14 @@ declare function checkAndSetLocationConsent(msisdn?: string | null): boolean;
380
599
  /**
381
600
  * IP Geolocation Service
382
601
  * Fetches location data (country, region, city) from user's IP address
383
- * Uses free tier of ip-api.com (no API key required, 45 requests/minute)
602
+ * Uses ipwho.is API (no API key required)
603
+ *
604
+ * Stores all keys dynamically from the API response, including nested objects
605
+ * This ensures we capture all available data and any new fields added by the API
384
606
  */
385
607
  /**
386
- * Get public IP address using ip-api.com
387
- * Free tier: 45 requests/minute, no API key required
608
+ * Get public IP address using ipwho.is API
609
+ * No API key required
388
610
  *
389
611
  * @returns Promise<string | null> - The public IP address, or null if unavailable
390
612
  *
@@ -396,13 +618,11 @@ declare function checkAndSetLocationConsent(msisdn?: string | null): boolean;
396
618
  */
397
619
  declare function getPublicIP(): Promise<string | null>;
398
620
  /**
399
- * Get location from IP address using ip-api.com
400
- * Free tier: 45 requests/minute, no API key required
621
+ * Get location from IP address using ipwho.is API
622
+ * Free tier: No API key required
401
623
  *
402
- * Alternative services:
403
- * - ipapi.co (requires API key for production)
404
- * - ipgeolocation.io (requires API key)
405
- * - ip-api.com (free tier available)
624
+ * Stores all keys dynamically from the API response, including nested objects
625
+ * This ensures we capture all available data and any new fields added by the API
406
626
  */
407
627
  declare function getIPLocation(ip: string): Promise<IPLocation | null>;
408
628
  /**
@@ -411,5 +631,24 @@ declare function getIPLocation(ip: string): Promise<IPLocation | null>;
411
631
  */
412
632
  declare function getIPFromRequest(req: Request | any): string;
413
633
 
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 };
634
+ /**
635
+ * Logger utility for analytics tracker
636
+ * Provides configurable logging levels for development and production
637
+ */
638
+ type LogLevel = 'silent' | 'error' | 'warn' | 'info' | 'debug';
639
+ declare class Logger {
640
+ private level;
641
+ private isDevelopment;
642
+ constructor();
643
+ setLevel(level: LogLevel): void;
644
+ getLevel(): LogLevel;
645
+ private shouldLog;
646
+ error(message: string, ...args: any[]): void;
647
+ warn(message: string, ...args: any[]): void;
648
+ info(message: string, ...args: any[]): void;
649
+ debug(message: string, ...args: any[]): void;
650
+ }
651
+ declare const logger: Logger;
652
+
653
+ 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 };
654
+ export type { AnalyticsConfig, AnalyticsEvent, AttributionInfo, DeviceInfo, DeviceType, IPLocation, LocationInfo, LogLevel$1 as LogLevel, NetworkInfo, NetworkType, QueueConfig, QueuedEvent, SessionInfo, UseAnalyticsOptions, UseAnalyticsReturn };