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/CHANGELOG.md CHANGED
@@ -1,3 +1,37 @@
1
+ # [2.0.0](https://github.com/switch-org/analytics-tracker/compare/v1.7.0...v2.0.0) (2025-12-01)
2
+
3
+
4
+ ### Features
5
+
6
+ * major improvements - event batching, retry logic, plugins, and more ([f47b0ea](https://github.com/switch-org/analytics-tracker/commit/f47b0ea0f7bde575d4d91a2ae807fb074065c55c))
7
+ * major improvements - event batching, retry logic, plugins, and more ([46d0c1c](https://github.com/switch-org/analytics-tracker/commit/46d0c1c3e8435dec70fb04e99ad0902198c1486c))
8
+
9
+
10
+ ### BREAKING CHANGES
11
+
12
+ * None - all changes are backward compatible
13
+ * None - all changes are backward compatible
14
+
15
+ # [1.8.0](https://github.com/switch-org/analytics-tracker/compare/v1.7.0...v1.8.0) (2025-01-XX)
16
+
17
+ ### Features
18
+
19
+ * **Event Batching & Queue System**: Automatic event batching reduces API calls by 50-90%. Events are queued and sent in configurable batches (default: 10 events per batch, 5 second intervals)
20
+ * **Offline Support**: Events are persisted to localStorage and automatically sent when connection is restored
21
+ * **Retry Logic with Exponential Backoff**: Automatic retry mechanism for failed requests with exponential backoff (1s, 2s, 4s, 8s). Configurable max retries (default: 3)
22
+ * **Enhanced Logging System**: Configurable log levels (`silent`, `error`, `warn`, `info`, `debug`) with automatic dev/prod level selection
23
+ * **Plugin/Middleware System**: Extensible plugin architecture for event transformation, filtering, and enrichment. Supports `beforeSend`, `afterSend`, and `onError` hooks
24
+ * **Session Management Improvements**: Enhanced session tracking with timeout detection (default: 30 min), automatic session renewal, and session utilities
25
+ * **Developer Debugging Tools**: Built-in debug utilities accessible via `window.__analyticsDebug` in development mode. Includes queue inspection, manual flush, and stats
26
+ * **Performance Monitoring & Metrics**: Optional metrics collection tracking events sent/queued/failed, average send time, retry counts, and error history
27
+ * **Enhanced Configuration Options**: New config options for batching (`batchSize`, `batchInterval`, `maxQueueSize`), retry (`maxRetries`, `retryDelay`), session (`sessionTimeout`), logging (`logLevel`), and metrics (`enableMetrics`)
28
+
29
+ ### Improvements
30
+
31
+ * Better error handling with graceful degradation
32
+ * Improved test coverage for new features
33
+ * Enhanced TypeScript types for all new features
34
+
1
35
  # [1.7.0](https://github.com/switch-org/analytics-tracker/compare/v1.6.0...v1.7.0) (2025-11-24)
2
36
 
3
37
 
package/README.md CHANGED
@@ -22,6 +22,13 @@ A comprehensive, lightweight analytics tracking library for React applications.
22
22
  - 📊 **IP Geolocation**: Client-side and server-side IP-based location detection utilities
23
23
  - 🔒 **Privacy-First**: User consent required for location tracking (GPS & IP), consent management utilities
24
24
  - 🎯 **Custom Event Tracking**: Firebase/Google Analytics-style event tracking with automatic context collection
25
+ - ⚡ **Event Batching & Queue System**: Automatic event batching reduces API calls by 50-90%. Events are queued and sent in configurable batches with offline persistence
26
+ - 🔄 **Retry Logic**: Automatic retry with exponential backoff for failed requests. Configurable retry attempts and delays
27
+ - 📝 **Enhanced Logging**: Configurable log levels (silent, error, warn, info, debug) with automatic dev/prod level selection
28
+ - 🔌 **Plugin System**: Extensible plugin architecture for event transformation, filtering, and enrichment
29
+ - 📈 **Session Management**: Enhanced session tracking with timeout detection and automatic renewal
30
+ - 🐛 **Debug Tools**: Built-in debugging utilities for development (queue inspection, manual flush, stats)
31
+ - 📊 **Performance Metrics**: Optional metrics collection for monitoring events, retries, and performance
25
32
  - ⚡ **Lightweight**: Zero runtime dependencies (except React)
26
33
  - 📦 **TypeScript**: Fully typed with comprehensive type definitions
27
34
  - 🎨 **Framework Agnostic Core**: Core detectors work without React
@@ -59,6 +66,36 @@ function App() {
59
66
  }
60
67
  ```
61
68
 
69
+ ### Advanced Configuration Options
70
+
71
+ The package now supports extensive configuration options for batching, retry logic, logging, and more:
72
+
73
+ ```tsx
74
+ const analytics = useAnalytics({
75
+ config: {
76
+ apiEndpoint: 'https://api.yourcompany.com/analytics',
77
+
78
+ // Event batching configuration
79
+ batchSize: 10, // Events per batch (default: 10)
80
+ batchInterval: 5000, // Flush interval in ms (default: 5000)
81
+ maxQueueSize: 100, // Max queued events (default: 100)
82
+
83
+ // Retry configuration
84
+ maxRetries: 3, // Max retry attempts (default: 3)
85
+ retryDelay: 1000, // Initial retry delay in ms (default: 1000)
86
+
87
+ // Session configuration
88
+ sessionTimeout: 1800000, // Session timeout in ms (default: 30 min)
89
+
90
+ // Logging configuration
91
+ logLevel: 'warn', // 'silent' | 'error' | 'warn' | 'info' | 'debug' (default: 'warn')
92
+
93
+ // Metrics configuration
94
+ enableMetrics: false, // Enable metrics collection (default: false)
95
+ },
96
+ });
97
+ ```
98
+
62
99
  ### Configuration Options
63
100
 
64
101
  You can configure your backend URL in three ways:
@@ -272,6 +309,32 @@ interface UseAnalyticsOptions {
272
309
  attribution: AttributionInfo;
273
310
  }) => void; // Callback when data is ready
274
311
  }
312
+
313
+ interface AnalyticsConfig {
314
+ apiEndpoint: string;
315
+ // Batching options
316
+ batchSize?: number; // Events per batch (default: 10)
317
+ batchInterval?: number; // Flush interval in ms (default: 5000)
318
+ maxQueueSize?: number; // Max queued events (default: 100)
319
+ // Retry options
320
+ maxRetries?: number; // Max retry attempts (default: 3)
321
+ retryDelay?: number; // Initial retry delay in ms (default: 1000)
322
+ // Session options
323
+ sessionTimeout?: number; // Session timeout in ms (default: 1800000 = 30 min)
324
+ // Logging options
325
+ logLevel?: LogLevel; // 'silent' | 'error' | 'warn' | 'info' | 'debug' (default: 'warn')
326
+ // Metrics options
327
+ enableMetrics?: boolean; // Enable metrics collection (default: false)
328
+ // Existing options
329
+ autoSend?: boolean;
330
+ enableLocation?: boolean;
331
+ enableIPGeolocation?: boolean;
332
+ enableNetworkDetection?: boolean;
333
+ enableDeviceDetection?: boolean;
334
+ enableAttribution?: boolean;
335
+ sessionStoragePrefix?: string;
336
+ localStoragePrefix?: string;
337
+ }
275
338
  ```
276
339
 
277
340
  #### Returns
@@ -416,6 +479,26 @@ const attribution = AttributionDetector.detect();
416
479
 
417
480
  ### Services
418
481
 
482
+ #### `AnalyticsService.configure()`
483
+
484
+ Configure the analytics service with advanced options.
485
+
486
+ ```typescript
487
+ import { AnalyticsService } from 'user-analytics-tracker';
488
+
489
+ AnalyticsService.configure({
490
+ apiEndpoint: 'https://api.yourcompany.com/analytics',
491
+ batchSize: 20, // Events per batch (default: 10)
492
+ batchInterval: 10000, // Flush interval in ms (default: 5000)
493
+ maxQueueSize: 100, // Max queued events (default: 100)
494
+ maxRetries: 5, // Max retry attempts (default: 3)
495
+ retryDelay: 2000, // Initial retry delay in ms (default: 1000)
496
+ sessionTimeout: 1800000, // Session timeout in ms (default: 30 min)
497
+ logLevel: 'info', // Logging verbosity (default: 'warn')
498
+ enableMetrics: true, // Enable metrics collection (default: false)
499
+ });
500
+ ```
501
+
419
502
  #### `AnalyticsService.trackUserJourney()`
420
503
 
421
504
  Send analytics data to your backend.
@@ -443,8 +526,111 @@ await AnalyticsService.trackUserJourney({
443
526
  });
444
527
  ```
445
528
 
529
+ #### `AnalyticsService.flushQueue()`
530
+
531
+ Manually flush the event queue (useful before page unload).
532
+
533
+ ```typescript
534
+ // Flush all queued events immediately
535
+ await AnalyticsService.flushQueue();
536
+ ```
537
+
538
+ #### `AnalyticsService.getQueueSize()`
539
+
540
+ Get the current number of events in the queue.
541
+
542
+ ```typescript
543
+ const size = AnalyticsService.getQueueSize();
544
+ console.log(`Queue has ${size} events`);
545
+ ```
546
+
547
+ #### `AnalyticsService.getMetrics()`
548
+
549
+ Get performance metrics (if enabled).
550
+
551
+ ```typescript
552
+ const metrics = AnalyticsService.getMetrics();
553
+ if (metrics) {
554
+ console.log(`Sent: ${metrics.eventsSent}, Failed: ${metrics.eventsFailed}`);
555
+ }
556
+ ```
557
+
446
558
  ### Utilities
447
559
 
560
+ #### Logger
561
+
562
+ Configure logging levels for better debugging and production use.
563
+
564
+ ```typescript
565
+ import { logger } from 'user-analytics-tracker';
566
+
567
+ // Set log level
568
+ logger.setLevel('debug'); // 'silent' | 'error' | 'warn' | 'info' | 'debug'
569
+
570
+ // Use logger
571
+ logger.debug('Debug message');
572
+ logger.info('Info message');
573
+ logger.warn('Warning message');
574
+ logger.error('Error message');
575
+ ```
576
+
577
+ #### Plugin Manager
578
+
579
+ Register and manage plugins for event transformation.
580
+
581
+ ```typescript
582
+ import { pluginManager } from 'user-analytics-tracker';
583
+
584
+ // Register a plugin
585
+ pluginManager.register({
586
+ name: 'my-plugin',
587
+ beforeSend: (event) => {
588
+ // Transform event
589
+ return event;
590
+ },
591
+ });
592
+
593
+ // Unregister a plugin
594
+ pluginManager.unregister('my-plugin');
595
+
596
+ // Get all plugins
597
+ const plugins = pluginManager.getPlugins();
598
+ ```
599
+
600
+ #### Queue Manager
601
+
602
+ Advanced queue management (for power users).
603
+
604
+ ```typescript
605
+ import { QueueManager } from 'user-analytics-tracker';
606
+
607
+ const queue = new QueueManager({
608
+ batchSize: 20,
609
+ batchInterval: 10000,
610
+ maxQueueSize: 200,
611
+ storageKey: 'my-queue',
612
+ });
613
+
614
+ queue.setFlushCallback(async (events) => {
615
+ // Custom flush logic
616
+ });
617
+ ```
618
+
619
+ #### Metrics Collector
620
+
621
+ Collect and monitor analytics performance metrics.
622
+
623
+ ```typescript
624
+ import { metricsCollector } from 'user-analytics-tracker';
625
+
626
+ // Metrics are automatically collected when enableMetrics is true
627
+ // Access metrics
628
+ const metrics = metricsCollector.getMetrics();
629
+
630
+ // Reset metrics
631
+ metricsCollector.reset();
632
+ ```
633
+
448
634
  #### Location Consent Management
449
635
 
450
636
  ```typescript
@@ -468,6 +654,45 @@ setLocationConsentGranted();
468
654
  clearLocationConsent();
469
655
  ```
470
656
 
657
+ #### Session Management
658
+
659
+ Enhanced session tracking utilities.
660
+
661
+ ```typescript
662
+ import {
663
+ getOrCreateSession,
664
+ updateSessionActivity,
665
+ getSession,
666
+ clearSession,
667
+ } from 'user-analytics-tracker';
668
+
669
+ // Get or create session with custom timeout (30 minutes)
670
+ const session = getOrCreateSession(30 * 60 * 1000);
671
+ // Returns: { sessionId, startTime, lastActivity, pageViews }
672
+
673
+ // Update session activity
674
+ updateSessionActivity();
675
+
676
+ // Get current session
677
+ const currentSession = getSession();
678
+
679
+ // Clear session
680
+ clearSession();
681
+ ```
682
+
683
+ #### Debug Utilities
684
+
685
+ Development debugging tools.
686
+
687
+ ```typescript
688
+ import { initDebug } from 'user-analytics-tracker';
689
+
690
+ // Initialize debug tools (automatically called in development)
691
+ initDebug();
692
+
693
+ // Then access via window.__analyticsDebug in browser console
694
+ ```
695
+
471
696
  #### IP Geolocation Utilities
472
697
 
473
698
  **Client-Side: Get Public IP**