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