@kitbase/analytics 0.1.6

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.
@@ -0,0 +1,1242 @@
1
+ /**
2
+ * Configuration options for offline event queueing
3
+ */
4
+ interface OfflineConfig {
5
+ /**
6
+ * Enable offline queueing
7
+ * @default false
8
+ */
9
+ enabled?: boolean;
10
+ /**
11
+ * Maximum number of events to store in the queue
12
+ * Oldest events are dropped when limit is reached
13
+ * @default 1000
14
+ */
15
+ maxQueueSize?: number;
16
+ /**
17
+ * Interval in milliseconds to flush queued events when online
18
+ * @default 30000 (30 seconds)
19
+ */
20
+ flushInterval?: number;
21
+ /**
22
+ * Number of events to send per batch when flushing
23
+ * @default 50
24
+ */
25
+ flushBatchSize?: number;
26
+ /**
27
+ * Maximum number of retry attempts for failed events
28
+ * @default 3
29
+ */
30
+ maxRetries?: number;
31
+ /**
32
+ * Base delay in milliseconds for exponential backoff
33
+ * @default 1000 (1 second)
34
+ */
35
+ retryBaseDelay?: number;
36
+ }
37
+ /**
38
+ * A queued event stored in the database
39
+ */
40
+ interface QueuedEvent {
41
+ /**
42
+ * Auto-incremented unique identifier
43
+ */
44
+ id?: number;
45
+ /**
46
+ * The event payload to send
47
+ */
48
+ payload: LogPayload;
49
+ /**
50
+ * Timestamp when the event was queued (ms since epoch)
51
+ */
52
+ timestamp: number;
53
+ /**
54
+ * Number of retry attempts made
55
+ */
56
+ retries: number;
57
+ /**
58
+ * Timestamp of the last retry attempt (ms since epoch)
59
+ */
60
+ lastAttempt?: number;
61
+ }
62
+ /**
63
+ * Statistics about the event queue
64
+ */
65
+ interface QueueStats {
66
+ /**
67
+ * Number of events currently in the queue
68
+ */
69
+ size: number;
70
+ /**
71
+ * Oldest event timestamp in the queue
72
+ */
73
+ oldestEvent?: number;
74
+ /**
75
+ * Whether the queue is currently flushing
76
+ */
77
+ isFlushing: boolean;
78
+ }
79
+
80
+ /**
81
+ * Bot detection module for filtering automated traffic
82
+ *
83
+ * Detects common automation tools, headless browsers, and bot user agents.
84
+ * Inspired by DataFast's bot detection approach.
85
+ */
86
+ /**
87
+ * Bot detection result
88
+ * @internal This is an internal API and may change without notice.
89
+ */
90
+ interface BotDetectionResult {
91
+ isBot: boolean;
92
+ reason?: string;
93
+ checks: {
94
+ webdriver: boolean;
95
+ phantomjs: boolean;
96
+ nightmare: boolean;
97
+ automationGlobals: boolean;
98
+ documentAttributes: boolean;
99
+ userAgentHeadless: boolean;
100
+ userAgentHttpClient: boolean;
101
+ missingUserAgent: boolean;
102
+ invalidEnvironment: boolean;
103
+ };
104
+ }
105
+ /**
106
+ * Configuration for bot detection
107
+ * @internal This is an internal API and may change without notice.
108
+ */
109
+ interface BotDetectionConfig {
110
+ /**
111
+ * Enable bot detection.
112
+ * When enabled and a bot is detected, all tracking events are blocked.
113
+ * Set to false to disable bot detection.
114
+ * @default true
115
+ */
116
+ enabled?: boolean;
117
+ /**
118
+ * Check for webdriver flag (Chrome, Firefox)
119
+ * @default true
120
+ */
121
+ checkWebdriver?: boolean;
122
+ /**
123
+ * Check for PhantomJS
124
+ * @default true
125
+ */
126
+ checkPhantomJS?: boolean;
127
+ /**
128
+ * Check for Nightmare.js
129
+ * @default true
130
+ */
131
+ checkNightmare?: boolean;
132
+ /**
133
+ * Check for automation tool globals
134
+ * @default true
135
+ */
136
+ checkAutomationGlobals?: boolean;
137
+ /**
138
+ * Check document element attributes
139
+ * @default true
140
+ */
141
+ checkDocumentAttributes?: boolean;
142
+ /**
143
+ * Check user agent for headless browsers
144
+ * @default true
145
+ */
146
+ checkUserAgentHeadless?: boolean;
147
+ /**
148
+ * Check user agent for HTTP clients/bots
149
+ * @default true
150
+ */
151
+ checkUserAgentHttpClient?: boolean;
152
+ /**
153
+ * Additional user agent patterns to detect as bots
154
+ */
155
+ additionalBotPatterns?: string[];
156
+ /**
157
+ * Callback when a bot is detected
158
+ */
159
+ onBotDetected?: (result: BotDetectionResult) => void;
160
+ }
161
+ /**
162
+ * Detect if the current visitor is a bot
163
+ *
164
+ * @internal This is an internal API and may change without notice.
165
+ * @param config - Bot detection configuration
166
+ * @returns Bot detection result
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * const result = detectBot();
171
+ * if (result.isBot) {
172
+ * console.log('Bot detected:', result.reason);
173
+ * }
174
+ * ```
175
+ */
176
+ declare function detectBot(config?: BotDetectionConfig): BotDetectionResult;
177
+ /**
178
+ * Quick check if current visitor is a bot
179
+ *
180
+ * @internal This is an internal API and may change without notice.
181
+ * @param config - Bot detection configuration
182
+ * @returns true if bot detected, false otherwise
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * if (isBot()) {
187
+ * console.log('Bot detected, skipping tracking');
188
+ * return;
189
+ * }
190
+ * ```
191
+ */
192
+ declare function isBot(config?: BotDetectionConfig): boolean;
193
+ /**
194
+ * Check a custom user agent string for bot patterns
195
+ * Useful for server-side bot detection
196
+ *
197
+ * @internal This is an internal API and may change without notice.
198
+ * @param userAgent - The user agent string to check
199
+ * @param additionalPatterns - Additional patterns to check
200
+ * @returns true if bot user agent detected
201
+ *
202
+ * @example
203
+ * ```typescript
204
+ * // Server-side usage
205
+ * const ua = request.headers['user-agent'];
206
+ * if (isUserAgentBot(ua)) {
207
+ * console.log('Bot request detected');
208
+ * }
209
+ * ```
210
+ */
211
+ declare function isUserAgentBot(userAgent: string, additionalPatterns?: string[]): boolean;
212
+ /**
213
+ * Get the current user agent (browser only)
214
+ *
215
+ * @internal This is an internal API and may change without notice.
216
+ * @returns User agent string or null if not in browser
217
+ */
218
+ declare function getUserAgent(): string | null;
219
+
220
+ /**
221
+ * Configuration options for the Kitbase client
222
+ */
223
+ interface KitbaseConfig {
224
+ /**
225
+ * Your Kitbase SDK key (sent as the `x-sdk-key` HTTP header)
226
+ */
227
+ sdkKey: string;
228
+ /**
229
+ * Override the default API endpoint.
230
+ * @default 'https://api.kitbase.dev'
231
+ */
232
+ baseUrl?: string;
233
+ /**
234
+ * Enable debug mode for console logging.
235
+ * @default false
236
+ */
237
+ debug?: boolean;
238
+ /**
239
+ * Offline queueing configuration.
240
+ * Events are queued locally when offline or when the API fails,
241
+ * and automatically sent when back online.
242
+ */
243
+ offline?: OfflineConfig;
244
+ /**
245
+ * Analytics tracking configuration.
246
+ * Enables pageview tracking and revenue tracking.
247
+ */
248
+ analytics?: AnalyticsConfig$1;
249
+ /**
250
+ * Bot detection configuration.
251
+ * When enabled, detects automated traffic and can block tracking for bots.
252
+ * @internal This is an internal API and may change without notice.
253
+ */
254
+ botDetection?: BotDetectionConfig;
255
+ }
256
+ /**
257
+ * Tag values can be strings, numbers, or booleans
258
+ */
259
+ type TagValue$1 = string | number | boolean;
260
+ /**
261
+ * Event tags for additional metadata
262
+ */
263
+ type Tags$1 = Record<string, TagValue$1>;
264
+ /**
265
+ * Options for tracking an event
266
+ */
267
+ interface TrackOptions$1 {
268
+ /**
269
+ * The channel/category for the event
270
+ * @example 'payments', 'auth', 'users'
271
+ */
272
+ channel: string;
273
+ /**
274
+ * The name of the event
275
+ * @example 'New Subscription', 'User Signed Up'
276
+ */
277
+ event: string;
278
+ /**
279
+ * Optional user identifier (set when user is identified/logged in)
280
+ */
281
+ user_id?: string;
282
+ /**
283
+ * Icon for the event (emoji or icon name)
284
+ * @example '💰', 'money_bag'
285
+ */
286
+ icon?: string;
287
+ /**
288
+ * Whether to send a notification for this event
289
+ * @default false
290
+ */
291
+ notify?: boolean;
292
+ /**
293
+ * Optional description for the event
294
+ */
295
+ description?: string;
296
+ /**
297
+ * Additional metadata tags
298
+ */
299
+ tags?: Tags$1;
300
+ }
301
+ /**
302
+ * Response from the track API
303
+ */
304
+ interface TrackResponse$1 {
305
+ /**
306
+ * Unique identifier for the logged event
307
+ */
308
+ id: string;
309
+ /**
310
+ * The event name
311
+ */
312
+ event: string;
313
+ /**
314
+ * Server timestamp when the event was recorded
315
+ */
316
+ timestamp: string;
317
+ }
318
+ /**
319
+ * Internal request payload sent to the API
320
+ */
321
+ interface LogPayload {
322
+ channel: string;
323
+ event: string;
324
+ user_id?: string;
325
+ icon?: string;
326
+ notify?: boolean;
327
+ description?: string;
328
+ tags?: Tags$1;
329
+ /**
330
+ * Client-side timestamp (ms since epoch) when the event occurred.
331
+ * Always set by the SDK for both online and offline events.
332
+ */
333
+ client_timestamp: number;
334
+ /**
335
+ * Client-generated session UUID, rotated after 30min of inactivity.
336
+ * Used by the server for offline session reconstruction.
337
+ */
338
+ client_session_id: string;
339
+ }
340
+ /**
341
+ * Configuration for analytics tracking
342
+ */
343
+ interface AnalyticsConfig$1 {
344
+ /**
345
+ * Enable automatic pageview tracking on route changes
346
+ * @default true
347
+ */
348
+ autoTrackPageViews?: boolean;
349
+ /**
350
+ * Enable automatic outbound link click tracking
351
+ * Tracks when users click links to external domains
352
+ * @default true
353
+ */
354
+ autoTrackOutboundLinks?: boolean;
355
+ /**
356
+ * Track clicks on interactive elements (buttons, links, inputs)
357
+ * @default true
358
+ */
359
+ autoTrackClicks?: boolean;
360
+ /**
361
+ * Track max scroll depth per page (sent on navigation)
362
+ * @default true
363
+ */
364
+ autoTrackScrollDepth?: boolean;
365
+ /**
366
+ * Track visibility duration of elements with `data-kb-track-visibility` attribute.
367
+ * Uses IntersectionObserver to measure how long elements are visible in the viewport.
368
+ * @default true
369
+ */
370
+ autoTrackVisibility?: boolean;
371
+ /**
372
+ * Track Core Web Vitals (LCP, CLS, INP, FCP, TTFB).
373
+ * Collects all metrics and sends them as a single `web_vitals` event.
374
+ * Requires the `web-vitals` library (included as a dependency).
375
+ * @default false
376
+ */
377
+ autoTrackWebVitals?: boolean;
378
+ /**
379
+ * Detect frustration signals (rage clicks and dead clicks).
380
+ * Rage clicks: 3+ rapid clicks in the same area within 1 second.
381
+ * Dead clicks: clicks on interactive elements that produce no DOM change.
382
+ * @default true
383
+ */
384
+ autoDetectFrustration?: boolean;
385
+ }
386
+ /**
387
+ * Options for tracking a pageview
388
+ */
389
+ interface PageViewOptions$1 {
390
+ /**
391
+ * The page path (defaults to window.location.pathname)
392
+ */
393
+ path?: string;
394
+ /**
395
+ * The page title (defaults to document.title)
396
+ */
397
+ title?: string;
398
+ /**
399
+ * The referrer URL
400
+ */
401
+ referrer?: string;
402
+ /**
403
+ * Additional metadata tags
404
+ */
405
+ tags?: Tags$1;
406
+ }
407
+ /**
408
+ * Options for tracking revenue
409
+ */
410
+ interface RevenueOptions {
411
+ /**
412
+ * Revenue amount in cents (e.g., 1999 for $19.99)
413
+ */
414
+ amount: number;
415
+ /**
416
+ * Currency code (e.g., 'USD', 'EUR')
417
+ * @default 'USD'
418
+ */
419
+ currency?: string;
420
+ /**
421
+ * Optional user identifier
422
+ */
423
+ user_id?: string;
424
+ /**
425
+ * Additional metadata tags
426
+ */
427
+ tags?: Tags$1;
428
+ }
429
+ /**
430
+ * Options for identifying a user
431
+ */
432
+ interface IdentifyOptions {
433
+ /**
434
+ * The unique user identifier
435
+ */
436
+ userId: string;
437
+ /**
438
+ * User traits/properties
439
+ */
440
+ traits?: Tags$1;
441
+ }
442
+
443
+ /**
444
+ * Configuration options for the Kitbase lite client (without offline queue)
445
+ */
446
+ interface KitbaseLiteConfig {
447
+ /**
448
+ * Your Kitbase SDK key (sent as the `x-sdk-key` HTTP header)
449
+ */
450
+ sdkKey: string;
451
+ /**
452
+ * Override the default API endpoint.
453
+ * @default 'https://api.kitbase.dev'
454
+ */
455
+ baseUrl?: string;
456
+ /**
457
+ * Enable debug mode for console logging.
458
+ * @default false
459
+ */
460
+ debug?: boolean;
461
+ /**
462
+ * Analytics tracking configuration.
463
+ * Enables pageview tracking and revenue tracking.
464
+ */
465
+ analytics?: AnalyticsConfig;
466
+ /**
467
+ * Bot detection configuration.
468
+ * When enabled, detects automated traffic and can block tracking for bots.
469
+ * @internal This is an internal API and may change without notice.
470
+ */
471
+ botDetection?: BotDetectionConfig;
472
+ }
473
+ /**
474
+ * Tag values can be strings, numbers, or booleans
475
+ */
476
+ type TagValue = string | number | boolean;
477
+ /**
478
+ * Event tags for additional metadata
479
+ */
480
+ type Tags = Record<string, TagValue>;
481
+ /**
482
+ * Options for tracking an event
483
+ */
484
+ interface TrackOptions {
485
+ /**
486
+ * The channel/category for the event
487
+ * @example 'payments', 'auth', 'users'
488
+ */
489
+ channel: string;
490
+ /**
491
+ * The name of the event
492
+ * @example 'New Subscription', 'User Signed Up'
493
+ */
494
+ event: string;
495
+ /**
496
+ * Optional user identifier (set when user is identified/logged in)
497
+ */
498
+ user_id?: string;
499
+ /**
500
+ * Icon for the event (emoji or icon name)
501
+ * @example '💰', 'money_bag'
502
+ */
503
+ icon?: string;
504
+ /**
505
+ * Whether to send a notification for this event
506
+ * @default false
507
+ */
508
+ notify?: boolean;
509
+ /**
510
+ * Optional description for the event
511
+ */
512
+ description?: string;
513
+ /**
514
+ * Additional metadata tags
515
+ */
516
+ tags?: Tags;
517
+ }
518
+ /**
519
+ * Response from the track API
520
+ */
521
+ interface TrackResponse {
522
+ /**
523
+ * Unique identifier for the logged event
524
+ */
525
+ id: string;
526
+ /**
527
+ * The event name
528
+ */
529
+ event: string;
530
+ /**
531
+ * Server timestamp when the event was recorded
532
+ */
533
+ timestamp: string;
534
+ }
535
+ /**
536
+ * Configuration for analytics tracking
537
+ */
538
+ interface AnalyticsConfig {
539
+ /**
540
+ * Enable automatic pageview tracking on route changes
541
+ * @default true
542
+ */
543
+ autoTrackPageViews?: boolean;
544
+ /**
545
+ * Enable automatic outbound link click tracking
546
+ * Tracks when users click links to external domains
547
+ * @default true
548
+ */
549
+ autoTrackOutboundLinks?: boolean;
550
+ /**
551
+ * Track clicks on interactive elements (buttons, links, inputs)
552
+ * @default true
553
+ */
554
+ autoTrackClicks?: boolean;
555
+ /**
556
+ * Track max scroll depth per page (sent on navigation)
557
+ * @default true
558
+ */
559
+ autoTrackScrollDepth?: boolean;
560
+ /**
561
+ * Track visibility duration of elements with `data-kb-track-visibility` attribute.
562
+ * Uses IntersectionObserver to measure how long elements are visible in the viewport.
563
+ * @default true
564
+ */
565
+ autoTrackVisibility?: boolean;
566
+ /**
567
+ * Track Core Web Vitals (LCP, CLS, INP, FCP, TTFB).
568
+ * Collects all metrics and sends them as a single `web_vitals` event.
569
+ * Requires the `web-vitals` library (included as a dependency).
570
+ * @default false
571
+ */
572
+ autoTrackWebVitals?: boolean;
573
+ /**
574
+ * Detect frustration signals (rage clicks and dead clicks).
575
+ * Rage clicks: 3+ rapid clicks in the same area within 1 second.
576
+ * Dead clicks: clicks on interactive elements that produce no DOM change.
577
+ * @default true
578
+ */
579
+ autoDetectFrustration?: boolean;
580
+ }
581
+ /**
582
+ * Options for tracking a pageview
583
+ */
584
+ interface PageViewOptions {
585
+ /**
586
+ * The page path (defaults to window.location.pathname)
587
+ */
588
+ path?: string;
589
+ /**
590
+ * The page title (defaults to document.title)
591
+ */
592
+ title?: string;
593
+ /**
594
+ * The referrer URL
595
+ */
596
+ referrer?: string;
597
+ /**
598
+ * Additional metadata tags
599
+ */
600
+ tags?: Tags;
601
+ }
602
+
603
+ interface KitbasePlugin {
604
+ readonly name: string;
605
+ setup(ctx: PluginContext): void | false;
606
+ teardown(): void;
607
+ methods?: Record<string, (...args: any[]) => any>;
608
+ }
609
+ interface PluginContext {
610
+ track(options: TrackOptions): Promise<TrackResponse | void>;
611
+ readonly config: Readonly<AnalyticsConfig>;
612
+ readonly debug: boolean;
613
+ log(message: string, data?: unknown): void;
614
+ isBotBlockingActive(): boolean;
615
+ findClickableElement(event: MouseEvent): Element | null;
616
+ readonly CLICKABLE_SELECTOR: string;
617
+ getRootDomain(hostname: string): string;
618
+ isSameRootDomain(host1: string, host2: string): boolean;
619
+ getUtmParams(): Tags;
620
+ }
621
+
622
+ /**
623
+ * Kitbase base client for tracking events (lite version without offline queue)
624
+ *
625
+ * This is a lightweight version of the Kitbase client that sends events
626
+ * directly to the API without offline queueing support.
627
+ *
628
+ * @example
629
+ * ```typescript
630
+ * import { Kitbase } from '@kitbase/analytics/lite';
631
+ *
632
+ * const kitbase = new Kitbase({
633
+ * sdkKey: '<YOUR_API_KEY>',
634
+ * debug: true,
635
+ * });
636
+ *
637
+ * // Register super properties (included in all events)
638
+ * kitbase.register({ app_version: '2.1.0', platform: 'web' });
639
+ *
640
+ * // Track events
641
+ * await kitbase.track({
642
+ * channel: 'payments',
643
+ * event: 'Page Viewed',
644
+ * icon: '👀',
645
+ * });
646
+ * ```
647
+ */
648
+ declare class KitbaseAnalytics$1 {
649
+ protected readonly sdkKey: string;
650
+ protected readonly baseUrl: string;
651
+ protected superProperties: Tags$1;
652
+ protected timedEvents: Map<string, number>;
653
+ protected debugMode: boolean;
654
+ protected analyticsConfig: KitbaseLiteConfig['analytics'];
655
+ protected userId: string | null;
656
+ protected botDetectionConfig: BotDetectionConfig;
657
+ protected botDetectionResult: BotDetectionResult | null;
658
+ private clientSessionId;
659
+ private lastActivityAt;
660
+ private static readonly SESSION_TIMEOUT_MS;
661
+ private _plugins;
662
+ private _pluginContext;
663
+ constructor(config: KitbaseLiteConfig, defaultPlugins?: KitbasePlugin[]);
664
+ /**
665
+ * Register a plugin
666
+ *
667
+ * @param plugin - The plugin instance to register
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * kitbase.use(new WebVitalsPlugin());
672
+ * ```
673
+ */
674
+ use(plugin: KitbasePlugin): void;
675
+ /**
676
+ * Get the names of all registered plugins
677
+ */
678
+ getPlugins(): string[];
679
+ private getPluginContext;
680
+ /**
681
+ * Enable or disable debug mode
682
+ * When enabled, all SDK operations are logged to the console
683
+ *
684
+ * @param enabled - Whether to enable debug mode
685
+ *
686
+ * @example
687
+ * ```typescript
688
+ * kitbase.setDebugMode(true);
689
+ * // All events and operations will now be logged
690
+ * ```
691
+ */
692
+ setDebugMode(enabled: boolean): void;
693
+ /**
694
+ * Check if debug mode is enabled
695
+ */
696
+ isDebugMode(): boolean;
697
+ /**
698
+ * Internal logging function
699
+ */
700
+ protected log(message: string, data?: unknown): void;
701
+ /**
702
+ * Register super properties that will be included with every event
703
+ * These properties are stored in memory only and reset on page reload
704
+ *
705
+ * @param properties - Properties to register
706
+ *
707
+ * @example
708
+ * ```typescript
709
+ * kitbase.register({
710
+ * app_version: '2.1.0',
711
+ * platform: 'web',
712
+ * environment: 'production',
713
+ * });
714
+ * ```
715
+ */
716
+ register(properties: Tags$1): void;
717
+ /**
718
+ * Register super properties only if they haven't been set yet
719
+ * Useful for setting default values that shouldn't override existing ones
720
+ *
721
+ * @param properties - Properties to register if not already set
722
+ *
723
+ * @example
724
+ * ```typescript
725
+ * kitbase.registerOnce({ first_visit: new Date().toISOString() });
726
+ * ```
727
+ */
728
+ registerOnce(properties: Tags$1): void;
729
+ /**
730
+ * Remove a super property
731
+ *
732
+ * @param key - The property key to remove
733
+ *
734
+ * @example
735
+ * ```typescript
736
+ * kitbase.unregister('platform');
737
+ * ```
738
+ */
739
+ unregister(key: string): void;
740
+ /**
741
+ * Get all registered super properties
742
+ *
743
+ * @returns A copy of the current super properties
744
+ *
745
+ * @example
746
+ * ```typescript
747
+ * const props = kitbase.getSuperProperties();
748
+ * console.log(props); // { app_version: '2.1.0', platform: 'web' }
749
+ * ```
750
+ */
751
+ getSuperProperties(): Tags$1;
752
+ /**
753
+ * Clear all super properties
754
+ *
755
+ * @example
756
+ * ```typescript
757
+ * kitbase.clearSuperProperties();
758
+ * ```
759
+ */
760
+ clearSuperProperties(): void;
761
+ /**
762
+ * Start timing an event
763
+ * When the same event is tracked later, a $duration property (in seconds)
764
+ * will automatically be included
765
+ *
766
+ * @param eventName - The name of the event to time
767
+ *
768
+ * @example
769
+ * ```typescript
770
+ * kitbase.timeEvent('Video Watched');
771
+ * // ... user watches video ...
772
+ * await kitbase.track({
773
+ * channel: 'engagement',
774
+ * event: 'Video Watched',
775
+ * tags: { video_id: '123' }
776
+ * });
777
+ * // Event will include $duration: 45.2 (seconds)
778
+ * ```
779
+ */
780
+ timeEvent(eventName: string): void;
781
+ /**
782
+ * Cancel a timed event without tracking it
783
+ *
784
+ * @param eventName - The name of the event to cancel timing for
785
+ *
786
+ * @example
787
+ * ```typescript
788
+ * kitbase.timeEvent('Checkout Flow');
789
+ * // User abandons checkout
790
+ * kitbase.cancelTimeEvent('Checkout Flow');
791
+ * ```
792
+ */
793
+ cancelTimeEvent(eventName: string): void;
794
+ /**
795
+ * Get all currently timed events
796
+ *
797
+ * @returns Array of event names that are currently being timed
798
+ *
799
+ * @example
800
+ * ```typescript
801
+ * const timedEvents = kitbase.getTimedEvents();
802
+ * console.log(timedEvents); // ['Video Watched', 'Checkout Flow']
803
+ * ```
804
+ */
805
+ getTimedEvents(): string[];
806
+ /**
807
+ * Get the duration of a timed event (without stopping it)
808
+ * @internal
809
+ *
810
+ * @param eventName - The name of the event
811
+ * @returns Duration in seconds, or null if not being timed
812
+ */
813
+ getEventDuration(eventName: string): number | null;
814
+ /**
815
+ * Check if the current visitor is detected as a bot
816
+ *
817
+ * @internal This is an internal API and may change without notice.
818
+ * @returns true if bot detected, false otherwise
819
+ *
820
+ * @example
821
+ * ```typescript
822
+ * if (kitbase.isBot()) {
823
+ * console.log('Bot detected, tracking disabled');
824
+ * }
825
+ * ```
826
+ */
827
+ isBot(): boolean;
828
+ /**
829
+ * Get detailed bot detection result
830
+ *
831
+ * @internal This is an internal API and may change without notice.
832
+ * @returns Bot detection result with detailed checks, or null if detection not enabled
833
+ *
834
+ * @example
835
+ * ```typescript
836
+ * const result = kitbase.getBotDetectionResult();
837
+ * if (result?.isBot) {
838
+ * console.log('Bot detected:', result.reason);
839
+ * console.log('Checks:', result.checks);
840
+ * }
841
+ * ```
842
+ */
843
+ getBotDetectionResult(): BotDetectionResult | null;
844
+ /**
845
+ * Force re-run bot detection
846
+ * Useful if you want to check again after page state changes
847
+ *
848
+ * @internal This is an internal API and may change without notice.
849
+ * @returns Updated bot detection result
850
+ *
851
+ * @example
852
+ * ```typescript
853
+ * const result = kitbase.redetectBot();
854
+ * console.log('Is bot:', result.isBot);
855
+ * ```
856
+ */
857
+ redetectBot(): BotDetectionResult;
858
+ /**
859
+ * Check if bot blocking is currently active
860
+ * When bot detection is enabled and a bot is detected, all events are blocked.
861
+ *
862
+ * @internal This is an internal API and may change without notice.
863
+ * @returns true if bots are being blocked from tracking
864
+ */
865
+ isBotBlockingActive(): boolean;
866
+ /**
867
+ * Get or create a client-side session ID.
868
+ * Rotates the session after 30 minutes of inactivity.
869
+ * @internal
870
+ */
871
+ protected getClientSessionId(): string;
872
+ /**
873
+ * Generate a UUID v4, with fallback for environments where
874
+ * crypto.randomUUID() is not available (older WebViews, Ionic).
875
+ */
876
+ private static generateUUID;
877
+ /**
878
+ * Track an event
879
+ *
880
+ * Events are sent directly to the API. For offline queueing support,
881
+ * use the full Kitbase client instead.
882
+ *
883
+ * @param options - Event tracking options
884
+ * @returns Promise resolving to the track response, or void if tracking is blocked
885
+ * @throws {ValidationError} When required fields are missing
886
+ * @throws {AuthenticationError} When the API key is invalid
887
+ * @throws {ApiError} When the API returns an error
888
+ * @throws {TimeoutError} When the request times out
889
+ */
890
+ track(options: TrackOptions$1): Promise<TrackResponse$1 | void>;
891
+ protected validateTrackOptions(options: TrackOptions$1): void;
892
+ /**
893
+ * Send a request to the API
894
+ */
895
+ protected sendRequest<T>(endpoint: string, body: unknown): Promise<T>;
896
+ protected parseResponseBody(response: Response): Promise<unknown>;
897
+ protected getErrorMessage(body: unknown, fallback: string): string;
898
+ /**
899
+ * Track a page view
900
+ *
901
+ * @param options - Page view options
902
+ * @returns Promise resolving to the track response
903
+ *
904
+ * @example
905
+ * ```typescript
906
+ * // Track current page
907
+ * await kitbase.trackPageView();
908
+ *
909
+ * // Track with custom path
910
+ * await kitbase.trackPageView({ path: '/products/123', title: 'Product Details' });
911
+ * ```
912
+ */
913
+ trackPageView(options?: PageViewOptions$1): Promise<TrackResponse$1 | void>;
914
+ /**
915
+ * Track a click on an interactive element
916
+ */
917
+ trackClick(tags: Tags$1): Promise<TrackResponse$1 | void>;
918
+ /**
919
+ * Track an outbound link click
920
+ *
921
+ * @param options - Outbound link options
922
+ * @returns Promise resolving to the track response
923
+ *
924
+ * @example
925
+ * ```typescript
926
+ * await kitbase.trackOutboundLink({
927
+ * url: 'https://example.com',
928
+ * text: 'Visit Example',
929
+ * });
930
+ * ```
931
+ */
932
+ trackOutboundLink(options: {
933
+ url: string;
934
+ text?: string;
935
+ }): Promise<TrackResponse$1 | void>;
936
+ /**
937
+ * Track a revenue event
938
+ *
939
+ * @param options - Revenue options
940
+ * @returns Promise resolving to the track response
941
+ *
942
+ * @example
943
+ * ```typescript
944
+ * // Track a $19.99 purchase
945
+ * await kitbase.trackRevenue({
946
+ * amount: 1999,
947
+ * currency: 'USD',
948
+ * tags: { product_id: 'prod_123', plan: 'premium' },
949
+ * });
950
+ * ```
951
+ */
952
+ trackRevenue(options: RevenueOptions): Promise<TrackResponse$1 | void>;
953
+ /**
954
+ * Identify a user
955
+ * Sets the user identity on the server.
956
+ * Call this when a user signs up or logs in.
957
+ *
958
+ * @param options - Identify options
959
+ * @returns Promise that resolves when the identity is set
960
+ *
961
+ * @example
962
+ * ```typescript
963
+ * await kitbase.identify({
964
+ * userId: 'user_123',
965
+ * traits: { email: 'user@example.com', plan: 'premium' },
966
+ * });
967
+ * ```
968
+ */
969
+ identify(options: IdentifyOptions): Promise<void>;
970
+ /**
971
+ * Get the current user ID (set via identify)
972
+ */
973
+ getUserId(): string | null;
974
+ /**
975
+ * Reset the user identity
976
+ * Call this when a user logs out
977
+ *
978
+ * @example
979
+ * ```typescript
980
+ * kitbase.reset();
981
+ * ```
982
+ */
983
+ reset(): void;
984
+ /**
985
+ * Shutdown the client and cleanup resources
986
+ * Call this when you're done using the client to stop timers and close connections
987
+ *
988
+ * @example
989
+ * ```typescript
990
+ * kitbase.shutdown();
991
+ * ```
992
+ */
993
+ shutdown(): void;
994
+ }
995
+
996
+ /**
997
+ * Initialize the Kitbase Analytics SDK
998
+ *
999
+ * Creates a singleton instance that is used for all tracking.
1000
+ * Call this once at the top of your application entry point.
1001
+ *
1002
+ * @param config - SDK configuration
1003
+ * @returns The KitbaseAnalytics instance
1004
+ *
1005
+ * @example
1006
+ * ```typescript
1007
+ * import { init } from '@kitbase/analytics';
1008
+ *
1009
+ * init({
1010
+ * sdkKey: '<YOUR_API_KEY>',
1011
+ * debug: true,
1012
+ * offline: { enabled: true },
1013
+ * });
1014
+ * ```
1015
+ */
1016
+ declare function init(config: KitbaseConfig): KitbaseAnalytics;
1017
+ /**
1018
+ * Get the current KitbaseAnalytics singleton instance
1019
+ *
1020
+ * @returns The instance, or null if `init()` has not been called
1021
+ */
1022
+ declare function getInstance(): KitbaseAnalytics | null;
1023
+ declare class KitbaseAnalytics extends KitbaseAnalytics$1 {
1024
+ private queue;
1025
+ private offlineEnabled;
1026
+ constructor(config: KitbaseConfig);
1027
+ /**
1028
+ * Enable or disable debug mode
1029
+ * When enabled, all SDK operations are logged to the console
1030
+ *
1031
+ * @param enabled - Whether to enable debug mode
1032
+ *
1033
+ * @example
1034
+ * ```typescript
1035
+ * kitbase.setDebugMode(true);
1036
+ * // All events and operations will now be logged
1037
+ * ```
1038
+ */
1039
+ setDebugMode(enabled: boolean): void;
1040
+ /**
1041
+ * Get offline queue statistics
1042
+ *
1043
+ * @returns Queue statistics including size and flush status
1044
+ *
1045
+ * @example
1046
+ * ```typescript
1047
+ * const stats = await kitbase.getQueueStats();
1048
+ * console.log(stats); // { size: 5, isFlushing: false }
1049
+ * ```
1050
+ */
1051
+ getQueueStats(): Promise<QueueStats | null>;
1052
+ /**
1053
+ * Manually flush the offline queue
1054
+ * Events are automatically flushed on interval and when coming back online,
1055
+ * but this method can be used to trigger an immediate flush
1056
+ *
1057
+ * @example
1058
+ * ```typescript
1059
+ * await kitbase.flushQueue();
1060
+ * ```
1061
+ */
1062
+ flushQueue(): Promise<void>;
1063
+ /**
1064
+ * Clear all events from the offline queue
1065
+ *
1066
+ * @example
1067
+ * ```typescript
1068
+ * await kitbase.clearQueue();
1069
+ * ```
1070
+ */
1071
+ clearQueue(): Promise<void>;
1072
+ /**
1073
+ * Callback for the queue to send batched events via the batch endpoint.
1074
+ * Sends all events in a single HTTP request instead of individual POSTs.
1075
+ */
1076
+ private sendQueuedEvents;
1077
+ /**
1078
+ * Track an event
1079
+ *
1080
+ * When offline queueing is enabled, events are always written to the local
1081
+ * database first (write-ahead), then sent to the server. This ensures no
1082
+ * events are lost if the browser crashes or the network fails.
1083
+ *
1084
+ * @param options - Event tracking options
1085
+ * @returns Promise resolving to the track response, or void if tracking is blocked
1086
+ * @throws {ValidationError} When required fields are missing
1087
+ * @throws {AuthenticationError} When the API key is invalid (only when offline disabled)
1088
+ * @throws {ApiError} When the API returns an error (only when offline disabled)
1089
+ * @throws {TimeoutError} When the request times out (only when offline disabled)
1090
+ */
1091
+ track(options: TrackOptions$1): Promise<TrackResponse$1 | void>;
1092
+ protected validateTrackOptions(options: TrackOptions$1): void;
1093
+ /**
1094
+ * Shutdown the client and cleanup resources
1095
+ * Call this when you're done using the client to stop timers and close connections
1096
+ *
1097
+ * @example
1098
+ * ```typescript
1099
+ * await kitbase.shutdown();
1100
+ * ```
1101
+ */
1102
+ shutdown(): Promise<void>;
1103
+ }
1104
+
1105
+ /**
1106
+ * Base error class for Kitbase SDK errors
1107
+ */
1108
+ declare class KitbaseError extends Error {
1109
+ constructor(message: string);
1110
+ }
1111
+ /**
1112
+ * Error thrown when API authentication fails
1113
+ */
1114
+ declare class AuthenticationError extends KitbaseError {
1115
+ constructor(message?: string);
1116
+ }
1117
+ /**
1118
+ * Error thrown when the API request fails
1119
+ */
1120
+ declare class ApiError extends KitbaseError {
1121
+ readonly statusCode: number;
1122
+ readonly response?: unknown;
1123
+ constructor(message: string, statusCode: number, response?: unknown);
1124
+ }
1125
+ /**
1126
+ * Error thrown when request validation fails
1127
+ */
1128
+ declare class ValidationError extends KitbaseError {
1129
+ readonly field?: string;
1130
+ constructor(message: string, field?: string);
1131
+ }
1132
+ /**
1133
+ * Error thrown when a request times out
1134
+ */
1135
+ declare class TimeoutError extends KitbaseError {
1136
+ constructor(message?: string);
1137
+ }
1138
+
1139
+ /**
1140
+ * Create the default set of plugins based on analytics configuration.
1141
+ * Reads config flags and instantiates only the enabled plugins.
1142
+ */
1143
+ declare function createDefaultPlugins(config?: AnalyticsConfig): KitbasePlugin[];
1144
+
1145
+ declare class PageViewPlugin implements KitbasePlugin {
1146
+ readonly name = "page-view";
1147
+ private ctx;
1148
+ private active;
1149
+ private popstateListener;
1150
+ setup(ctx: PluginContext): void | false;
1151
+ teardown(): void;
1152
+ get methods(): {
1153
+ trackPageView: (options?: PageViewOptions) => Promise<TrackResponse | void>;
1154
+ };
1155
+ private trackPageView;
1156
+ }
1157
+
1158
+ declare class OutboundLinksPlugin implements KitbasePlugin {
1159
+ readonly name = "outbound-links";
1160
+ private ctx;
1161
+ private clickListener;
1162
+ private keydownListener;
1163
+ setup(ctx: PluginContext): void | false;
1164
+ teardown(): void;
1165
+ get methods(): {
1166
+ trackOutboundLink: (options: {
1167
+ url: string;
1168
+ text?: string;
1169
+ }) => Promise<TrackResponse | void>;
1170
+ };
1171
+ private handleLinkClick;
1172
+ private trackOutboundLink;
1173
+ }
1174
+
1175
+ declare class ClickTrackingPlugin implements KitbasePlugin {
1176
+ readonly name = "click-tracking";
1177
+ private ctx;
1178
+ private clickListener;
1179
+ setup(ctx: PluginContext): void | false;
1180
+ teardown(): void;
1181
+ get methods(): {
1182
+ trackClick: (tags: Tags) => Promise<TrackResponse | void>;
1183
+ };
1184
+ private trackClick;
1185
+ }
1186
+
1187
+ declare class ScrollDepthPlugin implements KitbasePlugin {
1188
+ readonly name = "scroll-depth";
1189
+ private ctx;
1190
+ private active;
1191
+ private maxScrollDepth;
1192
+ private scrollListener;
1193
+ private beforeUnloadListener;
1194
+ private popstateListener;
1195
+ private scrollRafScheduled;
1196
+ setup(ctx: PluginContext): void | false;
1197
+ teardown(): void;
1198
+ private flushScrollDepth;
1199
+ }
1200
+
1201
+ declare class VisibilityPlugin implements KitbasePlugin {
1202
+ readonly name = "visibility";
1203
+ private ctx;
1204
+ private active;
1205
+ private visibilityObservers;
1206
+ private visibilityMutationObserver;
1207
+ private visibilityData;
1208
+ private beforeUnloadListener;
1209
+ private popstateListener;
1210
+ setup(ctx: PluginContext): void | false;
1211
+ teardown(): void;
1212
+ private scanForVisibilityElements;
1213
+ private observeVisibilityElement;
1214
+ private getOrCreateObserver;
1215
+ private flushVisibilityForElement;
1216
+ private flushAllVisibilityEvents;
1217
+ }
1218
+
1219
+ declare class WebVitalsPlugin implements KitbasePlugin {
1220
+ readonly name = "web-vitals";
1221
+ private ctx;
1222
+ private sent;
1223
+ private timeout;
1224
+ private beforeUnloadListener;
1225
+ private data;
1226
+ setup(ctx: PluginContext): void | false;
1227
+ teardown(): void;
1228
+ private sendWebVitals;
1229
+ }
1230
+
1231
+ declare class FrustrationPlugin implements KitbasePlugin {
1232
+ readonly name = "frustration";
1233
+ private ctx;
1234
+ private rageClickBuffer;
1235
+ private deadClickObserver;
1236
+ private deadClickTimeout;
1237
+ private clickListener;
1238
+ setup(ctx: PluginContext): void | false;
1239
+ teardown(): void;
1240
+ }
1241
+
1242
+ export { type AnalyticsConfig$1 as AnalyticsConfig, ApiError, AuthenticationError, type BotDetectionConfig, type BotDetectionResult, ClickTrackingPlugin, FrustrationPlugin, type IdentifyOptions, KitbaseAnalytics, type KitbaseConfig, KitbaseError, type KitbasePlugin, type OfflineConfig, OutboundLinksPlugin, type PageViewOptions$1 as PageViewOptions, PageViewPlugin, type PluginContext, type QueueStats, type QueuedEvent, type RevenueOptions, ScrollDepthPlugin, type TagValue$1 as TagValue, type Tags$1 as Tags, TimeoutError, type TrackOptions$1 as TrackOptions, type TrackResponse$1 as TrackResponse, ValidationError, VisibilityPlugin, WebVitalsPlugin, createDefaultPlugins, detectBot, getInstance, getUserAgent, init, isBot, isUserAgentBot };