user-analytics-tracker 1.2.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,72 @@
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
+
35
+ # [1.7.0](https://github.com/switch-org/analytics-tracker/compare/v1.6.0...v1.7.0) (2025-11-24)
36
+
37
+
38
+ ### Features
39
+
40
+ * updated build ([4778be5](https://github.com/switch-org/analytics-tracker/commit/4778be5c9f41a034593c02a97c70076c480dd1ed))
41
+
42
+ # [1.6.0](https://github.com/switch-org/analytics-tracker/compare/v1.5.0...v1.6.0) (2025-11-24)
43
+
44
+
45
+ ### Features
46
+
47
+ * update permissions ([553d9be](https://github.com/switch-org/analytics-tracker/commit/553d9be405d7609e2cb9853ff16535cf4b1b9e66))
48
+
49
+ # [1.5.0](https://github.com/switch-org/analytics-tracker/compare/v1.4.0...v1.5.0) (2025-11-24)
50
+
51
+
52
+ ### Features
53
+
54
+ * updated ([a5d770b](https://github.com/switch-org/analytics-tracker/commit/a5d770b97719707c458601f955a98655c1baa27f))
55
+
56
+ # [1.4.0](https://github.com/switch-org/analytics-tracker/compare/v1.3.1...v1.4.0) (2025-11-24)
57
+
58
+
59
+ ### Features
60
+
61
+ * updated doc ([9d606f4](https://github.com/switch-org/analytics-tracker/commit/9d606f4a735dcc7b0aeda30615328b5bda54c4bc))
62
+
63
+ ## [1.3.1](https://github.com/switch-org/analytics-tracker/compare/v1.3.0...v1.3.1) (2025-11-24)
64
+
65
+
66
+ ### Bug Fixes
67
+
68
+ * updated names ([c56f903](https://github.com/switch-org/analytics-tracker/commit/c56f903b9360f2dc2492e5114667dc240cca9e0c))
69
+
1
70
  # [1.3.0](https://github.com/switch-org/analytics-tracker/compare/v1.2.0...v1.3.0) (2025-11-24)
2
71
 
3
72
 
package/README.md CHANGED
@@ -13,13 +13,22 @@ A comprehensive, lightweight analytics tracking library for React applications.
13
13
  - 🔍 **Device Detection**: Automatically detects device type, OS, browser, model, brand, and hardware specs using User-Agent Client Hints
14
14
  - 🌐 **Network Detection**: Identifies WiFi, Cellular, Hotspot, Ethernet connections with quality metrics
15
15
  - 📍 **Location Tracking**:
16
- - **Automatic IP-based location** (no permission required) - works immediately
17
- - GPS location with consent management (MSISDN-based consent)
16
+ - **IP-based location** - Requires user consent (privacy-compliant)
17
+ - **GPS location** - Requires explicit user consent and browser permission
18
18
  - Includes public IP address, country, city, region, timezone
19
19
  - Automatic fallback from GPS to IP when GPS unavailable
20
+ - Consent management utilities included
20
21
  - 🎯 **Attribution Tracking**: UTM parameters, referrer tracking, first/last touch attribution
21
22
  - 📊 **IP Geolocation**: Client-side and server-side IP-based location detection utilities
22
- - 🔒 **Privacy-First**: Location consent management, automatic IP fallback
23
+ - 🔒 **Privacy-First**: User consent required for location tracking (GPS & IP), consent management utilities
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
23
32
  - ⚡ **Lightweight**: Zero runtime dependencies (except React)
24
33
  - 📦 **TypeScript**: Fully typed with comprehensive type definitions
25
34
  - 🎨 **Framework Agnostic Core**: Core detectors work without React
@@ -57,6 +66,36 @@ function App() {
57
66
  }
58
67
  ```
59
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
+
60
99
  ### Configuration Options
61
100
 
62
101
  You can configure your backend URL in three ways:
@@ -169,7 +208,14 @@ function App() {
169
208
  import { useAnalytics } from 'user-analytics-tracker';
170
209
 
171
210
  function MyApp() {
172
- const { sessionId, networkInfo, deviceInfo, location, logEvent } = useAnalytics({
211
+ const {
212
+ sessionId,
213
+ networkInfo,
214
+ deviceInfo,
215
+ location,
216
+ trackEvent,
217
+ trackPageView
218
+ } = useAnalytics({
173
219
  autoSend: true,
174
220
  config: {
175
221
  // Use your own backend server (full URL)
@@ -179,11 +225,24 @@ function MyApp() {
179
225
  },
180
226
  });
181
227
 
228
+ // Track page view on mount
229
+ useEffect(() => {
230
+ trackPageView();
231
+ }, [trackPageView]);
232
+
233
+ const handleButtonClick = async () => {
234
+ // Track custom event (Firebase/GA-style)
235
+ await trackEvent('button_click', {
236
+ button_name: 'signup',
237
+ button_location: 'header'
238
+ });
239
+ };
240
+
182
241
  return (
183
242
  <div>
184
243
  <p>Device: {deviceInfo?.deviceBrand} {deviceInfo?.deviceModel}</p>
185
244
  <p>Network: {networkInfo?.type}</p>
186
- <button onClick={() => logEvent({ action: 'button_click' })}>
245
+ <button onClick={handleButtonClick}>
187
246
  Track Click
188
247
  </button>
189
248
  </div>
@@ -250,6 +309,32 @@ interface UseAnalyticsOptions {
250
309
  attribution: AttributionInfo;
251
310
  }) => void; // Callback when data is ready
252
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
+ }
253
338
  ```
254
339
 
255
340
  #### Returns
@@ -264,6 +349,8 @@ interface UseAnalyticsReturn {
264
349
  pageVisits: number;
265
350
  interactions: number;
266
351
  logEvent: (customData?: Record<string, any>) => Promise<void>;
352
+ trackEvent: (eventName: string, parameters?: Record<string, any>) => Promise<void>;
353
+ trackPageView: (pageName?: string, parameters?: Record<string, any>) => Promise<void>;
267
354
  incrementInteraction: () => void;
268
355
  refresh: () => Promise<{
269
356
  net: NetworkInfo;
@@ -392,6 +479,26 @@ const attribution = AttributionDetector.detect();
392
479
 
393
480
  ### Services
394
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
+
395
502
  #### `AnalyticsService.trackUserJourney()`
396
503
 
397
504
  Send analytics data to your backend.
@@ -419,8 +526,111 @@ await AnalyticsService.trackUserJourney({
419
526
  });
420
527
  ```
421
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
+
422
558
  ### Utilities
423
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
+
424
634
  #### Location Consent Management
425
635
 
426
636
  ```typescript
@@ -444,6 +654,45 @@ setLocationConsentGranted();
444
654
  clearLocationConsent();
445
655
  ```
446
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
+
447
696
  #### IP Geolocation Utilities
448
697
 
449
698
  **Client-Side: Get Public IP**
@@ -527,12 +776,46 @@ class MyAnalyticsService extends AnalyticsService {
527
776
  }
528
777
  ```
529
778
 
530
- ### Manual Event Tracking
779
+ ### Custom Event Tracking (Firebase/GA-style)
780
+
781
+ Track custom events with automatic context collection:
782
+
783
+ ```typescript
784
+ const { trackEvent, trackPageView } = useAnalytics();
785
+
786
+ // Track button click
787
+ await trackEvent('button_click', {
788
+ button_name: 'signup',
789
+ button_location: 'header',
790
+ button_color: 'blue'
791
+ });
792
+
793
+ // Track purchase
794
+ await trackEvent('purchase', {
795
+ transaction_id: 'T12345',
796
+ value: 29.99,
797
+ currency: 'USD',
798
+ items: [
799
+ { id: 'item1', name: 'Product 1', price: 29.99 }
800
+ ]
801
+ });
802
+
803
+ // Track page views
804
+ await trackPageView('/dashboard', {
805
+ page_title: 'Dashboard',
806
+ user_type: 'premium'
807
+ });
808
+
809
+ // Track current page view
810
+ await trackPageView();
811
+ ```
812
+
813
+ ### Manual Event Tracking (Legacy)
531
814
 
532
815
  ```typescript
533
816
  const { logEvent, incrementInteraction } = useAnalytics();
534
817
 
535
- // Log custom event
818
+ // Log custom event with full control
536
819
  await logEvent({
537
820
  eventType: 'purchase',
538
821
  productId: '123',