@clianta/sdk 1.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.
@@ -0,0 +1,1809 @@
1
+ /*!
2
+ * Clianta SDK v1.0.0
3
+ * (c) 2026 Clianta
4
+ * Released under the MIT License.
5
+ */
6
+ 'use strict';
7
+
8
+ Object.defineProperty(exports, '__esModule', { value: true });
9
+
10
+ /**
11
+ * Clianta SDK - Configuration
12
+ * @version 1.0.0
13
+ */
14
+ /** SDK Version */
15
+ const SDK_VERSION = '1.0.0';
16
+ /** Default API endpoint based on environment */
17
+ const getDefaultApiEndpoint = () => {
18
+ if (typeof window === 'undefined')
19
+ return 'https://api.clianta.online';
20
+ const hostname = window.location.hostname;
21
+ if (hostname.includes('localhost') || hostname.includes('127.0.0.1')) {
22
+ return 'http://localhost:5000';
23
+ }
24
+ return 'https://api.clianta.online';
25
+ };
26
+ /** Core plugins enabled by default */
27
+ const DEFAULT_PLUGINS = [
28
+ 'pageView',
29
+ 'forms',
30
+ 'scroll',
31
+ 'clicks',
32
+ 'engagement',
33
+ 'downloads',
34
+ 'exitIntent',
35
+ ];
36
+ /** Default configuration values */
37
+ const DEFAULT_CONFIG = {
38
+ apiEndpoint: getDefaultApiEndpoint(),
39
+ debug: false,
40
+ autoPageView: true,
41
+ plugins: DEFAULT_PLUGINS,
42
+ sessionTimeout: 30 * 60 * 1000, // 30 minutes
43
+ batchSize: 10,
44
+ flushInterval: 5000, // 5 seconds
45
+ consent: {
46
+ defaultConsent: { analytics: true, marketing: false, personalization: false },
47
+ waitForConsent: false,
48
+ storageKey: 'mb_consent',
49
+ },
50
+ cookieDomain: '',
51
+ useCookies: false,
52
+ };
53
+ /** Storage keys */
54
+ const STORAGE_KEYS = {
55
+ VISITOR_ID: 'mb_vid',
56
+ SESSION_ID: 'mb_sid',
57
+ SESSION_TIMESTAMP: 'mb_st',
58
+ CONSENT: 'mb_consent',
59
+ EVENT_QUEUE: 'mb_queue',
60
+ };
61
+ /** Scroll depth milestones to track */
62
+ const SCROLL_MILESTONES = [25, 50, 75, 100];
63
+ /** File extensions to track as downloads */
64
+ const DOWNLOAD_EXTENSIONS = [
65
+ '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
66
+ '.zip', '.rar', '.tar', '.gz', '.7z',
67
+ '.csv', '.txt', '.json', '.xml',
68
+ '.mp3', '.mp4', '.wav', '.avi', '.mov',
69
+ ];
70
+ /**
71
+ * Merge user config with defaults
72
+ */
73
+ function mergeConfig(userConfig = {}) {
74
+ return {
75
+ ...DEFAULT_CONFIG,
76
+ ...userConfig,
77
+ consent: {
78
+ ...DEFAULT_CONFIG.consent,
79
+ ...userConfig.consent,
80
+ },
81
+ };
82
+ }
83
+
84
+ /**
85
+ * MorrisB Tracking SDK - Debug Logger
86
+ * @version 3.0.0
87
+ */
88
+ const LOG_PREFIX = '[Clianta]';
89
+ const LOG_STYLES = {
90
+ debug: 'color: #6b7280; font-weight: normal;',
91
+ info: 'color: #3b82f6; font-weight: normal;',
92
+ warn: 'color: #f59e0b; font-weight: bold;',
93
+ error: 'color: #ef4444; font-weight: bold;',
94
+ };
95
+ const LOG_LEVELS = {
96
+ debug: 0,
97
+ info: 1,
98
+ warn: 2,
99
+ error: 3,
100
+ };
101
+ /**
102
+ * Create a logger instance
103
+ */
104
+ function createLogger(enabled = false) {
105
+ let currentLevel = 'debug';
106
+ let isEnabled = enabled;
107
+ const shouldLog = (level) => {
108
+ if (!isEnabled)
109
+ return false;
110
+ return LOG_LEVELS[level] >= LOG_LEVELS[currentLevel];
111
+ };
112
+ const formatArgs = (level, args) => {
113
+ if (typeof console !== 'undefined' && typeof window !== 'undefined') {
114
+ // Browser with styled console
115
+ return [`%c${LOG_PREFIX}`, LOG_STYLES[level], ...args];
116
+ }
117
+ // Node.js or basic console
118
+ return [`${LOG_PREFIX} [${level.toUpperCase()}]`, ...args];
119
+ };
120
+ return {
121
+ get enabled() {
122
+ return isEnabled;
123
+ },
124
+ set enabled(value) {
125
+ isEnabled = value;
126
+ },
127
+ debug(...args) {
128
+ if (shouldLog('debug') && typeof console !== 'undefined') {
129
+ console.log(...formatArgs('debug', args));
130
+ }
131
+ },
132
+ info(...args) {
133
+ if (shouldLog('info') && typeof console !== 'undefined') {
134
+ console.info(...formatArgs('info', args));
135
+ }
136
+ },
137
+ warn(...args) {
138
+ if (shouldLog('warn') && typeof console !== 'undefined') {
139
+ console.warn(...formatArgs('warn', args));
140
+ }
141
+ },
142
+ error(...args) {
143
+ if (shouldLog('error') && typeof console !== 'undefined') {
144
+ console.error(...formatArgs('error', args));
145
+ }
146
+ },
147
+ setLevel(level) {
148
+ currentLevel = level;
149
+ },
150
+ };
151
+ }
152
+ /** Global logger instance */
153
+ const logger = createLogger(false);
154
+
155
+ /**
156
+ * MorrisB Tracking SDK - Transport Layer
157
+ * Handles sending events to the backend with retry logic
158
+ * @version 3.0.0
159
+ */
160
+ const DEFAULT_TIMEOUT = 10000; // 10 seconds
161
+ const DEFAULT_MAX_RETRIES = 3;
162
+ const DEFAULT_RETRY_DELAY = 1000; // 1 second
163
+ /**
164
+ * Transport class for sending data to the backend
165
+ */
166
+ class Transport {
167
+ constructor(config) {
168
+ this.config = {
169
+ apiEndpoint: config.apiEndpoint,
170
+ maxRetries: config.maxRetries ?? DEFAULT_MAX_RETRIES,
171
+ retryDelay: config.retryDelay ?? DEFAULT_RETRY_DELAY,
172
+ timeout: config.timeout ?? DEFAULT_TIMEOUT,
173
+ };
174
+ }
175
+ /**
176
+ * Send events to the tracking endpoint
177
+ */
178
+ async sendEvents(events) {
179
+ const url = `${this.config.apiEndpoint}/api/public/track/event`;
180
+ const payload = JSON.stringify({ events });
181
+ return this.send(url, payload);
182
+ }
183
+ /**
184
+ * Send identify request
185
+ */
186
+ async sendIdentify(data) {
187
+ const url = `${this.config.apiEndpoint}/api/public/track/identify`;
188
+ const payload = JSON.stringify(data);
189
+ return this.send(url, payload);
190
+ }
191
+ /**
192
+ * Send events synchronously (for page unload)
193
+ * Uses navigator.sendBeacon for reliability
194
+ */
195
+ sendBeacon(events) {
196
+ if (typeof navigator === 'undefined' || !navigator.sendBeacon) {
197
+ logger.warn('sendBeacon not available, events may be lost');
198
+ return false;
199
+ }
200
+ const url = `${this.config.apiEndpoint}/api/public/track/event`;
201
+ const payload = JSON.stringify({ events });
202
+ const blob = new Blob([payload], { type: 'application/json' });
203
+ try {
204
+ const success = navigator.sendBeacon(url, blob);
205
+ if (success) {
206
+ logger.debug(`Beacon sent ${events.length} events`);
207
+ }
208
+ else {
209
+ logger.warn('sendBeacon returned false');
210
+ }
211
+ return success;
212
+ }
213
+ catch (error) {
214
+ logger.error('sendBeacon error:', error);
215
+ return false;
216
+ }
217
+ }
218
+ /**
219
+ * Internal send with retry logic
220
+ */
221
+ async send(url, payload, attempt = 1) {
222
+ try {
223
+ const response = await this.fetchWithTimeout(url, {
224
+ method: 'POST',
225
+ headers: {
226
+ 'Content-Type': 'application/json',
227
+ },
228
+ body: payload,
229
+ keepalive: true,
230
+ });
231
+ if (response.ok) {
232
+ logger.debug('Request successful:', url);
233
+ return { success: true, status: response.status };
234
+ }
235
+ // Server error - may retry
236
+ if (response.status >= 500 && attempt < this.config.maxRetries) {
237
+ logger.warn(`Server error (${response.status}), retrying...`);
238
+ await this.delay(this.config.retryDelay * attempt);
239
+ return this.send(url, payload, attempt + 1);
240
+ }
241
+ // Client error - don't retry
242
+ logger.error(`Request failed with status ${response.status}`);
243
+ return { success: false, status: response.status };
244
+ }
245
+ catch (error) {
246
+ // Network error - retry if possible
247
+ if (attempt < this.config.maxRetries) {
248
+ logger.warn(`Network error, retrying (${attempt}/${this.config.maxRetries})...`);
249
+ await this.delay(this.config.retryDelay * attempt);
250
+ return this.send(url, payload, attempt + 1);
251
+ }
252
+ logger.error('Request failed after retries:', error);
253
+ return { success: false, error: error };
254
+ }
255
+ }
256
+ /**
257
+ * Fetch with timeout
258
+ */
259
+ async fetchWithTimeout(url, options) {
260
+ const controller = new AbortController();
261
+ const timeout = setTimeout(() => controller.abort(), this.config.timeout);
262
+ try {
263
+ const response = await fetch(url, {
264
+ ...options,
265
+ signal: controller.signal,
266
+ });
267
+ return response;
268
+ }
269
+ finally {
270
+ clearTimeout(timeout);
271
+ }
272
+ }
273
+ /**
274
+ * Delay helper
275
+ */
276
+ delay(ms) {
277
+ return new Promise((resolve) => setTimeout(resolve, ms));
278
+ }
279
+ }
280
+
281
+ /**
282
+ * MorrisB Tracking SDK - Utility Functions
283
+ * @version 3.0.0
284
+ */
285
+ // ============================================
286
+ // UUID GENERATION
287
+ // ============================================
288
+ /**
289
+ * Generate a UUID v4
290
+ */
291
+ function generateUUID() {
292
+ // Use crypto.randomUUID if available (modern browsers)
293
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
294
+ return crypto.randomUUID();
295
+ }
296
+ // Fallback to manual generation
297
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
298
+ const r = (Math.random() * 16) | 0;
299
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
300
+ return v.toString(16);
301
+ });
302
+ }
303
+ // ============================================
304
+ // STORAGE UTILITIES
305
+ // ============================================
306
+ /**
307
+ * Safely get from localStorage
308
+ */
309
+ function getLocalStorage(key) {
310
+ try {
311
+ if (typeof localStorage !== 'undefined') {
312
+ return localStorage.getItem(key);
313
+ }
314
+ }
315
+ catch {
316
+ // localStorage not available or blocked
317
+ }
318
+ return null;
319
+ }
320
+ /**
321
+ * Safely set to localStorage
322
+ */
323
+ function setLocalStorage(key, value) {
324
+ try {
325
+ if (typeof localStorage !== 'undefined') {
326
+ localStorage.setItem(key, value);
327
+ return true;
328
+ }
329
+ }
330
+ catch {
331
+ // localStorage not available or blocked
332
+ }
333
+ return false;
334
+ }
335
+ /**
336
+ * Safely get from sessionStorage
337
+ */
338
+ function getSessionStorage(key) {
339
+ try {
340
+ if (typeof sessionStorage !== 'undefined') {
341
+ return sessionStorage.getItem(key);
342
+ }
343
+ }
344
+ catch {
345
+ // sessionStorage not available or blocked
346
+ }
347
+ return null;
348
+ }
349
+ /**
350
+ * Safely set to sessionStorage
351
+ */
352
+ function setSessionStorage(key, value) {
353
+ try {
354
+ if (typeof sessionStorage !== 'undefined') {
355
+ sessionStorage.setItem(key, value);
356
+ return true;
357
+ }
358
+ }
359
+ catch {
360
+ // sessionStorage not available or blocked
361
+ }
362
+ return false;
363
+ }
364
+ /**
365
+ * Get or set a cookie
366
+ */
367
+ function cookie(name, value, days) {
368
+ if (typeof document === 'undefined')
369
+ return null;
370
+ // Get cookie
371
+ if (value === undefined) {
372
+ const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
373
+ return match ? match[2] : null;
374
+ }
375
+ // Set cookie
376
+ let expires = '';
377
+ if (days) {
378
+ const date = new Date();
379
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
380
+ expires = '; expires=' + date.toUTCString();
381
+ }
382
+ document.cookie = name + '=' + value + expires + '; path=/; SameSite=Lax';
383
+ return value;
384
+ }
385
+ // ============================================
386
+ // VISITOR & SESSION MANAGEMENT
387
+ // ============================================
388
+ /**
389
+ * Get or create a persistent visitor ID
390
+ */
391
+ function getOrCreateVisitorId(useCookies = false) {
392
+ const key = STORAGE_KEYS.VISITOR_ID;
393
+ // Try to get existing ID
394
+ let visitorId = null;
395
+ if (useCookies) {
396
+ visitorId = cookie(key);
397
+ }
398
+ else {
399
+ visitorId = getLocalStorage(key);
400
+ }
401
+ // Create new ID if not found
402
+ if (!visitorId) {
403
+ visitorId = generateUUID();
404
+ if (useCookies) {
405
+ cookie(key, visitorId, 365); // 1 year
406
+ }
407
+ else {
408
+ setLocalStorage(key, visitorId);
409
+ }
410
+ }
411
+ return visitorId;
412
+ }
413
+ /**
414
+ * Get or create a session ID (expires after timeout)
415
+ */
416
+ function getOrCreateSessionId(timeout) {
417
+ const sidKey = STORAGE_KEYS.SESSION_ID;
418
+ const tsKey = STORAGE_KEYS.SESSION_TIMESTAMP;
419
+ let sessionId = getSessionStorage(sidKey);
420
+ const lastActivity = parseInt(getSessionStorage(tsKey) || '0', 10);
421
+ const now = Date.now();
422
+ // Check if session expired
423
+ if (!sessionId || now - lastActivity > timeout) {
424
+ sessionId = generateUUID();
425
+ setSessionStorage(sidKey, sessionId);
426
+ }
427
+ // Update last activity
428
+ setSessionStorage(tsKey, now.toString());
429
+ return sessionId;
430
+ }
431
+ /**
432
+ * Reset visitor and session IDs
433
+ */
434
+ function resetIds(useCookies = false) {
435
+ const visitorKey = STORAGE_KEYS.VISITOR_ID;
436
+ if (useCookies) {
437
+ cookie(visitorKey, '', -1); // Delete cookie
438
+ }
439
+ else {
440
+ try {
441
+ localStorage.removeItem(visitorKey);
442
+ }
443
+ catch {
444
+ // Ignore
445
+ }
446
+ }
447
+ try {
448
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_ID);
449
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_TIMESTAMP);
450
+ }
451
+ catch {
452
+ // Ignore
453
+ }
454
+ }
455
+ // ============================================
456
+ // URL UTILITIES
457
+ // ============================================
458
+ /**
459
+ * Extract UTM parameters from URL
460
+ */
461
+ function getUTMParams() {
462
+ if (typeof window === 'undefined')
463
+ return {};
464
+ try {
465
+ const params = new URLSearchParams(window.location.search);
466
+ return {
467
+ utmSource: params.get('utm_source') || undefined,
468
+ utmMedium: params.get('utm_medium') || undefined,
469
+ utmCampaign: params.get('utm_campaign') || undefined,
470
+ utmTerm: params.get('utm_term') || undefined,
471
+ utmContent: params.get('utm_content') || undefined,
472
+ };
473
+ }
474
+ catch {
475
+ return {};
476
+ }
477
+ }
478
+ /**
479
+ * Check if URL is a download link
480
+ */
481
+ function isDownloadUrl(url) {
482
+ const lowerUrl = url.toLowerCase();
483
+ return DOWNLOAD_EXTENSIONS.some((ext) => lowerUrl.includes(ext));
484
+ }
485
+ /**
486
+ * Extract filename from URL
487
+ */
488
+ function getFilenameFromUrl(url) {
489
+ try {
490
+ return url.split('/').pop()?.split('?')[0] || 'unknown';
491
+ }
492
+ catch {
493
+ return 'unknown';
494
+ }
495
+ }
496
+ /**
497
+ * Extract file extension from URL
498
+ */
499
+ function getFileExtension(url) {
500
+ const filename = getFilenameFromUrl(url);
501
+ const parts = filename.split('.');
502
+ return parts.length > 1 ? parts.pop() || 'unknown' : 'unknown';
503
+ }
504
+ // ============================================
505
+ // DOM UTILITIES
506
+ // ============================================
507
+ /**
508
+ * Get text content from element (truncated)
509
+ */
510
+ function getElementText(element, maxLength = 100) {
511
+ const text = element.innerText ||
512
+ element.textContent ||
513
+ element.value ||
514
+ '';
515
+ return text.trim().substring(0, maxLength);
516
+ }
517
+ /**
518
+ * Get element identification info
519
+ */
520
+ function getElementInfo(element) {
521
+ return {
522
+ tag: element.tagName?.toLowerCase() || 'unknown',
523
+ id: element.id || '',
524
+ className: element.className || '',
525
+ text: getElementText(element, 50),
526
+ };
527
+ }
528
+ /**
529
+ * Check if element is a trackable click target
530
+ */
531
+ function isTrackableClickElement(element) {
532
+ const trackableTags = ['BUTTON', 'A', 'INPUT'];
533
+ return (trackableTags.includes(element.tagName) ||
534
+ element.hasAttribute('data-track-click') ||
535
+ element.classList.contains('track-click'));
536
+ }
537
+ /**
538
+ * Check if device is mobile
539
+ */
540
+ function isMobile() {
541
+ if (typeof navigator === 'undefined')
542
+ return false;
543
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
544
+ }
545
+ // ============================================
546
+ // DEVICE INFO
547
+ // ============================================
548
+ /**
549
+ * Get current device information
550
+ */
551
+ function getDeviceInfo() {
552
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
553
+ return {
554
+ userAgent: 'unknown',
555
+ screen: 'unknown',
556
+ language: 'unknown',
557
+ timezone: 'unknown',
558
+ };
559
+ }
560
+ return {
561
+ userAgent: navigator.userAgent,
562
+ screen: `${screen.width}x${screen.height}`,
563
+ language: navigator.language,
564
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'unknown',
565
+ };
566
+ }
567
+
568
+ /**
569
+ * MorrisB Tracking SDK - Event Queue
570
+ * Handles batching and flushing of events
571
+ * @version 3.0.0
572
+ */
573
+ const MAX_QUEUE_SIZE = 1000;
574
+ /**
575
+ * Event queue with batching, persistence, and auto-flush
576
+ */
577
+ class EventQueue {
578
+ constructor(transport, config = {}) {
579
+ this.queue = [];
580
+ this.flushTimer = null;
581
+ this.isFlushing = false;
582
+ this.transport = transport;
583
+ this.config = {
584
+ batchSize: config.batchSize ?? 10,
585
+ flushInterval: config.flushInterval ?? 5000,
586
+ maxQueueSize: config.maxQueueSize ?? MAX_QUEUE_SIZE,
587
+ storageKey: config.storageKey ?? STORAGE_KEYS.EVENT_QUEUE,
588
+ };
589
+ // Restore persisted queue
590
+ this.restoreQueue();
591
+ // Start auto-flush timer
592
+ this.startFlushTimer();
593
+ // Setup unload handlers
594
+ this.setupUnloadHandlers();
595
+ }
596
+ /**
597
+ * Add an event to the queue
598
+ */
599
+ push(event) {
600
+ // Don't exceed max queue size
601
+ if (this.queue.length >= this.config.maxQueueSize) {
602
+ logger.warn('Queue full, dropping oldest event');
603
+ this.queue.shift();
604
+ }
605
+ this.queue.push(event);
606
+ logger.debug('Event queued:', event.eventName, `(${this.queue.length} in queue)`);
607
+ // Flush if batch size reached
608
+ if (this.queue.length >= this.config.batchSize) {
609
+ this.flush();
610
+ }
611
+ }
612
+ /**
613
+ * Flush the queue (send all events)
614
+ */
615
+ async flush() {
616
+ if (this.isFlushing || this.queue.length === 0) {
617
+ return;
618
+ }
619
+ this.isFlushing = true;
620
+ try {
621
+ // Take all events from queue
622
+ const events = this.queue.splice(0, this.queue.length);
623
+ logger.debug(`Flushing ${events.length} events`);
624
+ // Clear persisted queue
625
+ this.persistQueue([]);
626
+ // Send to backend
627
+ const result = await this.transport.sendEvents(events);
628
+ if (!result.success) {
629
+ // Re-queue events on failure (at the front)
630
+ logger.warn('Flush failed, re-queuing events');
631
+ this.queue.unshift(...events);
632
+ this.persistQueue(this.queue);
633
+ }
634
+ else {
635
+ logger.debug('Flush successful');
636
+ }
637
+ }
638
+ catch (error) {
639
+ logger.error('Flush error:', error);
640
+ }
641
+ finally {
642
+ this.isFlushing = false;
643
+ }
644
+ }
645
+ /**
646
+ * Flush synchronously using sendBeacon (for page unload)
647
+ */
648
+ flushSync() {
649
+ if (this.queue.length === 0)
650
+ return;
651
+ const events = this.queue.splice(0, this.queue.length);
652
+ logger.debug(`Sync flushing ${events.length} events via beacon`);
653
+ const success = this.transport.sendBeacon(events);
654
+ if (!success) {
655
+ // Re-queue and persist for next page load
656
+ this.queue.unshift(...events);
657
+ this.persistQueue(this.queue);
658
+ }
659
+ }
660
+ /**
661
+ * Get current queue length
662
+ */
663
+ get length() {
664
+ return this.queue.length;
665
+ }
666
+ /**
667
+ * Clear the queue
668
+ */
669
+ clear() {
670
+ this.queue = [];
671
+ this.persistQueue([]);
672
+ }
673
+ /**
674
+ * Stop the flush timer
675
+ */
676
+ destroy() {
677
+ if (this.flushTimer) {
678
+ clearInterval(this.flushTimer);
679
+ this.flushTimer = null;
680
+ }
681
+ }
682
+ /**
683
+ * Start auto-flush timer
684
+ */
685
+ startFlushTimer() {
686
+ if (this.flushTimer) {
687
+ clearInterval(this.flushTimer);
688
+ }
689
+ this.flushTimer = setInterval(() => {
690
+ this.flush();
691
+ }, this.config.flushInterval);
692
+ }
693
+ /**
694
+ * Setup page unload handlers
695
+ */
696
+ setupUnloadHandlers() {
697
+ if (typeof window === 'undefined')
698
+ return;
699
+ // Flush on page unload
700
+ window.addEventListener('beforeunload', () => {
701
+ this.flushSync();
702
+ });
703
+ // Flush when page becomes hidden
704
+ window.addEventListener('visibilitychange', () => {
705
+ if (document.visibilityState === 'hidden') {
706
+ this.flushSync();
707
+ }
708
+ });
709
+ // Flush on page hide (iOS Safari)
710
+ window.addEventListener('pagehide', () => {
711
+ this.flushSync();
712
+ });
713
+ }
714
+ /**
715
+ * Persist queue to localStorage
716
+ */
717
+ persistQueue(events) {
718
+ try {
719
+ setLocalStorage(this.config.storageKey, JSON.stringify(events));
720
+ }
721
+ catch {
722
+ // Ignore storage errors
723
+ }
724
+ }
725
+ /**
726
+ * Restore queue from localStorage
727
+ */
728
+ restoreQueue() {
729
+ try {
730
+ const stored = getLocalStorage(this.config.storageKey);
731
+ if (stored) {
732
+ const events = JSON.parse(stored);
733
+ if (Array.isArray(events) && events.length > 0) {
734
+ this.queue = events;
735
+ logger.debug(`Restored ${events.length} events from storage`);
736
+ }
737
+ }
738
+ }
739
+ catch {
740
+ // Ignore parse errors
741
+ }
742
+ }
743
+ }
744
+
745
+ /**
746
+ * MorrisB Tracking SDK - Plugin Base
747
+ * @version 3.0.0
748
+ */
749
+ /**
750
+ * Base class for plugins
751
+ */
752
+ class BasePlugin {
753
+ constructor() {
754
+ this.tracker = null;
755
+ }
756
+ init(tracker) {
757
+ this.tracker = tracker;
758
+ }
759
+ destroy() {
760
+ this.tracker = null;
761
+ }
762
+ track(eventType, eventName, properties) {
763
+ if (this.tracker) {
764
+ this.tracker.track(eventType, eventName, properties);
765
+ }
766
+ }
767
+ }
768
+
769
+ /**
770
+ * MorrisB Tracking SDK - Page View Plugin
771
+ * @version 3.0.0
772
+ */
773
+ /**
774
+ * Page View Plugin - Tracks page views
775
+ */
776
+ class PageViewPlugin extends BasePlugin {
777
+ constructor() {
778
+ super(...arguments);
779
+ this.name = 'pageView';
780
+ }
781
+ init(tracker) {
782
+ super.init(tracker);
783
+ // Track initial page view
784
+ this.trackPageView();
785
+ // Track SPA navigation (History API)
786
+ if (typeof window !== 'undefined') {
787
+ // Intercept pushState and replaceState
788
+ const originalPushState = history.pushState;
789
+ const originalReplaceState = history.replaceState;
790
+ history.pushState = (...args) => {
791
+ originalPushState.apply(history, args);
792
+ this.trackPageView();
793
+ };
794
+ history.replaceState = (...args) => {
795
+ originalReplaceState.apply(history, args);
796
+ this.trackPageView();
797
+ };
798
+ // Handle back/forward navigation
799
+ window.addEventListener('popstate', () => {
800
+ this.trackPageView();
801
+ });
802
+ }
803
+ }
804
+ trackPageView() {
805
+ if (typeof window === 'undefined' || typeof document === 'undefined')
806
+ return;
807
+ this.track('page_view', 'Page Viewed', {
808
+ title: document.title,
809
+ path: window.location.pathname,
810
+ search: window.location.search,
811
+ hash: window.location.hash,
812
+ referrer: document.referrer || 'direct',
813
+ viewport: `${window.innerWidth}x${window.innerHeight}`,
814
+ });
815
+ }
816
+ }
817
+
818
+ /**
819
+ * MorrisB Tracking SDK - Scroll Depth Plugin
820
+ * @version 3.0.0
821
+ */
822
+ /**
823
+ * Scroll Depth Plugin - Tracks scroll milestones
824
+ */
825
+ class ScrollPlugin extends BasePlugin {
826
+ constructor() {
827
+ super(...arguments);
828
+ this.name = 'scroll';
829
+ this.milestonesReached = new Set();
830
+ this.maxScrollDepth = 0;
831
+ this.pageLoadTime = 0;
832
+ this.scrollTimeout = null;
833
+ this.boundHandler = null;
834
+ }
835
+ init(tracker) {
836
+ super.init(tracker);
837
+ this.pageLoadTime = Date.now();
838
+ if (typeof window !== 'undefined') {
839
+ this.boundHandler = this.handleScroll.bind(this);
840
+ window.addEventListener('scroll', this.boundHandler, { passive: true });
841
+ }
842
+ }
843
+ destroy() {
844
+ if (this.boundHandler && typeof window !== 'undefined') {
845
+ window.removeEventListener('scroll', this.boundHandler);
846
+ }
847
+ if (this.scrollTimeout) {
848
+ clearTimeout(this.scrollTimeout);
849
+ }
850
+ super.destroy();
851
+ }
852
+ handleScroll() {
853
+ // Debounce scroll tracking
854
+ if (this.scrollTimeout) {
855
+ clearTimeout(this.scrollTimeout);
856
+ }
857
+ this.scrollTimeout = setTimeout(() => this.trackScrollDepth(), 150);
858
+ }
859
+ trackScrollDepth() {
860
+ if (typeof window === 'undefined' || typeof document === 'undefined')
861
+ return;
862
+ const windowHeight = window.innerHeight;
863
+ const documentHeight = document.documentElement.scrollHeight;
864
+ const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
865
+ const scrollPercent = Math.floor((scrollTop / (documentHeight - windowHeight)) * 100);
866
+ // Clamp to valid range
867
+ const clampedPercent = Math.max(0, Math.min(100, scrollPercent));
868
+ // Update max scroll depth
869
+ if (clampedPercent > this.maxScrollDepth) {
870
+ this.maxScrollDepth = clampedPercent;
871
+ }
872
+ // Track milestones
873
+ for (const milestone of SCROLL_MILESTONES) {
874
+ if (clampedPercent >= milestone && !this.milestonesReached.has(milestone)) {
875
+ this.milestonesReached.add(milestone);
876
+ this.track('scroll_depth', `Scrolled ${milestone}%`, {
877
+ depth: milestone,
878
+ maxDepth: this.maxScrollDepth,
879
+ timeToReach: Date.now() - this.pageLoadTime,
880
+ });
881
+ }
882
+ }
883
+ }
884
+ }
885
+
886
+ /**
887
+ * MorrisB Tracking SDK - Form Tracking Plugin
888
+ * @version 3.0.0
889
+ */
890
+ /**
891
+ * Form Tracking Plugin - Auto-tracks form views, interactions, and submissions
892
+ */
893
+ class FormsPlugin extends BasePlugin {
894
+ constructor() {
895
+ super(...arguments);
896
+ this.name = 'forms';
897
+ this.trackedForms = new WeakSet();
898
+ this.formInteractions = new Set();
899
+ this.observer = null;
900
+ }
901
+ init(tracker) {
902
+ super.init(tracker);
903
+ if (typeof document === 'undefined')
904
+ return;
905
+ // Track existing forms
906
+ this.trackAllForms();
907
+ // Watch for dynamically added forms
908
+ if (typeof MutationObserver !== 'undefined') {
909
+ this.observer = new MutationObserver(() => this.trackAllForms());
910
+ this.observer.observe(document.body, { childList: true, subtree: true });
911
+ }
912
+ }
913
+ destroy() {
914
+ if (this.observer) {
915
+ this.observer.disconnect();
916
+ this.observer = null;
917
+ }
918
+ super.destroy();
919
+ }
920
+ trackAllForms() {
921
+ document.querySelectorAll('form').forEach((form) => {
922
+ this.setupFormTracking(form);
923
+ });
924
+ }
925
+ setupFormTracking(form) {
926
+ if (this.trackedForms.has(form))
927
+ return;
928
+ this.trackedForms.add(form);
929
+ const formId = form.id || form.name || `form-${Math.random().toString(36).substr(2, 9)}`;
930
+ // Track form view
931
+ this.track('form_view', 'Form Viewed', {
932
+ formId,
933
+ action: form.action,
934
+ method: form.method,
935
+ fieldCount: form.elements.length,
936
+ });
937
+ // Track field interactions
938
+ Array.from(form.elements).forEach((field) => {
939
+ if (field instanceof HTMLInputElement ||
940
+ field instanceof HTMLSelectElement ||
941
+ field instanceof HTMLTextAreaElement) {
942
+ if (!field.name || field.type === 'submit' || field.type === 'button')
943
+ return;
944
+ ['focus', 'blur', 'change'].forEach((eventType) => {
945
+ field.addEventListener(eventType, () => {
946
+ const key = `${formId}-${field.name}-${eventType}`;
947
+ if (!this.formInteractions.has(key)) {
948
+ this.formInteractions.add(key);
949
+ this.track('form_interaction', 'Form Field Interaction', {
950
+ formId,
951
+ fieldName: field.name,
952
+ fieldType: field.type,
953
+ interactionType: eventType,
954
+ });
955
+ }
956
+ });
957
+ });
958
+ }
959
+ });
960
+ // Track form submission
961
+ form.addEventListener('submit', () => {
962
+ this.track('form_submit', 'Form Submitted', {
963
+ formId,
964
+ action: form.action,
965
+ method: form.method,
966
+ });
967
+ // Auto-identify if email field found
968
+ this.autoIdentify(form);
969
+ });
970
+ }
971
+ autoIdentify(form) {
972
+ const emailField = form.querySelector('input[type="email"], input[name*="email"]');
973
+ if (!emailField?.value || !this.tracker)
974
+ return;
975
+ const email = emailField.value;
976
+ const traits = {};
977
+ // Capture common fields
978
+ const firstNameField = form.querySelector('[name*="first"], [name*="fname"]');
979
+ const lastNameField = form.querySelector('[name*="last"], [name*="lname"]');
980
+ const companyField = form.querySelector('[name*="company"], [name*="organization"]');
981
+ const phoneField = form.querySelector('[type="tel"], [name*="phone"]');
982
+ if (firstNameField?.value)
983
+ traits.firstName = firstNameField.value;
984
+ if (lastNameField?.value)
985
+ traits.lastName = lastNameField.value;
986
+ if (companyField?.value)
987
+ traits.company = companyField.value;
988
+ if (phoneField?.value)
989
+ traits.phone = phoneField.value;
990
+ this.tracker.identify(email, traits);
991
+ }
992
+ }
993
+
994
+ /**
995
+ * MorrisB Tracking SDK - Click Tracking Plugin
996
+ * @version 3.0.0
997
+ */
998
+ /**
999
+ * Click Tracking Plugin - Tracks button and CTA clicks
1000
+ */
1001
+ class ClicksPlugin extends BasePlugin {
1002
+ constructor() {
1003
+ super(...arguments);
1004
+ this.name = 'clicks';
1005
+ this.boundHandler = null;
1006
+ }
1007
+ init(tracker) {
1008
+ super.init(tracker);
1009
+ if (typeof document !== 'undefined') {
1010
+ this.boundHandler = this.handleClick.bind(this);
1011
+ document.addEventListener('click', this.boundHandler, true);
1012
+ }
1013
+ }
1014
+ destroy() {
1015
+ if (this.boundHandler && typeof document !== 'undefined') {
1016
+ document.removeEventListener('click', this.boundHandler, true);
1017
+ }
1018
+ super.destroy();
1019
+ }
1020
+ handleClick(e) {
1021
+ const target = e.target;
1022
+ if (!target || !isTrackableClickElement(target))
1023
+ return;
1024
+ const buttonText = getElementText(target, 100);
1025
+ const elementInfo = getElementInfo(target);
1026
+ this.track('button_click', 'Button Clicked', {
1027
+ buttonText,
1028
+ elementType: target.tagName.toLowerCase(),
1029
+ elementId: elementInfo.id,
1030
+ elementClass: elementInfo.className,
1031
+ href: target.href || undefined,
1032
+ });
1033
+ }
1034
+ }
1035
+
1036
+ /**
1037
+ * MorrisB Tracking SDK - Engagement Plugin
1038
+ * @version 3.0.0
1039
+ */
1040
+ /**
1041
+ * Engagement Plugin - Tracks user engagement and time on page
1042
+ */
1043
+ class EngagementPlugin extends BasePlugin {
1044
+ constructor() {
1045
+ super(...arguments);
1046
+ this.name = 'engagement';
1047
+ this.pageLoadTime = 0;
1048
+ this.engagementStartTime = 0;
1049
+ this.isEngaged = false;
1050
+ this.engagementTimeout = null;
1051
+ this.boundMarkEngaged = null;
1052
+ this.boundTrackTimeOnPage = null;
1053
+ }
1054
+ init(tracker) {
1055
+ super.init(tracker);
1056
+ this.pageLoadTime = Date.now();
1057
+ this.engagementStartTime = Date.now();
1058
+ if (typeof document === 'undefined' || typeof window === 'undefined')
1059
+ return;
1060
+ // Setup engagement detection
1061
+ this.boundMarkEngaged = this.markEngaged.bind(this);
1062
+ this.boundTrackTimeOnPage = this.trackTimeOnPage.bind(this);
1063
+ ['mousemove', 'keydown', 'touchstart', 'scroll'].forEach((event) => {
1064
+ document.addEventListener(event, this.boundMarkEngaged, { passive: true });
1065
+ });
1066
+ // Track time on page before unload
1067
+ window.addEventListener('beforeunload', this.boundTrackTimeOnPage);
1068
+ window.addEventListener('visibilitychange', () => {
1069
+ if (document.visibilityState === 'hidden') {
1070
+ this.trackTimeOnPage();
1071
+ }
1072
+ else {
1073
+ // Reset engagement timer when page becomes visible again
1074
+ this.engagementStartTime = Date.now();
1075
+ }
1076
+ });
1077
+ }
1078
+ destroy() {
1079
+ if (this.boundMarkEngaged && typeof document !== 'undefined') {
1080
+ ['mousemove', 'keydown', 'touchstart', 'scroll'].forEach((event) => {
1081
+ document.removeEventListener(event, this.boundMarkEngaged);
1082
+ });
1083
+ }
1084
+ if (this.boundTrackTimeOnPage && typeof window !== 'undefined') {
1085
+ window.removeEventListener('beforeunload', this.boundTrackTimeOnPage);
1086
+ }
1087
+ if (this.engagementTimeout) {
1088
+ clearTimeout(this.engagementTimeout);
1089
+ }
1090
+ super.destroy();
1091
+ }
1092
+ markEngaged() {
1093
+ if (!this.isEngaged) {
1094
+ this.isEngaged = true;
1095
+ this.track('engagement', 'User Engaged', {
1096
+ timeToEngage: Date.now() - this.pageLoadTime,
1097
+ });
1098
+ }
1099
+ // Reset engagement timeout
1100
+ if (this.engagementTimeout) {
1101
+ clearTimeout(this.engagementTimeout);
1102
+ }
1103
+ this.engagementTimeout = setTimeout(() => {
1104
+ this.isEngaged = false;
1105
+ }, 30000); // 30 seconds of inactivity
1106
+ }
1107
+ trackTimeOnPage() {
1108
+ const timeSpent = Math.floor((Date.now() - this.engagementStartTime) / 1000);
1109
+ if (timeSpent > 0) {
1110
+ this.track('time_on_page', 'Time Spent', {
1111
+ seconds: timeSpent,
1112
+ engaged: this.isEngaged,
1113
+ });
1114
+ }
1115
+ }
1116
+ }
1117
+
1118
+ /**
1119
+ * MorrisB Tracking SDK - Downloads Plugin
1120
+ * @version 3.0.0
1121
+ */
1122
+ /**
1123
+ * Downloads Plugin - Tracks file downloads
1124
+ */
1125
+ class DownloadsPlugin extends BasePlugin {
1126
+ constructor() {
1127
+ super(...arguments);
1128
+ this.name = 'downloads';
1129
+ this.trackedDownloads = new Set();
1130
+ this.boundHandler = null;
1131
+ }
1132
+ init(tracker) {
1133
+ super.init(tracker);
1134
+ if (typeof document !== 'undefined') {
1135
+ this.boundHandler = this.handleClick.bind(this);
1136
+ document.addEventListener('click', this.boundHandler, true);
1137
+ }
1138
+ }
1139
+ destroy() {
1140
+ if (this.boundHandler && typeof document !== 'undefined') {
1141
+ document.removeEventListener('click', this.boundHandler, true);
1142
+ }
1143
+ super.destroy();
1144
+ }
1145
+ handleClick(e) {
1146
+ const link = e.target.closest('a');
1147
+ if (!link || !link.href)
1148
+ return;
1149
+ const url = link.href;
1150
+ // Check if it's a download link
1151
+ if (!isDownloadUrl(url))
1152
+ return;
1153
+ // Avoid tracking the same download multiple times
1154
+ if (this.trackedDownloads.has(url))
1155
+ return;
1156
+ this.trackedDownloads.add(url);
1157
+ this.track('download', 'File Download', {
1158
+ url,
1159
+ filename: getFilenameFromUrl(url),
1160
+ fileType: getFileExtension(url),
1161
+ linkText: getElementText(link, 100),
1162
+ });
1163
+ }
1164
+ }
1165
+
1166
+ /**
1167
+ * MorrisB Tracking SDK - Exit Intent Plugin
1168
+ * @version 3.0.0
1169
+ */
1170
+ /**
1171
+ * Exit Intent Plugin - Detects when user intends to leave the page
1172
+ */
1173
+ class ExitIntentPlugin extends BasePlugin {
1174
+ constructor() {
1175
+ super(...arguments);
1176
+ this.name = 'exitIntent';
1177
+ this.exitIntentShown = false;
1178
+ this.pageLoadTime = 0;
1179
+ this.boundHandler = null;
1180
+ }
1181
+ init(tracker) {
1182
+ super.init(tracker);
1183
+ this.pageLoadTime = Date.now();
1184
+ // Skip on mobile (no mouse events)
1185
+ if (isMobile())
1186
+ return;
1187
+ if (typeof document !== 'undefined') {
1188
+ this.boundHandler = this.handleMouseLeave.bind(this);
1189
+ document.addEventListener('mouseleave', this.boundHandler);
1190
+ }
1191
+ }
1192
+ destroy() {
1193
+ if (this.boundHandler && typeof document !== 'undefined') {
1194
+ document.removeEventListener('mouseleave', this.boundHandler);
1195
+ }
1196
+ super.destroy();
1197
+ }
1198
+ handleMouseLeave(e) {
1199
+ // Only trigger when mouse leaves from the top of the page
1200
+ if (e.clientY > 0 || this.exitIntentShown)
1201
+ return;
1202
+ this.exitIntentShown = true;
1203
+ this.track('exit_intent', 'Exit Intent Detected', {
1204
+ timeOnPage: Date.now() - this.pageLoadTime,
1205
+ });
1206
+ }
1207
+ }
1208
+
1209
+ /**
1210
+ * MorrisB Tracking SDK - Error Tracking Plugin
1211
+ * @version 3.0.0
1212
+ */
1213
+ /**
1214
+ * Error Tracking Plugin - Tracks JavaScript errors
1215
+ */
1216
+ class ErrorsPlugin extends BasePlugin {
1217
+ constructor() {
1218
+ super(...arguments);
1219
+ this.name = 'errors';
1220
+ this.boundErrorHandler = null;
1221
+ this.boundRejectionHandler = null;
1222
+ }
1223
+ init(tracker) {
1224
+ super.init(tracker);
1225
+ if (typeof window !== 'undefined') {
1226
+ this.boundErrorHandler = this.handleError.bind(this);
1227
+ this.boundRejectionHandler = this.handleRejection.bind(this);
1228
+ window.addEventListener('error', this.boundErrorHandler);
1229
+ window.addEventListener('unhandledrejection', this.boundRejectionHandler);
1230
+ }
1231
+ }
1232
+ destroy() {
1233
+ if (typeof window !== 'undefined') {
1234
+ if (this.boundErrorHandler) {
1235
+ window.removeEventListener('error', this.boundErrorHandler);
1236
+ }
1237
+ if (this.boundRejectionHandler) {
1238
+ window.removeEventListener('unhandledrejection', this.boundRejectionHandler);
1239
+ }
1240
+ }
1241
+ super.destroy();
1242
+ }
1243
+ handleError(e) {
1244
+ this.track('error', 'JavaScript Error', {
1245
+ message: e.message,
1246
+ filename: e.filename,
1247
+ line: e.lineno,
1248
+ column: e.colno,
1249
+ stack: e.error?.stack?.substring(0, 500),
1250
+ });
1251
+ }
1252
+ handleRejection(e) {
1253
+ this.track('error', 'Unhandled Promise Rejection', {
1254
+ reason: String(e.reason).substring(0, 200),
1255
+ });
1256
+ }
1257
+ }
1258
+
1259
+ /**
1260
+ * MorrisB Tracking SDK - Performance Plugin
1261
+ * @version 3.0.0
1262
+ */
1263
+ /**
1264
+ * Performance Plugin - Tracks page performance and Web Vitals
1265
+ */
1266
+ class PerformancePlugin extends BasePlugin {
1267
+ constructor() {
1268
+ super(...arguments);
1269
+ this.name = 'performance';
1270
+ }
1271
+ init(tracker) {
1272
+ super.init(tracker);
1273
+ if (typeof window !== 'undefined') {
1274
+ // Track performance after page load
1275
+ window.addEventListener('load', () => {
1276
+ // Delay to ensure all metrics are available
1277
+ setTimeout(() => this.trackPerformance(), 100);
1278
+ });
1279
+ }
1280
+ }
1281
+ trackPerformance() {
1282
+ if (typeof performance === 'undefined')
1283
+ return;
1284
+ // Use Navigation Timing API
1285
+ const timing = performance.timing;
1286
+ if (!timing)
1287
+ return;
1288
+ const loadTime = timing.loadEventEnd - timing.navigationStart;
1289
+ const domReady = timing.domContentLoadedEventEnd - timing.navigationStart;
1290
+ const ttfb = timing.responseStart - timing.navigationStart;
1291
+ const domInteractive = timing.domInteractive - timing.navigationStart;
1292
+ this.track('performance', 'Page Performance', {
1293
+ loadTime,
1294
+ domReady,
1295
+ ttfb, // Time to First Byte
1296
+ domInteractive,
1297
+ });
1298
+ // Track Web Vitals if available
1299
+ this.trackWebVitals();
1300
+ }
1301
+ trackWebVitals() {
1302
+ // LCP (Largest Contentful Paint)
1303
+ if ('PerformanceObserver' in window) {
1304
+ try {
1305
+ const lcpObserver = new PerformanceObserver((entryList) => {
1306
+ const entries = entryList.getEntries();
1307
+ const lastEntry = entries[entries.length - 1];
1308
+ if (lastEntry) {
1309
+ this.track('performance', 'Web Vital - LCP', {
1310
+ metric: 'LCP',
1311
+ value: Math.round(lastEntry.startTime),
1312
+ });
1313
+ }
1314
+ });
1315
+ lcpObserver.observe({ type: 'largest-contentful-paint', buffered: true });
1316
+ }
1317
+ catch {
1318
+ // LCP not supported
1319
+ }
1320
+ // FID (First Input Delay)
1321
+ try {
1322
+ const fidObserver = new PerformanceObserver((entryList) => {
1323
+ const entries = entryList.getEntries();
1324
+ const firstEntry = entries[0];
1325
+ if (firstEntry) {
1326
+ this.track('performance', 'Web Vital - FID', {
1327
+ metric: 'FID',
1328
+ value: Math.round(firstEntry.processingStart - firstEntry.startTime),
1329
+ });
1330
+ }
1331
+ });
1332
+ fidObserver.observe({ type: 'first-input', buffered: true });
1333
+ }
1334
+ catch {
1335
+ // FID not supported
1336
+ }
1337
+ // CLS (Cumulative Layout Shift)
1338
+ try {
1339
+ let clsValue = 0;
1340
+ const clsObserver = new PerformanceObserver((entryList) => {
1341
+ const entries = entryList.getEntries();
1342
+ entries.forEach((entry) => {
1343
+ if (!entry.hadRecentInput) {
1344
+ clsValue += entry.value || 0;
1345
+ }
1346
+ });
1347
+ });
1348
+ clsObserver.observe({ type: 'layout-shift', buffered: true });
1349
+ // Report CLS after page is hidden
1350
+ window.addEventListener('visibilitychange', () => {
1351
+ if (document.visibilityState === 'hidden' && clsValue > 0) {
1352
+ this.track('performance', 'Web Vital - CLS', {
1353
+ metric: 'CLS',
1354
+ value: Math.round(clsValue * 1000) / 1000,
1355
+ });
1356
+ }
1357
+ }, { once: true });
1358
+ }
1359
+ catch {
1360
+ // CLS not supported
1361
+ }
1362
+ }
1363
+ }
1364
+ }
1365
+
1366
+ /**
1367
+ * MorrisB Tracking SDK - Plugins Index
1368
+ * @version 3.0.0
1369
+ */
1370
+ /**
1371
+ * Get plugin instance by name
1372
+ */
1373
+ function getPlugin(name) {
1374
+ switch (name) {
1375
+ case 'pageView':
1376
+ return new PageViewPlugin();
1377
+ case 'scroll':
1378
+ return new ScrollPlugin();
1379
+ case 'forms':
1380
+ return new FormsPlugin();
1381
+ case 'clicks':
1382
+ return new ClicksPlugin();
1383
+ case 'engagement':
1384
+ return new EngagementPlugin();
1385
+ case 'downloads':
1386
+ return new DownloadsPlugin();
1387
+ case 'exitIntent':
1388
+ return new ExitIntentPlugin();
1389
+ case 'errors':
1390
+ return new ErrorsPlugin();
1391
+ case 'performance':
1392
+ return new PerformancePlugin();
1393
+ default:
1394
+ throw new Error(`Unknown plugin: ${name}`);
1395
+ }
1396
+ }
1397
+
1398
+ /**
1399
+ * MorrisB Tracking SDK - Main Tracker Class
1400
+ * @version 3.0.0
1401
+ */
1402
+ /**
1403
+ * Main MorrisB Tracker Class
1404
+ */
1405
+ class Tracker {
1406
+ constructor(workspaceId, userConfig = {}) {
1407
+ this.plugins = [];
1408
+ this.isInitialized = false;
1409
+ if (!workspaceId) {
1410
+ throw new Error('[Clianta] Workspace ID is required');
1411
+ }
1412
+ this.workspaceId = workspaceId;
1413
+ this.config = mergeConfig(userConfig);
1414
+ // Setup debug mode
1415
+ logger.enabled = this.config.debug;
1416
+ logger.info(`Initializing SDK v${SDK_VERSION}`, { workspaceId });
1417
+ // Initialize transport and queue
1418
+ this.transport = new Transport({ apiEndpoint: this.config.apiEndpoint });
1419
+ this.queue = new EventQueue(this.transport, {
1420
+ batchSize: this.config.batchSize,
1421
+ flushInterval: this.config.flushInterval,
1422
+ });
1423
+ // Get or create visitor and session IDs
1424
+ this.visitorId = getOrCreateVisitorId(this.config.useCookies);
1425
+ this.sessionId = getOrCreateSessionId(this.config.sessionTimeout);
1426
+ logger.debug('IDs created', { visitorId: this.visitorId, sessionId: this.sessionId });
1427
+ // Initialize plugins
1428
+ this.initPlugins();
1429
+ this.isInitialized = true;
1430
+ logger.info('SDK initialized successfully');
1431
+ }
1432
+ /**
1433
+ * Initialize enabled plugins
1434
+ */
1435
+ initPlugins() {
1436
+ const pluginsToLoad = this.config.plugins;
1437
+ // Skip pageView plugin if autoPageView is disabled
1438
+ const filteredPlugins = this.config.autoPageView
1439
+ ? pluginsToLoad
1440
+ : pluginsToLoad.filter((p) => p !== 'pageView');
1441
+ for (const pluginName of filteredPlugins) {
1442
+ try {
1443
+ const plugin = getPlugin(pluginName);
1444
+ plugin.init(this);
1445
+ this.plugins.push(plugin);
1446
+ logger.debug(`Plugin loaded: ${pluginName}`);
1447
+ }
1448
+ catch (error) {
1449
+ logger.error(`Failed to load plugin: ${pluginName}`, error);
1450
+ }
1451
+ }
1452
+ }
1453
+ /**
1454
+ * Track a custom event
1455
+ */
1456
+ track(eventType, eventName, properties = {}) {
1457
+ if (!this.isInitialized) {
1458
+ logger.warn('SDK not initialized, event dropped');
1459
+ return;
1460
+ }
1461
+ const event = {
1462
+ workspaceId: this.workspaceId,
1463
+ visitorId: this.visitorId,
1464
+ sessionId: this.sessionId,
1465
+ eventType: eventType,
1466
+ eventName,
1467
+ url: typeof window !== 'undefined' ? window.location.href : '',
1468
+ referrer: typeof document !== 'undefined' ? document.referrer || undefined : undefined,
1469
+ properties,
1470
+ device: getDeviceInfo(),
1471
+ utm: getUTMParams(),
1472
+ timestamp: new Date().toISOString(),
1473
+ sdkVersion: SDK_VERSION,
1474
+ };
1475
+ this.queue.push(event);
1476
+ logger.debug('Event tracked:', eventName, properties);
1477
+ }
1478
+ /**
1479
+ * Track a page view
1480
+ */
1481
+ page(name, properties = {}) {
1482
+ const pageName = name || (typeof document !== 'undefined' ? document.title : 'Page View');
1483
+ this.track('page_view', pageName, {
1484
+ ...properties,
1485
+ path: typeof window !== 'undefined' ? window.location.pathname : '',
1486
+ });
1487
+ }
1488
+ /**
1489
+ * Identify a visitor
1490
+ */
1491
+ async identify(email, traits = {}) {
1492
+ if (!email) {
1493
+ logger.warn('Email is required for identification');
1494
+ return;
1495
+ }
1496
+ logger.info('Identifying visitor:', email);
1497
+ const result = await this.transport.sendIdentify({
1498
+ workspaceId: this.workspaceId,
1499
+ visitorId: this.visitorId,
1500
+ email,
1501
+ properties: traits,
1502
+ });
1503
+ if (result.success) {
1504
+ logger.info('Visitor identified successfully');
1505
+ }
1506
+ else {
1507
+ logger.error('Failed to identify visitor:', result.error);
1508
+ }
1509
+ }
1510
+ /**
1511
+ * Update consent state
1512
+ */
1513
+ consent(state) {
1514
+ logger.info('Consent updated:', state);
1515
+ // TODO: Implement consent management
1516
+ // - Store consent state
1517
+ // - Enable/disable tracking based on consent
1518
+ // - Notify plugins
1519
+ }
1520
+ /**
1521
+ * Toggle debug mode
1522
+ */
1523
+ debug(enabled) {
1524
+ logger.enabled = enabled;
1525
+ logger.info(`Debug mode ${enabled ? 'enabled' : 'disabled'}`);
1526
+ }
1527
+ /**
1528
+ * Get visitor ID
1529
+ */
1530
+ getVisitorId() {
1531
+ return this.visitorId;
1532
+ }
1533
+ /**
1534
+ * Get session ID
1535
+ */
1536
+ getSessionId() {
1537
+ return this.sessionId;
1538
+ }
1539
+ /**
1540
+ * Get workspace ID
1541
+ */
1542
+ getWorkspaceId() {
1543
+ return this.workspaceId;
1544
+ }
1545
+ /**
1546
+ * Get current configuration
1547
+ */
1548
+ getConfig() {
1549
+ return { ...this.config };
1550
+ }
1551
+ /**
1552
+ * Force flush event queue
1553
+ */
1554
+ async flush() {
1555
+ await this.queue.flush();
1556
+ }
1557
+ /**
1558
+ * Reset visitor and session (for logout)
1559
+ */
1560
+ reset() {
1561
+ logger.info('Resetting visitor data');
1562
+ resetIds(this.config.useCookies);
1563
+ this.visitorId = getOrCreateVisitorId(this.config.useCookies);
1564
+ this.sessionId = getOrCreateSessionId(this.config.sessionTimeout);
1565
+ this.queue.clear();
1566
+ }
1567
+ /**
1568
+ * Destroy tracker and cleanup
1569
+ */
1570
+ destroy() {
1571
+ logger.info('Destroying tracker');
1572
+ // Flush any remaining events
1573
+ this.queue.flush();
1574
+ // Destroy plugins
1575
+ for (const plugin of this.plugins) {
1576
+ if (plugin.destroy) {
1577
+ plugin.destroy();
1578
+ }
1579
+ }
1580
+ this.plugins = [];
1581
+ // Destroy queue
1582
+ this.queue.destroy();
1583
+ this.isInitialized = false;
1584
+ }
1585
+ }
1586
+
1587
+ /**
1588
+ * Clianta SDK - CRM API Client
1589
+ * @version 1.0.0
1590
+ */
1591
+ /**
1592
+ * CRM API Client for managing contacts and opportunities
1593
+ */
1594
+ class CRMClient {
1595
+ constructor(apiEndpoint, workspaceId, authToken) {
1596
+ this.apiEndpoint = apiEndpoint;
1597
+ this.workspaceId = workspaceId;
1598
+ this.authToken = authToken;
1599
+ }
1600
+ /**
1601
+ * Set authentication token for API requests
1602
+ */
1603
+ setAuthToken(token) {
1604
+ this.authToken = token;
1605
+ }
1606
+ /**
1607
+ * Make authenticated API request
1608
+ */
1609
+ async request(endpoint, options = {}) {
1610
+ const url = `${this.apiEndpoint}${endpoint}`;
1611
+ const headers = {
1612
+ 'Content-Type': 'application/json',
1613
+ ...(options.headers || {}),
1614
+ };
1615
+ if (this.authToken) {
1616
+ headers['Authorization'] = `Bearer ${this.authToken}`;
1617
+ }
1618
+ try {
1619
+ const response = await fetch(url, {
1620
+ ...options,
1621
+ headers,
1622
+ });
1623
+ const data = await response.json();
1624
+ if (!response.ok) {
1625
+ return {
1626
+ success: false,
1627
+ error: data.message || 'Request failed',
1628
+ status: response.status,
1629
+ };
1630
+ }
1631
+ return {
1632
+ success: true,
1633
+ data: data.data || data,
1634
+ status: response.status,
1635
+ };
1636
+ }
1637
+ catch (error) {
1638
+ return {
1639
+ success: false,
1640
+ error: error instanceof Error ? error.message : 'Network error',
1641
+ status: 0,
1642
+ };
1643
+ }
1644
+ }
1645
+ // ============================================
1646
+ // CONTACTS API
1647
+ // ============================================
1648
+ /**
1649
+ * Get all contacts with pagination
1650
+ */
1651
+ async getContacts(params) {
1652
+ const queryParams = new URLSearchParams();
1653
+ if (params?.page)
1654
+ queryParams.set('page', params.page.toString());
1655
+ if (params?.limit)
1656
+ queryParams.set('limit', params.limit.toString());
1657
+ if (params?.search)
1658
+ queryParams.set('search', params.search);
1659
+ if (params?.status)
1660
+ queryParams.set('status', params.status);
1661
+ const query = queryParams.toString();
1662
+ const endpoint = `/api/workspaces/${this.workspaceId}/contacts${query ? `?${query}` : ''}`;
1663
+ return this.request(endpoint);
1664
+ }
1665
+ /**
1666
+ * Get a single contact by ID
1667
+ */
1668
+ async getContact(contactId) {
1669
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`);
1670
+ }
1671
+ /**
1672
+ * Create a new contact
1673
+ */
1674
+ async createContact(contact) {
1675
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts`, {
1676
+ method: 'POST',
1677
+ body: JSON.stringify(contact),
1678
+ });
1679
+ }
1680
+ /**
1681
+ * Update an existing contact
1682
+ */
1683
+ async updateContact(contactId, updates) {
1684
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
1685
+ method: 'PUT',
1686
+ body: JSON.stringify(updates),
1687
+ });
1688
+ }
1689
+ /**
1690
+ * Delete a contact
1691
+ */
1692
+ async deleteContact(contactId) {
1693
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
1694
+ method: 'DELETE',
1695
+ });
1696
+ }
1697
+ // ============================================
1698
+ // OPPORTUNITIES API
1699
+ // ============================================
1700
+ /**
1701
+ * Get all opportunities with pagination
1702
+ */
1703
+ async getOpportunities(params) {
1704
+ const queryParams = new URLSearchParams();
1705
+ if (params?.page)
1706
+ queryParams.set('page', params.page.toString());
1707
+ if (params?.limit)
1708
+ queryParams.set('limit', params.limit.toString());
1709
+ if (params?.pipelineId)
1710
+ queryParams.set('pipelineId', params.pipelineId);
1711
+ if (params?.stageId)
1712
+ queryParams.set('stageId', params.stageId);
1713
+ const query = queryParams.toString();
1714
+ const endpoint = `/api/workspaces/${this.workspaceId}/opportunities${query ? `?${query}` : ''}`;
1715
+ return this.request(endpoint);
1716
+ }
1717
+ /**
1718
+ * Get a single opportunity by ID
1719
+ */
1720
+ async getOpportunity(opportunityId) {
1721
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`);
1722
+ }
1723
+ /**
1724
+ * Create a new opportunity
1725
+ */
1726
+ async createOpportunity(opportunity) {
1727
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities`, {
1728
+ method: 'POST',
1729
+ body: JSON.stringify(opportunity),
1730
+ });
1731
+ }
1732
+ /**
1733
+ * Update an existing opportunity
1734
+ */
1735
+ async updateOpportunity(opportunityId, updates) {
1736
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`, {
1737
+ method: 'PUT',
1738
+ body: JSON.stringify(updates),
1739
+ });
1740
+ }
1741
+ /**
1742
+ * Delete an opportunity
1743
+ */
1744
+ async deleteOpportunity(opportunityId) {
1745
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`, {
1746
+ method: 'DELETE',
1747
+ });
1748
+ }
1749
+ /**
1750
+ * Move opportunity to a different stage
1751
+ */
1752
+ async moveOpportunity(opportunityId, stageId) {
1753
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}/move`, {
1754
+ method: 'POST',
1755
+ body: JSON.stringify({ stageId }),
1756
+ });
1757
+ }
1758
+ }
1759
+
1760
+ /**
1761
+ * Clianta SDK
1762
+ * Professional CRM and tracking SDK for lead generation
1763
+ * @version 1.0.0
1764
+ */
1765
+ // Global instance cache
1766
+ let globalInstance = null;
1767
+ /**
1768
+ * Initialize or get the Clianta tracker instance
1769
+ *
1770
+ * @example
1771
+ * // Simple initialization
1772
+ * const tracker = clianta('your-workspace-id');
1773
+ *
1774
+ * @example
1775
+ * // With configuration
1776
+ * const tracker = clianta('your-workspace-id', {
1777
+ * debug: true,
1778
+ * plugins: ['pageView', 'forms', 'scroll'],
1779
+ * });
1780
+ */
1781
+ function clianta(workspaceId, config) {
1782
+ // Return existing instance if same workspace
1783
+ if (globalInstance && globalInstance.getWorkspaceId() === workspaceId) {
1784
+ return globalInstance;
1785
+ }
1786
+ // Destroy existing instance if workspace changed
1787
+ if (globalInstance) {
1788
+ globalInstance.destroy();
1789
+ }
1790
+ // Create new instance
1791
+ globalInstance = new Tracker(workspaceId, config);
1792
+ return globalInstance;
1793
+ }
1794
+ // Attach to window for <script> usage
1795
+ if (typeof window !== 'undefined') {
1796
+ window.clianta = clianta;
1797
+ window.Clianta = {
1798
+ clianta,
1799
+ Tracker,
1800
+ CRMClient,
1801
+ };
1802
+ }
1803
+
1804
+ exports.CRMClient = CRMClient;
1805
+ exports.SDK_VERSION = SDK_VERSION;
1806
+ exports.Tracker = Tracker;
1807
+ exports.clianta = clianta;
1808
+ exports.default = clianta;
1809
+ //# sourceMappingURL=clianta.cjs.js.map