@clianta/sdk 1.2.0 → 1.3.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,3893 @@
1
+ /*!
2
+ * Clianta SDK v1.3.0
3
+ * (c) 2026 Clianta
4
+ * Released under the MIT License.
5
+ */
6
+ import { ref, inject } from 'vue';
7
+
8
+ /**
9
+ * Clianta SDK - Configuration
10
+ * @see SDK_VERSION in core/config.ts
11
+ */
12
+ /** SDK Version */
13
+ const SDK_VERSION = '1.3.0';
14
+ /** Default API endpoint based on environment */
15
+ const getDefaultApiEndpoint = () => {
16
+ if (typeof window === 'undefined')
17
+ return 'https://api.clianta.online';
18
+ const hostname = window.location.hostname;
19
+ if (hostname.includes('localhost') || hostname.includes('127.0.0.1')) {
20
+ return 'http://localhost:5000';
21
+ }
22
+ return 'https://api.clianta.online';
23
+ };
24
+ /** Core plugins enabled by default */
25
+ const DEFAULT_PLUGINS = [
26
+ 'pageView',
27
+ 'forms',
28
+ 'scroll',
29
+ 'clicks',
30
+ 'engagement',
31
+ 'downloads',
32
+ 'exitIntent',
33
+ ];
34
+ /** Default configuration values */
35
+ const DEFAULT_CONFIG = {
36
+ projectId: '',
37
+ apiEndpoint: getDefaultApiEndpoint(),
38
+ authToken: '',
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
+ anonymousMode: false,
50
+ },
51
+ cookieDomain: '',
52
+ useCookies: false,
53
+ cookielessMode: false,
54
+ };
55
+ /** Storage keys */
56
+ const STORAGE_KEYS = {
57
+ VISITOR_ID: 'mb_vid',
58
+ SESSION_ID: 'mb_sid',
59
+ SESSION_TIMESTAMP: 'mb_st',
60
+ CONSENT: 'mb_consent',
61
+ EVENT_QUEUE: 'mb_queue',
62
+ };
63
+ /** Scroll depth milestones to track */
64
+ const SCROLL_MILESTONES = [25, 50, 75, 100];
65
+ /** File extensions to track as downloads */
66
+ const DOWNLOAD_EXTENSIONS = [
67
+ '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx',
68
+ '.zip', '.rar', '.tar', '.gz', '.7z',
69
+ '.csv', '.txt', '.json', '.xml',
70
+ '.mp3', '.mp4', '.wav', '.avi', '.mov',
71
+ ];
72
+ /**
73
+ * Merge user config with defaults
74
+ */
75
+ function mergeConfig(userConfig = {}) {
76
+ return {
77
+ ...DEFAULT_CONFIG,
78
+ ...userConfig,
79
+ consent: {
80
+ ...DEFAULT_CONFIG.consent,
81
+ ...userConfig.consent,
82
+ },
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Clianta SDK - Debug Logger
88
+ * @see SDK_VERSION in core/config.ts
89
+ */
90
+ const LOG_PREFIX = '[Clianta]';
91
+ const LOG_STYLES = {
92
+ debug: 'color: #6b7280; font-weight: normal;',
93
+ info: 'color: #3b82f6; font-weight: normal;',
94
+ warn: 'color: #f59e0b; font-weight: bold;',
95
+ error: 'color: #ef4444; font-weight: bold;',
96
+ };
97
+ const LOG_LEVELS = {
98
+ debug: 0,
99
+ info: 1,
100
+ warn: 2,
101
+ error: 3,
102
+ };
103
+ /**
104
+ * Create a logger instance
105
+ */
106
+ function createLogger(enabled = false) {
107
+ let currentLevel = 'debug';
108
+ let isEnabled = enabled;
109
+ const shouldLog = (level) => {
110
+ if (!isEnabled)
111
+ return false;
112
+ return LOG_LEVELS[level] >= LOG_LEVELS[currentLevel];
113
+ };
114
+ const formatArgs = (level, args) => {
115
+ if (typeof console !== 'undefined' && typeof window !== 'undefined') {
116
+ // Browser with styled console
117
+ return [`%c${LOG_PREFIX}`, LOG_STYLES[level], ...args];
118
+ }
119
+ // Node.js or basic console
120
+ return [`${LOG_PREFIX} [${level.toUpperCase()}]`, ...args];
121
+ };
122
+ return {
123
+ get enabled() {
124
+ return isEnabled;
125
+ },
126
+ set enabled(value) {
127
+ isEnabled = value;
128
+ },
129
+ debug(...args) {
130
+ if (shouldLog('debug') && typeof console !== 'undefined') {
131
+ console.log(...formatArgs('debug', args));
132
+ }
133
+ },
134
+ info(...args) {
135
+ if (shouldLog('info') && typeof console !== 'undefined') {
136
+ console.info(...formatArgs('info', args));
137
+ }
138
+ },
139
+ warn(...args) {
140
+ if (shouldLog('warn') && typeof console !== 'undefined') {
141
+ console.warn(...formatArgs('warn', args));
142
+ }
143
+ },
144
+ error(...args) {
145
+ if (shouldLog('error') && typeof console !== 'undefined') {
146
+ console.error(...formatArgs('error', args));
147
+ }
148
+ },
149
+ setLevel(level) {
150
+ currentLevel = level;
151
+ },
152
+ };
153
+ }
154
+ /** Global logger instance */
155
+ const logger = createLogger(false);
156
+
157
+ /**
158
+ * Clianta SDK - Transport Layer
159
+ * Handles sending events to the backend with retry logic
160
+ * @see SDK_VERSION in core/config.ts
161
+ */
162
+ const DEFAULT_TIMEOUT = 10000; // 10 seconds
163
+ const DEFAULT_MAX_RETRIES = 3;
164
+ const DEFAULT_RETRY_DELAY = 1000; // 1 second
165
+ /**
166
+ * Transport class for sending data to the backend
167
+ */
168
+ class Transport {
169
+ constructor(config) {
170
+ this.config = {
171
+ apiEndpoint: config.apiEndpoint,
172
+ maxRetries: config.maxRetries ?? DEFAULT_MAX_RETRIES,
173
+ retryDelay: config.retryDelay ?? DEFAULT_RETRY_DELAY,
174
+ timeout: config.timeout ?? DEFAULT_TIMEOUT,
175
+ };
176
+ }
177
+ /**
178
+ * Send events to the tracking endpoint
179
+ */
180
+ async sendEvents(events) {
181
+ const url = `${this.config.apiEndpoint}/api/public/track/event`;
182
+ const payload = JSON.stringify({ events });
183
+ return this.send(url, payload);
184
+ }
185
+ /**
186
+ * Send identify request
187
+ */
188
+ async sendIdentify(data) {
189
+ const url = `${this.config.apiEndpoint}/api/public/track/identify`;
190
+ const payload = JSON.stringify(data);
191
+ return this.send(url, payload);
192
+ }
193
+ /**
194
+ * Send events synchronously (for page unload)
195
+ * Uses navigator.sendBeacon for reliability
196
+ */
197
+ sendBeacon(events) {
198
+ if (typeof navigator === 'undefined' || !navigator.sendBeacon) {
199
+ logger.warn('sendBeacon not available, events may be lost');
200
+ return false;
201
+ }
202
+ const url = `${this.config.apiEndpoint}/api/public/track/event`;
203
+ const payload = JSON.stringify({ events });
204
+ const blob = new Blob([payload], { type: 'application/json' });
205
+ try {
206
+ const success = navigator.sendBeacon(url, blob);
207
+ if (success) {
208
+ logger.debug(`Beacon sent ${events.length} events`);
209
+ }
210
+ else {
211
+ logger.warn('sendBeacon returned false');
212
+ }
213
+ return success;
214
+ }
215
+ catch (error) {
216
+ logger.error('sendBeacon error:', error);
217
+ return false;
218
+ }
219
+ }
220
+ /**
221
+ * Internal send with retry logic
222
+ */
223
+ async send(url, payload, attempt = 1) {
224
+ try {
225
+ const response = await this.fetchWithTimeout(url, {
226
+ method: 'POST',
227
+ headers: {
228
+ 'Content-Type': 'application/json',
229
+ },
230
+ body: payload,
231
+ keepalive: true,
232
+ });
233
+ if (response.ok) {
234
+ logger.debug('Request successful:', url);
235
+ return { success: true, status: response.status };
236
+ }
237
+ // Server error - may retry
238
+ if (response.status >= 500 && attempt < this.config.maxRetries) {
239
+ logger.warn(`Server error (${response.status}), retrying...`);
240
+ await this.delay(this.config.retryDelay * attempt);
241
+ return this.send(url, payload, attempt + 1);
242
+ }
243
+ // Client error - don't retry
244
+ logger.error(`Request failed with status ${response.status}`);
245
+ return { success: false, status: response.status };
246
+ }
247
+ catch (error) {
248
+ // Network error - retry if possible
249
+ if (attempt < this.config.maxRetries) {
250
+ logger.warn(`Network error, retrying (${attempt}/${this.config.maxRetries})...`);
251
+ await this.delay(this.config.retryDelay * attempt);
252
+ return this.send(url, payload, attempt + 1);
253
+ }
254
+ logger.error('Request failed after retries:', error);
255
+ return { success: false, error: error };
256
+ }
257
+ }
258
+ /**
259
+ * Fetch with timeout
260
+ */
261
+ async fetchWithTimeout(url, options) {
262
+ const controller = new AbortController();
263
+ const timeout = setTimeout(() => controller.abort(), this.config.timeout);
264
+ try {
265
+ const response = await fetch(url, {
266
+ ...options,
267
+ signal: controller.signal,
268
+ });
269
+ return response;
270
+ }
271
+ finally {
272
+ clearTimeout(timeout);
273
+ }
274
+ }
275
+ /**
276
+ * Delay helper
277
+ */
278
+ delay(ms) {
279
+ return new Promise((resolve) => setTimeout(resolve, ms));
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Clianta SDK - Utility Functions
285
+ * @see SDK_VERSION in core/config.ts
286
+ */
287
+ // ============================================
288
+ // UUID GENERATION
289
+ // ============================================
290
+ /**
291
+ * Generate a UUID v4
292
+ */
293
+ function generateUUID() {
294
+ // Use crypto.randomUUID if available (modern browsers)
295
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
296
+ return crypto.randomUUID();
297
+ }
298
+ // Fallback to manual generation
299
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
300
+ const r = (Math.random() * 16) | 0;
301
+ const v = c === 'x' ? r : (r & 0x3) | 0x8;
302
+ return v.toString(16);
303
+ });
304
+ }
305
+ // ============================================
306
+ // STORAGE UTILITIES
307
+ // ============================================
308
+ /**
309
+ * Safely get from localStorage
310
+ */
311
+ function getLocalStorage(key) {
312
+ try {
313
+ if (typeof localStorage !== 'undefined') {
314
+ return localStorage.getItem(key);
315
+ }
316
+ }
317
+ catch {
318
+ // localStorage not available or blocked
319
+ }
320
+ return null;
321
+ }
322
+ /**
323
+ * Safely set to localStorage
324
+ */
325
+ function setLocalStorage(key, value) {
326
+ try {
327
+ if (typeof localStorage !== 'undefined') {
328
+ localStorage.setItem(key, value);
329
+ return true;
330
+ }
331
+ }
332
+ catch {
333
+ // localStorage not available or blocked
334
+ }
335
+ return false;
336
+ }
337
+ /**
338
+ * Safely get from sessionStorage
339
+ */
340
+ function getSessionStorage(key) {
341
+ try {
342
+ if (typeof sessionStorage !== 'undefined') {
343
+ return sessionStorage.getItem(key);
344
+ }
345
+ }
346
+ catch {
347
+ // sessionStorage not available or blocked
348
+ }
349
+ return null;
350
+ }
351
+ /**
352
+ * Safely set to sessionStorage
353
+ */
354
+ function setSessionStorage(key, value) {
355
+ try {
356
+ if (typeof sessionStorage !== 'undefined') {
357
+ sessionStorage.setItem(key, value);
358
+ return true;
359
+ }
360
+ }
361
+ catch {
362
+ // sessionStorage not available or blocked
363
+ }
364
+ return false;
365
+ }
366
+ /**
367
+ * Get or set a cookie
368
+ */
369
+ function cookie(name, value, days) {
370
+ if (typeof document === 'undefined')
371
+ return null;
372
+ // Get cookie
373
+ if (value === undefined) {
374
+ const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
375
+ return match ? match[2] : null;
376
+ }
377
+ // Set cookie
378
+ let expires = '';
379
+ if (days) {
380
+ const date = new Date();
381
+ date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
382
+ expires = '; expires=' + date.toUTCString();
383
+ }
384
+ document.cookie = name + '=' + value + expires + '; path=/; SameSite=Lax';
385
+ return value;
386
+ }
387
+ // ============================================
388
+ // VISITOR & SESSION MANAGEMENT
389
+ // ============================================
390
+ /**
391
+ * Get or create a persistent visitor ID
392
+ */
393
+ function getOrCreateVisitorId(useCookies = false) {
394
+ const key = STORAGE_KEYS.VISITOR_ID;
395
+ // Try to get existing ID
396
+ let visitorId = null;
397
+ if (useCookies) {
398
+ visitorId = cookie(key);
399
+ }
400
+ else {
401
+ visitorId = getLocalStorage(key);
402
+ }
403
+ // Create new ID if not found
404
+ if (!visitorId) {
405
+ visitorId = generateUUID();
406
+ if (useCookies) {
407
+ cookie(key, visitorId, 365); // 1 year
408
+ }
409
+ else {
410
+ setLocalStorage(key, visitorId);
411
+ }
412
+ }
413
+ return visitorId;
414
+ }
415
+ /**
416
+ * Get or create a session ID (expires after timeout)
417
+ */
418
+ function getOrCreateSessionId(timeout) {
419
+ const sidKey = STORAGE_KEYS.SESSION_ID;
420
+ const tsKey = STORAGE_KEYS.SESSION_TIMESTAMP;
421
+ let sessionId = getSessionStorage(sidKey);
422
+ const lastActivity = parseInt(getSessionStorage(tsKey) || '0', 10);
423
+ const now = Date.now();
424
+ // Check if session expired
425
+ if (!sessionId || now - lastActivity > timeout) {
426
+ sessionId = generateUUID();
427
+ setSessionStorage(sidKey, sessionId);
428
+ }
429
+ // Update last activity
430
+ setSessionStorage(tsKey, now.toString());
431
+ return sessionId;
432
+ }
433
+ /**
434
+ * Reset visitor and session IDs
435
+ */
436
+ function resetIds(useCookies = false) {
437
+ const visitorKey = STORAGE_KEYS.VISITOR_ID;
438
+ if (useCookies) {
439
+ cookie(visitorKey, '', -1); // Delete cookie
440
+ }
441
+ else {
442
+ try {
443
+ localStorage.removeItem(visitorKey);
444
+ }
445
+ catch {
446
+ // Ignore
447
+ }
448
+ }
449
+ try {
450
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_ID);
451
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_TIMESTAMP);
452
+ }
453
+ catch {
454
+ // Ignore
455
+ }
456
+ }
457
+ // ============================================
458
+ // URL UTILITIES
459
+ // ============================================
460
+ /**
461
+ * Extract UTM parameters from URL
462
+ */
463
+ function getUTMParams() {
464
+ if (typeof window === 'undefined')
465
+ return {};
466
+ try {
467
+ const params = new URLSearchParams(window.location.search);
468
+ return {
469
+ utmSource: params.get('utm_source') || undefined,
470
+ utmMedium: params.get('utm_medium') || undefined,
471
+ utmCampaign: params.get('utm_campaign') || undefined,
472
+ utmTerm: params.get('utm_term') || undefined,
473
+ utmContent: params.get('utm_content') || undefined,
474
+ };
475
+ }
476
+ catch {
477
+ return {};
478
+ }
479
+ }
480
+ /**
481
+ * Check if URL is a download link
482
+ */
483
+ function isDownloadUrl(url) {
484
+ const lowerUrl = url.toLowerCase();
485
+ return DOWNLOAD_EXTENSIONS.some((ext) => lowerUrl.includes(ext));
486
+ }
487
+ /**
488
+ * Extract filename from URL
489
+ */
490
+ function getFilenameFromUrl(url) {
491
+ try {
492
+ return url.split('/').pop()?.split('?')[0] || 'unknown';
493
+ }
494
+ catch {
495
+ return 'unknown';
496
+ }
497
+ }
498
+ /**
499
+ * Extract file extension from URL
500
+ */
501
+ function getFileExtension(url) {
502
+ const filename = getFilenameFromUrl(url);
503
+ const parts = filename.split('.');
504
+ return parts.length > 1 ? parts.pop() || 'unknown' : 'unknown';
505
+ }
506
+ // ============================================
507
+ // DOM UTILITIES
508
+ // ============================================
509
+ /**
510
+ * Get text content from element (truncated)
511
+ */
512
+ function getElementText(element, maxLength = 100) {
513
+ const text = element.innerText ||
514
+ element.textContent ||
515
+ element.value ||
516
+ '';
517
+ return text.trim().substring(0, maxLength);
518
+ }
519
+ /**
520
+ * Get element identification info
521
+ */
522
+ function getElementInfo(element) {
523
+ return {
524
+ tag: element.tagName?.toLowerCase() || 'unknown',
525
+ id: element.id || '',
526
+ className: element.className || '',
527
+ text: getElementText(element, 50),
528
+ };
529
+ }
530
+ /**
531
+ * Check if element is a trackable click target
532
+ */
533
+ function isTrackableClickElement(element) {
534
+ const trackableTags = ['BUTTON', 'A', 'INPUT'];
535
+ return (trackableTags.includes(element.tagName) ||
536
+ element.hasAttribute('data-track-click') ||
537
+ element.classList.contains('track-click'));
538
+ }
539
+ /**
540
+ * Check if device is mobile
541
+ */
542
+ function isMobile() {
543
+ if (typeof navigator === 'undefined')
544
+ return false;
545
+ return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
546
+ }
547
+ // ============================================
548
+ // DEVICE INFO
549
+ // ============================================
550
+ /**
551
+ * Get current device information
552
+ */
553
+ function getDeviceInfo() {
554
+ if (typeof window === 'undefined' || typeof navigator === 'undefined') {
555
+ return {
556
+ userAgent: 'unknown',
557
+ screen: 'unknown',
558
+ language: 'unknown',
559
+ timezone: 'unknown',
560
+ };
561
+ }
562
+ return {
563
+ userAgent: navigator.userAgent,
564
+ screen: `${screen.width}x${screen.height}`,
565
+ language: navigator.language,
566
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'unknown',
567
+ };
568
+ }
569
+
570
+ /**
571
+ * Clianta SDK - Event Queue
572
+ * Handles batching and flushing of events
573
+ * @see SDK_VERSION in core/config.ts
574
+ */
575
+ const MAX_QUEUE_SIZE = 1000;
576
+ /** Rate limit: max events per window */
577
+ const RATE_LIMIT_MAX_EVENTS = 100;
578
+ /** Rate limit window in ms (1 minute) */
579
+ const RATE_LIMIT_WINDOW_MS = 60000;
580
+ /**
581
+ * Event queue with batching, persistence, rate limiting, and auto-flush
582
+ */
583
+ class EventQueue {
584
+ constructor(transport, config = {}) {
585
+ this.queue = [];
586
+ this.flushTimer = null;
587
+ this.isFlushing = false;
588
+ /** Rate limiting: timestamps of recent events */
589
+ this.eventTimestamps = [];
590
+ /** Unload handler references for cleanup */
591
+ this.boundBeforeUnload = null;
592
+ this.boundVisibilityChange = null;
593
+ this.boundPageHide = null;
594
+ this.transport = transport;
595
+ this.config = {
596
+ batchSize: config.batchSize ?? 10,
597
+ flushInterval: config.flushInterval ?? 5000,
598
+ maxQueueSize: config.maxQueueSize ?? MAX_QUEUE_SIZE,
599
+ storageKey: config.storageKey ?? STORAGE_KEYS.EVENT_QUEUE,
600
+ };
601
+ // Restore persisted queue
602
+ this.restoreQueue();
603
+ // Start auto-flush timer
604
+ this.startFlushTimer();
605
+ // Setup unload handlers
606
+ this.setupUnloadHandlers();
607
+ }
608
+ /**
609
+ * Add an event to the queue
610
+ */
611
+ push(event) {
612
+ // Rate limiting check
613
+ if (!this.checkRateLimit()) {
614
+ logger.warn('Rate limit exceeded, event dropped:', event.eventName);
615
+ return;
616
+ }
617
+ // Don't exceed max queue size
618
+ if (this.queue.length >= this.config.maxQueueSize) {
619
+ logger.warn('Queue full, dropping oldest event');
620
+ this.queue.shift();
621
+ }
622
+ this.queue.push(event);
623
+ logger.debug('Event queued:', event.eventName, `(${this.queue.length} in queue)`);
624
+ // Flush if batch size reached
625
+ if (this.queue.length >= this.config.batchSize) {
626
+ this.flush();
627
+ }
628
+ }
629
+ /**
630
+ * Check and enforce rate limiting
631
+ * @returns true if event is allowed, false if rate limited
632
+ */
633
+ checkRateLimit() {
634
+ const now = Date.now();
635
+ // Remove timestamps outside the window
636
+ this.eventTimestamps = this.eventTimestamps.filter(ts => now - ts < RATE_LIMIT_WINDOW_MS);
637
+ // Check if under limit
638
+ if (this.eventTimestamps.length >= RATE_LIMIT_MAX_EVENTS) {
639
+ return false;
640
+ }
641
+ // Record this event
642
+ this.eventTimestamps.push(now);
643
+ return true;
644
+ }
645
+ /**
646
+ * Flush the queue (send all events)
647
+ */
648
+ async flush() {
649
+ if (this.isFlushing || this.queue.length === 0) {
650
+ return;
651
+ }
652
+ this.isFlushing = true;
653
+ // Atomically take snapshot of current queue length to avoid race condition
654
+ const count = this.queue.length;
655
+ const events = this.queue.splice(0, count);
656
+ try {
657
+ logger.debug(`Flushing ${events.length} events`);
658
+ // Clear persisted queue
659
+ this.persistQueue([]);
660
+ // Send to backend
661
+ const result = await this.transport.sendEvents(events);
662
+ if (!result.success) {
663
+ // Re-queue events on failure (at the front)
664
+ logger.warn('Flush failed, re-queuing events');
665
+ this.queue.unshift(...events);
666
+ this.persistQueue(this.queue);
667
+ }
668
+ else {
669
+ logger.debug('Flush successful');
670
+ }
671
+ }
672
+ catch (error) {
673
+ logger.error('Flush error:', error);
674
+ }
675
+ finally {
676
+ this.isFlushing = false;
677
+ }
678
+ }
679
+ /**
680
+ * Flush synchronously using sendBeacon (for page unload)
681
+ */
682
+ flushSync() {
683
+ if (this.queue.length === 0)
684
+ return;
685
+ const events = this.queue.splice(0, this.queue.length);
686
+ logger.debug(`Sync flushing ${events.length} events via beacon`);
687
+ const success = this.transport.sendBeacon(events);
688
+ if (!success) {
689
+ // Re-queue and persist for next page load
690
+ this.queue.unshift(...events);
691
+ this.persistQueue(this.queue);
692
+ }
693
+ }
694
+ /**
695
+ * Get current queue length
696
+ */
697
+ get length() {
698
+ return this.queue.length;
699
+ }
700
+ /**
701
+ * Clear the queue
702
+ */
703
+ clear() {
704
+ this.queue = [];
705
+ this.persistQueue([]);
706
+ }
707
+ /**
708
+ * Stop the flush timer and cleanup handlers
709
+ */
710
+ destroy() {
711
+ if (this.flushTimer) {
712
+ clearInterval(this.flushTimer);
713
+ this.flushTimer = null;
714
+ }
715
+ // Remove unload handlers
716
+ if (typeof window !== 'undefined') {
717
+ if (this.boundBeforeUnload) {
718
+ window.removeEventListener('beforeunload', this.boundBeforeUnload);
719
+ }
720
+ if (this.boundVisibilityChange) {
721
+ window.removeEventListener('visibilitychange', this.boundVisibilityChange);
722
+ }
723
+ if (this.boundPageHide) {
724
+ window.removeEventListener('pagehide', this.boundPageHide);
725
+ }
726
+ }
727
+ }
728
+ /**
729
+ * Start auto-flush timer
730
+ */
731
+ startFlushTimer() {
732
+ if (this.flushTimer) {
733
+ clearInterval(this.flushTimer);
734
+ }
735
+ this.flushTimer = setInterval(() => {
736
+ this.flush();
737
+ }, this.config.flushInterval);
738
+ }
739
+ /**
740
+ * Setup page unload handlers
741
+ */
742
+ setupUnloadHandlers() {
743
+ if (typeof window === 'undefined')
744
+ return;
745
+ // Flush on page unload
746
+ this.boundBeforeUnload = () => this.flushSync();
747
+ window.addEventListener('beforeunload', this.boundBeforeUnload);
748
+ // Flush when page becomes hidden
749
+ this.boundVisibilityChange = () => {
750
+ if (document.visibilityState === 'hidden') {
751
+ this.flushSync();
752
+ }
753
+ };
754
+ window.addEventListener('visibilitychange', this.boundVisibilityChange);
755
+ // Flush on page hide (iOS Safari)
756
+ this.boundPageHide = () => this.flushSync();
757
+ window.addEventListener('pagehide', this.boundPageHide);
758
+ }
759
+ /**
760
+ * Persist queue to localStorage
761
+ */
762
+ persistQueue(events) {
763
+ try {
764
+ setLocalStorage(this.config.storageKey, JSON.stringify(events));
765
+ }
766
+ catch {
767
+ // Ignore storage errors
768
+ }
769
+ }
770
+ /**
771
+ * Restore queue from localStorage
772
+ */
773
+ restoreQueue() {
774
+ try {
775
+ const stored = getLocalStorage(this.config.storageKey);
776
+ if (stored) {
777
+ const events = JSON.parse(stored);
778
+ if (Array.isArray(events) && events.length > 0) {
779
+ this.queue = events;
780
+ logger.debug(`Restored ${events.length} events from storage`);
781
+ }
782
+ }
783
+ }
784
+ catch {
785
+ // Ignore parse errors
786
+ }
787
+ }
788
+ }
789
+
790
+ /**
791
+ * Clianta SDK - Plugin Base
792
+ * @see SDK_VERSION in core/config.ts
793
+ */
794
+ /**
795
+ * Base class for plugins
796
+ */
797
+ class BasePlugin {
798
+ constructor() {
799
+ this.tracker = null;
800
+ }
801
+ init(tracker) {
802
+ this.tracker = tracker;
803
+ }
804
+ destroy() {
805
+ this.tracker = null;
806
+ }
807
+ track(eventType, eventName, properties) {
808
+ if (this.tracker) {
809
+ this.tracker.track(eventType, eventName, properties);
810
+ }
811
+ }
812
+ }
813
+
814
+ /**
815
+ * Clianta SDK - Page View Plugin
816
+ * @see SDK_VERSION in core/config.ts
817
+ */
818
+ /**
819
+ * Page View Plugin - Tracks page views
820
+ */
821
+ class PageViewPlugin extends BasePlugin {
822
+ constructor() {
823
+ super(...arguments);
824
+ this.name = 'pageView';
825
+ this.originalPushState = null;
826
+ this.originalReplaceState = null;
827
+ this.popstateHandler = null;
828
+ }
829
+ init(tracker) {
830
+ super.init(tracker);
831
+ // Track initial page view
832
+ this.trackPageView();
833
+ // Track SPA navigation (History API)
834
+ if (typeof window !== 'undefined') {
835
+ // Store originals for cleanup
836
+ this.originalPushState = history.pushState;
837
+ this.originalReplaceState = history.replaceState;
838
+ // Intercept pushState and replaceState
839
+ const self = this;
840
+ history.pushState = function (...args) {
841
+ self.originalPushState.apply(history, args);
842
+ self.trackPageView();
843
+ };
844
+ history.replaceState = function (...args) {
845
+ self.originalReplaceState.apply(history, args);
846
+ self.trackPageView();
847
+ };
848
+ // Handle back/forward navigation
849
+ this.popstateHandler = () => this.trackPageView();
850
+ window.addEventListener('popstate', this.popstateHandler);
851
+ }
852
+ }
853
+ destroy() {
854
+ // Restore original history methods
855
+ if (this.originalPushState) {
856
+ history.pushState = this.originalPushState;
857
+ this.originalPushState = null;
858
+ }
859
+ if (this.originalReplaceState) {
860
+ history.replaceState = this.originalReplaceState;
861
+ this.originalReplaceState = null;
862
+ }
863
+ // Remove popstate listener
864
+ if (this.popstateHandler && typeof window !== 'undefined') {
865
+ window.removeEventListener('popstate', this.popstateHandler);
866
+ this.popstateHandler = null;
867
+ }
868
+ super.destroy();
869
+ }
870
+ trackPageView() {
871
+ if (typeof window === 'undefined' || typeof document === 'undefined')
872
+ return;
873
+ this.track('page_view', 'Page Viewed', {
874
+ title: document.title,
875
+ path: window.location.pathname,
876
+ search: window.location.search,
877
+ hash: window.location.hash,
878
+ referrer: document.referrer || 'direct',
879
+ viewport: `${window.innerWidth}x${window.innerHeight}`,
880
+ });
881
+ }
882
+ }
883
+
884
+ /**
885
+ * Clianta SDK - Scroll Depth Plugin
886
+ * @see SDK_VERSION in core/config.ts
887
+ */
888
+ /**
889
+ * Scroll Depth Plugin - Tracks scroll milestones
890
+ */
891
+ class ScrollPlugin extends BasePlugin {
892
+ constructor() {
893
+ super(...arguments);
894
+ this.name = 'scroll';
895
+ this.milestonesReached = new Set();
896
+ this.maxScrollDepth = 0;
897
+ this.pageLoadTime = 0;
898
+ this.scrollTimeout = null;
899
+ this.boundHandler = null;
900
+ /** SPA navigation support */
901
+ this.originalPushState = null;
902
+ this.originalReplaceState = null;
903
+ this.popstateHandler = null;
904
+ }
905
+ init(tracker) {
906
+ super.init(tracker);
907
+ this.pageLoadTime = Date.now();
908
+ if (typeof window !== 'undefined') {
909
+ this.boundHandler = this.handleScroll.bind(this);
910
+ window.addEventListener('scroll', this.boundHandler, { passive: true });
911
+ // Setup SPA navigation reset
912
+ this.setupNavigationReset();
913
+ }
914
+ }
915
+ destroy() {
916
+ if (this.boundHandler && typeof window !== 'undefined') {
917
+ window.removeEventListener('scroll', this.boundHandler);
918
+ }
919
+ if (this.scrollTimeout) {
920
+ clearTimeout(this.scrollTimeout);
921
+ }
922
+ // Restore original history methods
923
+ if (this.originalPushState) {
924
+ history.pushState = this.originalPushState;
925
+ this.originalPushState = null;
926
+ }
927
+ if (this.originalReplaceState) {
928
+ history.replaceState = this.originalReplaceState;
929
+ this.originalReplaceState = null;
930
+ }
931
+ // Remove popstate listener
932
+ if (this.popstateHandler && typeof window !== 'undefined') {
933
+ window.removeEventListener('popstate', this.popstateHandler);
934
+ this.popstateHandler = null;
935
+ }
936
+ super.destroy();
937
+ }
938
+ /**
939
+ * Reset scroll tracking for SPA navigation
940
+ */
941
+ resetForNavigation() {
942
+ this.milestonesReached.clear();
943
+ this.maxScrollDepth = 0;
944
+ this.pageLoadTime = Date.now();
945
+ }
946
+ /**
947
+ * Setup History API interception for SPA navigation
948
+ */
949
+ setupNavigationReset() {
950
+ if (typeof window === 'undefined')
951
+ return;
952
+ // Store originals for cleanup
953
+ this.originalPushState = history.pushState;
954
+ this.originalReplaceState = history.replaceState;
955
+ // Intercept pushState and replaceState
956
+ const self = this;
957
+ history.pushState = function (...args) {
958
+ self.originalPushState.apply(history, args);
959
+ self.resetForNavigation();
960
+ };
961
+ history.replaceState = function (...args) {
962
+ self.originalReplaceState.apply(history, args);
963
+ self.resetForNavigation();
964
+ };
965
+ // Handle back/forward navigation
966
+ this.popstateHandler = () => this.resetForNavigation();
967
+ window.addEventListener('popstate', this.popstateHandler);
968
+ }
969
+ handleScroll() {
970
+ // Debounce scroll tracking
971
+ if (this.scrollTimeout) {
972
+ clearTimeout(this.scrollTimeout);
973
+ }
974
+ this.scrollTimeout = setTimeout(() => this.trackScrollDepth(), 150);
975
+ }
976
+ trackScrollDepth() {
977
+ if (typeof window === 'undefined' || typeof document === 'undefined')
978
+ return;
979
+ const windowHeight = window.innerHeight;
980
+ const documentHeight = document.documentElement.scrollHeight;
981
+ const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
982
+ const scrollableHeight = documentHeight - windowHeight;
983
+ // Guard against divide-by-zero on short pages
984
+ if (scrollableHeight <= 0)
985
+ return;
986
+ const scrollPercent = Math.floor((scrollTop / scrollableHeight) * 100);
987
+ // Clamp to valid range
988
+ const clampedPercent = Math.max(0, Math.min(100, scrollPercent));
989
+ // Update max scroll depth
990
+ if (clampedPercent > this.maxScrollDepth) {
991
+ this.maxScrollDepth = clampedPercent;
992
+ }
993
+ // Track milestones
994
+ for (const milestone of SCROLL_MILESTONES) {
995
+ if (clampedPercent >= milestone && !this.milestonesReached.has(milestone)) {
996
+ this.milestonesReached.add(milestone);
997
+ this.track('scroll_depth', `Scrolled ${milestone}%`, {
998
+ depth: milestone,
999
+ maxDepth: this.maxScrollDepth,
1000
+ timeToReach: Date.now() - this.pageLoadTime,
1001
+ });
1002
+ }
1003
+ }
1004
+ }
1005
+ }
1006
+
1007
+ /**
1008
+ * Clianta SDK - Form Tracking Plugin
1009
+ * @see SDK_VERSION in core/config.ts
1010
+ */
1011
+ /**
1012
+ * Form Tracking Plugin - Auto-tracks form views, interactions, and submissions
1013
+ */
1014
+ class FormsPlugin extends BasePlugin {
1015
+ constructor() {
1016
+ super(...arguments);
1017
+ this.name = 'forms';
1018
+ this.trackedForms = new WeakSet();
1019
+ this.formInteractions = new Set();
1020
+ this.observer = null;
1021
+ this.listeners = [];
1022
+ }
1023
+ init(tracker) {
1024
+ super.init(tracker);
1025
+ if (typeof document === 'undefined')
1026
+ return;
1027
+ // Track existing forms
1028
+ this.trackAllForms();
1029
+ // Watch for dynamically added forms
1030
+ if (typeof MutationObserver !== 'undefined') {
1031
+ this.observer = new MutationObserver(() => this.trackAllForms());
1032
+ this.observer.observe(document.body, { childList: true, subtree: true });
1033
+ }
1034
+ }
1035
+ destroy() {
1036
+ if (this.observer) {
1037
+ this.observer.disconnect();
1038
+ this.observer = null;
1039
+ }
1040
+ // Remove all tracked event listeners
1041
+ for (const { element, event, handler } of this.listeners) {
1042
+ element.removeEventListener(event, handler);
1043
+ }
1044
+ this.listeners = [];
1045
+ super.destroy();
1046
+ }
1047
+ /**
1048
+ * Track event listener for cleanup
1049
+ */
1050
+ addListener(element, event, handler) {
1051
+ element.addEventListener(event, handler);
1052
+ this.listeners.push({ element, event, handler });
1053
+ }
1054
+ trackAllForms() {
1055
+ document.querySelectorAll('form').forEach((form) => {
1056
+ this.setupFormTracking(form);
1057
+ });
1058
+ }
1059
+ setupFormTracking(form) {
1060
+ if (this.trackedForms.has(form))
1061
+ return;
1062
+ this.trackedForms.add(form);
1063
+ const formId = form.id || form.name || `form-${Math.random().toString(36).substr(2, 9)}`;
1064
+ // Track form view
1065
+ this.track('form_view', 'Form Viewed', {
1066
+ formId,
1067
+ action: form.action,
1068
+ method: form.method,
1069
+ fieldCount: form.elements.length,
1070
+ });
1071
+ // Track field interactions
1072
+ Array.from(form.elements).forEach((field) => {
1073
+ if (field instanceof HTMLInputElement ||
1074
+ field instanceof HTMLSelectElement ||
1075
+ field instanceof HTMLTextAreaElement) {
1076
+ if (!field.name || field.type === 'submit' || field.type === 'button')
1077
+ return;
1078
+ ['focus', 'blur', 'change'].forEach((eventType) => {
1079
+ const handler = () => {
1080
+ const key = `${formId}-${field.name}-${eventType}`;
1081
+ if (!this.formInteractions.has(key)) {
1082
+ this.formInteractions.add(key);
1083
+ this.track('form_interaction', 'Form Field Interaction', {
1084
+ formId,
1085
+ fieldName: field.name,
1086
+ fieldType: field.type,
1087
+ interactionType: eventType,
1088
+ });
1089
+ }
1090
+ };
1091
+ this.addListener(field, eventType, handler);
1092
+ });
1093
+ }
1094
+ });
1095
+ // Track form submission
1096
+ const submitHandler = () => {
1097
+ this.track('form_submit', 'Form Submitted', {
1098
+ formId,
1099
+ action: form.action,
1100
+ method: form.method,
1101
+ });
1102
+ // Auto-identify if email field found
1103
+ this.autoIdentify(form);
1104
+ };
1105
+ this.addListener(form, 'submit', submitHandler);
1106
+ }
1107
+ autoIdentify(form) {
1108
+ const emailField = form.querySelector('input[type="email"], input[name*="email"]');
1109
+ if (!emailField?.value || !this.tracker)
1110
+ return;
1111
+ const email = emailField.value;
1112
+ const traits = {};
1113
+ // Capture common fields
1114
+ const firstNameField = form.querySelector('[name*="first"], [name*="fname"]');
1115
+ const lastNameField = form.querySelector('[name*="last"], [name*="lname"]');
1116
+ const companyField = form.querySelector('[name*="company"], [name*="organization"]');
1117
+ const phoneField = form.querySelector('[type="tel"], [name*="phone"]');
1118
+ if (firstNameField?.value)
1119
+ traits.firstName = firstNameField.value;
1120
+ if (lastNameField?.value)
1121
+ traits.lastName = lastNameField.value;
1122
+ if (companyField?.value)
1123
+ traits.company = companyField.value;
1124
+ if (phoneField?.value)
1125
+ traits.phone = phoneField.value;
1126
+ this.tracker.identify(email, traits);
1127
+ }
1128
+ }
1129
+
1130
+ /**
1131
+ * Clianta SDK - Click Tracking Plugin
1132
+ * @see SDK_VERSION in core/config.ts
1133
+ */
1134
+ /**
1135
+ * Click Tracking Plugin - Tracks button and CTA clicks
1136
+ */
1137
+ class ClicksPlugin extends BasePlugin {
1138
+ constructor() {
1139
+ super(...arguments);
1140
+ this.name = 'clicks';
1141
+ this.boundHandler = null;
1142
+ }
1143
+ init(tracker) {
1144
+ super.init(tracker);
1145
+ if (typeof document !== 'undefined') {
1146
+ this.boundHandler = this.handleClick.bind(this);
1147
+ document.addEventListener('click', this.boundHandler, true);
1148
+ }
1149
+ }
1150
+ destroy() {
1151
+ if (this.boundHandler && typeof document !== 'undefined') {
1152
+ document.removeEventListener('click', this.boundHandler, true);
1153
+ }
1154
+ super.destroy();
1155
+ }
1156
+ handleClick(e) {
1157
+ const target = e.target;
1158
+ if (!target || !isTrackableClickElement(target))
1159
+ return;
1160
+ const buttonText = getElementText(target, 100);
1161
+ const elementInfo = getElementInfo(target);
1162
+ this.track('button_click', 'Button Clicked', {
1163
+ buttonText,
1164
+ elementType: target.tagName.toLowerCase(),
1165
+ elementId: elementInfo.id,
1166
+ elementClass: elementInfo.className,
1167
+ href: target.href || undefined,
1168
+ });
1169
+ }
1170
+ }
1171
+
1172
+ /**
1173
+ * Clianta SDK - Engagement Plugin
1174
+ * @see SDK_VERSION in core/config.ts
1175
+ */
1176
+ /**
1177
+ * Engagement Plugin - Tracks user engagement and time on page
1178
+ */
1179
+ class EngagementPlugin extends BasePlugin {
1180
+ constructor() {
1181
+ super(...arguments);
1182
+ this.name = 'engagement';
1183
+ this.pageLoadTime = 0;
1184
+ this.engagementStartTime = 0;
1185
+ this.isEngaged = false;
1186
+ this.engagementTimeout = null;
1187
+ this.boundMarkEngaged = null;
1188
+ this.boundTrackTimeOnPage = null;
1189
+ this.boundVisibilityHandler = null;
1190
+ }
1191
+ init(tracker) {
1192
+ super.init(tracker);
1193
+ this.pageLoadTime = Date.now();
1194
+ this.engagementStartTime = Date.now();
1195
+ if (typeof document === 'undefined' || typeof window === 'undefined')
1196
+ return;
1197
+ // Setup engagement detection
1198
+ this.boundMarkEngaged = this.markEngaged.bind(this);
1199
+ this.boundTrackTimeOnPage = this.trackTimeOnPage.bind(this);
1200
+ this.boundVisibilityHandler = () => {
1201
+ if (document.visibilityState === 'hidden') {
1202
+ this.trackTimeOnPage();
1203
+ }
1204
+ else {
1205
+ // Reset engagement timer when page becomes visible again
1206
+ this.engagementStartTime = Date.now();
1207
+ }
1208
+ };
1209
+ ['mousemove', 'keydown', 'touchstart', 'scroll'].forEach((event) => {
1210
+ document.addEventListener(event, this.boundMarkEngaged, { passive: true });
1211
+ });
1212
+ // Track time on page before unload
1213
+ window.addEventListener('beforeunload', this.boundTrackTimeOnPage);
1214
+ document.addEventListener('visibilitychange', this.boundVisibilityHandler);
1215
+ }
1216
+ destroy() {
1217
+ if (this.boundMarkEngaged && typeof document !== 'undefined') {
1218
+ ['mousemove', 'keydown', 'touchstart', 'scroll'].forEach((event) => {
1219
+ document.removeEventListener(event, this.boundMarkEngaged);
1220
+ });
1221
+ }
1222
+ if (this.boundTrackTimeOnPage && typeof window !== 'undefined') {
1223
+ window.removeEventListener('beforeunload', this.boundTrackTimeOnPage);
1224
+ }
1225
+ if (this.boundVisibilityHandler && typeof document !== 'undefined') {
1226
+ document.removeEventListener('visibilitychange', this.boundVisibilityHandler);
1227
+ }
1228
+ if (this.engagementTimeout) {
1229
+ clearTimeout(this.engagementTimeout);
1230
+ }
1231
+ super.destroy();
1232
+ }
1233
+ markEngaged() {
1234
+ if (!this.isEngaged) {
1235
+ this.isEngaged = true;
1236
+ this.track('engagement', 'User Engaged', {
1237
+ timeToEngage: Date.now() - this.pageLoadTime,
1238
+ });
1239
+ }
1240
+ // Reset engagement timeout
1241
+ if (this.engagementTimeout) {
1242
+ clearTimeout(this.engagementTimeout);
1243
+ }
1244
+ this.engagementTimeout = setTimeout(() => {
1245
+ this.isEngaged = false;
1246
+ }, 30000); // 30 seconds of inactivity
1247
+ }
1248
+ trackTimeOnPage() {
1249
+ const timeSpent = Math.floor((Date.now() - this.engagementStartTime) / 1000);
1250
+ if (timeSpent > 0) {
1251
+ this.track('time_on_page', 'Time Spent', {
1252
+ seconds: timeSpent,
1253
+ engaged: this.isEngaged,
1254
+ });
1255
+ }
1256
+ }
1257
+ }
1258
+
1259
+ /**
1260
+ * Clianta SDK - Downloads Plugin
1261
+ * @see SDK_VERSION in core/config.ts
1262
+ */
1263
+ /**
1264
+ * Downloads Plugin - Tracks file downloads
1265
+ */
1266
+ class DownloadsPlugin extends BasePlugin {
1267
+ constructor() {
1268
+ super(...arguments);
1269
+ this.name = 'downloads';
1270
+ this.trackedDownloads = new Set();
1271
+ this.boundHandler = null;
1272
+ /** SPA navigation support */
1273
+ this.originalPushState = null;
1274
+ this.originalReplaceState = null;
1275
+ this.popstateHandler = null;
1276
+ }
1277
+ init(tracker) {
1278
+ super.init(tracker);
1279
+ if (typeof document !== 'undefined') {
1280
+ this.boundHandler = this.handleClick.bind(this);
1281
+ document.addEventListener('click', this.boundHandler, true);
1282
+ // Setup SPA navigation reset
1283
+ this.setupNavigationReset();
1284
+ }
1285
+ }
1286
+ destroy() {
1287
+ if (this.boundHandler && typeof document !== 'undefined') {
1288
+ document.removeEventListener('click', this.boundHandler, true);
1289
+ }
1290
+ // Restore original history methods
1291
+ if (this.originalPushState) {
1292
+ history.pushState = this.originalPushState;
1293
+ this.originalPushState = null;
1294
+ }
1295
+ if (this.originalReplaceState) {
1296
+ history.replaceState = this.originalReplaceState;
1297
+ this.originalReplaceState = null;
1298
+ }
1299
+ // Remove popstate listener
1300
+ if (this.popstateHandler && typeof window !== 'undefined') {
1301
+ window.removeEventListener('popstate', this.popstateHandler);
1302
+ this.popstateHandler = null;
1303
+ }
1304
+ super.destroy();
1305
+ }
1306
+ /**
1307
+ * Reset download tracking for SPA navigation
1308
+ */
1309
+ resetForNavigation() {
1310
+ this.trackedDownloads.clear();
1311
+ }
1312
+ /**
1313
+ * Setup History API interception for SPA navigation
1314
+ */
1315
+ setupNavigationReset() {
1316
+ if (typeof window === 'undefined')
1317
+ return;
1318
+ // Store originals for cleanup
1319
+ this.originalPushState = history.pushState;
1320
+ this.originalReplaceState = history.replaceState;
1321
+ // Intercept pushState and replaceState
1322
+ const self = this;
1323
+ history.pushState = function (...args) {
1324
+ self.originalPushState.apply(history, args);
1325
+ self.resetForNavigation();
1326
+ };
1327
+ history.replaceState = function (...args) {
1328
+ self.originalReplaceState.apply(history, args);
1329
+ self.resetForNavigation();
1330
+ };
1331
+ // Handle back/forward navigation
1332
+ this.popstateHandler = () => this.resetForNavigation();
1333
+ window.addEventListener('popstate', this.popstateHandler);
1334
+ }
1335
+ handleClick(e) {
1336
+ const link = e.target.closest('a');
1337
+ if (!link || !link.href)
1338
+ return;
1339
+ const url = link.href;
1340
+ // Check if it's a download link
1341
+ if (!isDownloadUrl(url))
1342
+ return;
1343
+ // Avoid tracking the same download multiple times
1344
+ if (this.trackedDownloads.has(url))
1345
+ return;
1346
+ this.trackedDownloads.add(url);
1347
+ this.track('download', 'File Download', {
1348
+ url,
1349
+ filename: getFilenameFromUrl(url),
1350
+ fileType: getFileExtension(url),
1351
+ linkText: getElementText(link, 100),
1352
+ });
1353
+ }
1354
+ }
1355
+
1356
+ /**
1357
+ * Clianta SDK - Exit Intent Plugin
1358
+ * @see SDK_VERSION in core/config.ts
1359
+ */
1360
+ /**
1361
+ * Exit Intent Plugin - Detects when user intends to leave the page
1362
+ */
1363
+ class ExitIntentPlugin extends BasePlugin {
1364
+ constructor() {
1365
+ super(...arguments);
1366
+ this.name = 'exitIntent';
1367
+ this.exitIntentShown = false;
1368
+ this.pageLoadTime = 0;
1369
+ this.boundHandler = null;
1370
+ }
1371
+ init(tracker) {
1372
+ super.init(tracker);
1373
+ this.pageLoadTime = Date.now();
1374
+ // Skip on mobile (no mouse events)
1375
+ if (isMobile())
1376
+ return;
1377
+ if (typeof document !== 'undefined') {
1378
+ this.boundHandler = this.handleMouseLeave.bind(this);
1379
+ document.addEventListener('mouseleave', this.boundHandler);
1380
+ }
1381
+ }
1382
+ destroy() {
1383
+ if (this.boundHandler && typeof document !== 'undefined') {
1384
+ document.removeEventListener('mouseleave', this.boundHandler);
1385
+ }
1386
+ super.destroy();
1387
+ }
1388
+ handleMouseLeave(e) {
1389
+ // Only trigger when mouse leaves from the top of the page
1390
+ if (e.clientY > 0 || this.exitIntentShown)
1391
+ return;
1392
+ this.exitIntentShown = true;
1393
+ this.track('exit_intent', 'Exit Intent Detected', {
1394
+ timeOnPage: Date.now() - this.pageLoadTime,
1395
+ });
1396
+ }
1397
+ }
1398
+
1399
+ /**
1400
+ * Clianta SDK - Error Tracking Plugin
1401
+ * @see SDK_VERSION in core/config.ts
1402
+ */
1403
+ /**
1404
+ * Error Tracking Plugin - Tracks JavaScript errors
1405
+ */
1406
+ class ErrorsPlugin extends BasePlugin {
1407
+ constructor() {
1408
+ super(...arguments);
1409
+ this.name = 'errors';
1410
+ this.boundErrorHandler = null;
1411
+ this.boundRejectionHandler = null;
1412
+ }
1413
+ init(tracker) {
1414
+ super.init(tracker);
1415
+ if (typeof window !== 'undefined') {
1416
+ this.boundErrorHandler = this.handleError.bind(this);
1417
+ this.boundRejectionHandler = this.handleRejection.bind(this);
1418
+ window.addEventListener('error', this.boundErrorHandler);
1419
+ window.addEventListener('unhandledrejection', this.boundRejectionHandler);
1420
+ }
1421
+ }
1422
+ destroy() {
1423
+ if (typeof window !== 'undefined') {
1424
+ if (this.boundErrorHandler) {
1425
+ window.removeEventListener('error', this.boundErrorHandler);
1426
+ }
1427
+ if (this.boundRejectionHandler) {
1428
+ window.removeEventListener('unhandledrejection', this.boundRejectionHandler);
1429
+ }
1430
+ }
1431
+ super.destroy();
1432
+ }
1433
+ handleError(e) {
1434
+ this.track('error', 'JavaScript Error', {
1435
+ message: e.message,
1436
+ filename: e.filename,
1437
+ line: e.lineno,
1438
+ column: e.colno,
1439
+ stack: e.error?.stack?.substring(0, 500),
1440
+ });
1441
+ }
1442
+ handleRejection(e) {
1443
+ this.track('error', 'Unhandled Promise Rejection', {
1444
+ reason: String(e.reason).substring(0, 200),
1445
+ });
1446
+ }
1447
+ }
1448
+
1449
+ /**
1450
+ * Clianta SDK - Performance Plugin
1451
+ * @see SDK_VERSION in core/config.ts
1452
+ */
1453
+ /**
1454
+ * Performance Plugin - Tracks page performance and Web Vitals
1455
+ */
1456
+ class PerformancePlugin extends BasePlugin {
1457
+ constructor() {
1458
+ super(...arguments);
1459
+ this.name = 'performance';
1460
+ this.boundLoadHandler = null;
1461
+ this.observers = [];
1462
+ this.boundClsVisibilityHandler = null;
1463
+ }
1464
+ init(tracker) {
1465
+ super.init(tracker);
1466
+ if (typeof window !== 'undefined') {
1467
+ // Track performance after page load
1468
+ this.boundLoadHandler = () => {
1469
+ // Delay to ensure all metrics are available
1470
+ setTimeout(() => this.trackPerformance(), 100);
1471
+ };
1472
+ window.addEventListener('load', this.boundLoadHandler);
1473
+ }
1474
+ }
1475
+ destroy() {
1476
+ if (this.boundLoadHandler && typeof window !== 'undefined') {
1477
+ window.removeEventListener('load', this.boundLoadHandler);
1478
+ }
1479
+ for (const observer of this.observers) {
1480
+ observer.disconnect();
1481
+ }
1482
+ this.observers = [];
1483
+ if (this.boundClsVisibilityHandler && typeof window !== 'undefined') {
1484
+ window.removeEventListener('visibilitychange', this.boundClsVisibilityHandler);
1485
+ }
1486
+ super.destroy();
1487
+ }
1488
+ trackPerformance() {
1489
+ if (typeof performance === 'undefined')
1490
+ return;
1491
+ // Use modern Navigation Timing API (PerformanceNavigationTiming)
1492
+ const entries = performance.getEntriesByType('navigation');
1493
+ if (entries.length > 0) {
1494
+ const navTiming = entries[0];
1495
+ const loadTime = Math.round(navTiming.loadEventEnd - navTiming.startTime);
1496
+ const domReady = Math.round(navTiming.domContentLoadedEventEnd - navTiming.startTime);
1497
+ const ttfb = Math.round(navTiming.responseStart - navTiming.requestStart);
1498
+ const domInteractive = Math.round(navTiming.domInteractive - navTiming.startTime);
1499
+ this.track('performance', 'Page Performance', {
1500
+ loadTime,
1501
+ domReady,
1502
+ ttfb, // Time to First Byte
1503
+ domInteractive,
1504
+ // Additional modern metrics
1505
+ dns: Math.round(navTiming.domainLookupEnd - navTiming.domainLookupStart),
1506
+ connection: Math.round(navTiming.connectEnd - navTiming.connectStart),
1507
+ transferSize: navTiming.transferSize,
1508
+ });
1509
+ }
1510
+ else {
1511
+ // Fallback for older browsers using deprecated API
1512
+ const timing = performance.timing;
1513
+ if (!timing)
1514
+ return;
1515
+ const loadTime = timing.loadEventEnd - timing.navigationStart;
1516
+ const domReady = timing.domContentLoadedEventEnd - timing.navigationStart;
1517
+ const ttfb = timing.responseStart - timing.navigationStart;
1518
+ const domInteractive = timing.domInteractive - timing.navigationStart;
1519
+ this.track('performance', 'Page Performance', {
1520
+ loadTime,
1521
+ domReady,
1522
+ ttfb,
1523
+ domInteractive,
1524
+ });
1525
+ }
1526
+ // Track Web Vitals if available
1527
+ this.trackWebVitals();
1528
+ }
1529
+ trackWebVitals() {
1530
+ // LCP (Largest Contentful Paint)
1531
+ if ('PerformanceObserver' in window) {
1532
+ try {
1533
+ const lcpObserver = new PerformanceObserver((entryList) => {
1534
+ const entries = entryList.getEntries();
1535
+ const lastEntry = entries[entries.length - 1];
1536
+ if (lastEntry) {
1537
+ this.track('performance', 'Web Vital - LCP', {
1538
+ metric: 'LCP',
1539
+ value: Math.round(lastEntry.startTime),
1540
+ });
1541
+ }
1542
+ });
1543
+ lcpObserver.observe({ type: 'largest-contentful-paint', buffered: true });
1544
+ this.observers.push(lcpObserver);
1545
+ }
1546
+ catch {
1547
+ // LCP not supported
1548
+ }
1549
+ // FID (First Input Delay)
1550
+ try {
1551
+ const fidObserver = new PerformanceObserver((entryList) => {
1552
+ const entries = entryList.getEntries();
1553
+ const firstEntry = entries[0];
1554
+ if (firstEntry) {
1555
+ this.track('performance', 'Web Vital - FID', {
1556
+ metric: 'FID',
1557
+ value: Math.round(firstEntry.processingStart - firstEntry.startTime),
1558
+ });
1559
+ }
1560
+ });
1561
+ fidObserver.observe({ type: 'first-input', buffered: true });
1562
+ this.observers.push(fidObserver);
1563
+ }
1564
+ catch {
1565
+ // FID not supported
1566
+ }
1567
+ // CLS (Cumulative Layout Shift)
1568
+ try {
1569
+ let clsValue = 0;
1570
+ const clsObserver = new PerformanceObserver((entryList) => {
1571
+ const entries = entryList.getEntries();
1572
+ entries.forEach((entry) => {
1573
+ if (!entry.hadRecentInput) {
1574
+ clsValue += entry.value || 0;
1575
+ }
1576
+ });
1577
+ });
1578
+ clsObserver.observe({ type: 'layout-shift', buffered: true });
1579
+ this.observers.push(clsObserver);
1580
+ // Report CLS after page is hidden
1581
+ this.boundClsVisibilityHandler = () => {
1582
+ if (document.visibilityState === 'hidden' && clsValue > 0) {
1583
+ this.track('performance', 'Web Vital - CLS', {
1584
+ metric: 'CLS',
1585
+ value: Math.round(clsValue * 1000) / 1000,
1586
+ });
1587
+ }
1588
+ };
1589
+ window.addEventListener('visibilitychange', this.boundClsVisibilityHandler, { once: true });
1590
+ }
1591
+ catch {
1592
+ // CLS not supported
1593
+ }
1594
+ }
1595
+ }
1596
+ }
1597
+
1598
+ /**
1599
+ * Clianta Tracking SDK - Popup Forms Plugin
1600
+ * @see SDK_VERSION in core/config.ts
1601
+ *
1602
+ * Auto-loads and displays lead capture popups based on triggers
1603
+ */
1604
+ /**
1605
+ * Popup Forms Plugin - Fetches and displays lead capture forms
1606
+ */
1607
+ class PopupFormsPlugin extends BasePlugin {
1608
+ constructor() {
1609
+ super(...arguments);
1610
+ this.name = 'popupForms';
1611
+ this.forms = [];
1612
+ this.shownForms = new Set();
1613
+ this.scrollHandler = null;
1614
+ this.exitHandler = null;
1615
+ }
1616
+ async init(tracker) {
1617
+ super.init(tracker);
1618
+ if (typeof window === 'undefined')
1619
+ return;
1620
+ // Load shown forms from storage
1621
+ this.loadShownForms();
1622
+ // Fetch active forms
1623
+ await this.fetchForms();
1624
+ // Setup triggers
1625
+ this.setupTriggers();
1626
+ }
1627
+ destroy() {
1628
+ this.removeTriggers();
1629
+ super.destroy();
1630
+ }
1631
+ loadShownForms() {
1632
+ try {
1633
+ const stored = localStorage.getItem('clianta_shown_forms');
1634
+ if (stored) {
1635
+ const data = JSON.parse(stored);
1636
+ this.shownForms = new Set(data.forms || []);
1637
+ }
1638
+ }
1639
+ catch (e) {
1640
+ // Ignore storage errors
1641
+ }
1642
+ }
1643
+ saveShownForms() {
1644
+ try {
1645
+ localStorage.setItem('clianta_shown_forms', JSON.stringify({
1646
+ forms: Array.from(this.shownForms),
1647
+ timestamp: Date.now(),
1648
+ }));
1649
+ }
1650
+ catch (e) {
1651
+ // Ignore storage errors
1652
+ }
1653
+ }
1654
+ async fetchForms() {
1655
+ if (!this.tracker)
1656
+ return;
1657
+ const config = this.tracker.getConfig();
1658
+ const workspaceId = this.tracker.getWorkspaceId();
1659
+ const apiEndpoint = config.apiEndpoint || 'https://api.clianta.online';
1660
+ try {
1661
+ const url = encodeURIComponent(window.location.href);
1662
+ const response = await fetch(`${apiEndpoint}/api/public/lead-forms/${workspaceId}?url=${url}`);
1663
+ if (!response.ok)
1664
+ return;
1665
+ const data = await response.json();
1666
+ if (data.success && Array.isArray(data.data)) {
1667
+ this.forms = data.data.filter((form) => this.shouldShowForm(form));
1668
+ }
1669
+ }
1670
+ catch (error) {
1671
+ console.error('[Clianta] Failed to fetch forms:', error);
1672
+ }
1673
+ }
1674
+ shouldShowForm(form) {
1675
+ // Check show frequency
1676
+ if (form.showFrequency === 'once_per_visitor') {
1677
+ if (this.shownForms.has(form._id))
1678
+ return false;
1679
+ }
1680
+ else if (form.showFrequency === 'once_per_session') {
1681
+ const sessionKey = `clianta_form_${form._id}_shown`;
1682
+ if (sessionStorage.getItem(sessionKey))
1683
+ return false;
1684
+ }
1685
+ return true;
1686
+ }
1687
+ setupTriggers() {
1688
+ this.forms.forEach(form => {
1689
+ switch (form.trigger.type) {
1690
+ case 'delay':
1691
+ setTimeout(() => this.showForm(form), (form.trigger.value || 5) * 1000);
1692
+ break;
1693
+ case 'scroll':
1694
+ this.setupScrollTrigger(form);
1695
+ break;
1696
+ case 'exit_intent':
1697
+ this.setupExitIntentTrigger(form);
1698
+ break;
1699
+ case 'click':
1700
+ this.setupClickTrigger(form);
1701
+ break;
1702
+ }
1703
+ });
1704
+ }
1705
+ setupScrollTrigger(form) {
1706
+ const threshold = form.trigger.value || 50;
1707
+ this.scrollHandler = () => {
1708
+ const scrollPercent = (window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100;
1709
+ if (scrollPercent >= threshold) {
1710
+ this.showForm(form);
1711
+ if (this.scrollHandler) {
1712
+ window.removeEventListener('scroll', this.scrollHandler);
1713
+ }
1714
+ }
1715
+ };
1716
+ window.addEventListener('scroll', this.scrollHandler, { passive: true });
1717
+ }
1718
+ setupExitIntentTrigger(form) {
1719
+ this.exitHandler = (e) => {
1720
+ if (e.clientY <= 0) {
1721
+ this.showForm(form);
1722
+ if (this.exitHandler) {
1723
+ document.removeEventListener('mouseout', this.exitHandler);
1724
+ }
1725
+ }
1726
+ };
1727
+ document.addEventListener('mouseout', this.exitHandler);
1728
+ }
1729
+ setupClickTrigger(form) {
1730
+ if (!form.trigger.selector)
1731
+ return;
1732
+ const elements = document.querySelectorAll(form.trigger.selector);
1733
+ elements.forEach(el => {
1734
+ el.addEventListener('click', () => this.showForm(form));
1735
+ });
1736
+ }
1737
+ removeTriggers() {
1738
+ if (this.scrollHandler) {
1739
+ window.removeEventListener('scroll', this.scrollHandler);
1740
+ }
1741
+ if (this.exitHandler) {
1742
+ document.removeEventListener('mouseout', this.exitHandler);
1743
+ }
1744
+ }
1745
+ async showForm(form) {
1746
+ // Check if already shown in this session
1747
+ if (!this.shouldShowForm(form))
1748
+ return;
1749
+ // Mark as shown
1750
+ this.shownForms.add(form._id);
1751
+ this.saveShownForms();
1752
+ sessionStorage.setItem(`clianta_form_${form._id}_shown`, 'true');
1753
+ // Track view
1754
+ await this.trackFormView(form._id);
1755
+ // Render form
1756
+ this.renderForm(form);
1757
+ }
1758
+ async trackFormView(formId) {
1759
+ if (!this.tracker)
1760
+ return;
1761
+ const config = this.tracker.getConfig();
1762
+ const apiEndpoint = config.apiEndpoint || 'https://api.clianta.online';
1763
+ try {
1764
+ await fetch(`${apiEndpoint}/api/public/lead-forms/${formId}/view`, {
1765
+ method: 'POST',
1766
+ headers: { 'Content-Type': 'application/json' },
1767
+ });
1768
+ }
1769
+ catch (e) {
1770
+ // Ignore tracking errors
1771
+ }
1772
+ }
1773
+ renderForm(form) {
1774
+ // Create overlay
1775
+ const overlay = document.createElement('div');
1776
+ overlay.id = `clianta-form-overlay-${form._id}`;
1777
+ overlay.style.cssText = `
1778
+ position: fixed;
1779
+ top: 0;
1780
+ left: 0;
1781
+ right: 0;
1782
+ bottom: 0;
1783
+ background: rgba(0, 0, 0, 0.5);
1784
+ z-index: 999998;
1785
+ display: flex;
1786
+ align-items: center;
1787
+ justify-content: center;
1788
+ opacity: 0;
1789
+ transition: opacity 0.3s ease;
1790
+ `;
1791
+ // Create form container
1792
+ const container = document.createElement('div');
1793
+ container.id = `clianta-form-${form._id}`;
1794
+ const style = form.style || {};
1795
+ container.style.cssText = `
1796
+ background: ${style.backgroundColor || '#FFFFFF'};
1797
+ border-radius: ${style.borderRadius || 12}px;
1798
+ padding: 24px;
1799
+ max-width: 400px;
1800
+ width: 90%;
1801
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
1802
+ transform: translateY(20px);
1803
+ opacity: 0;
1804
+ transition: all 0.3s ease;
1805
+ `;
1806
+ // Build form using safe DOM APIs (no innerHTML for user content)
1807
+ this.buildFormDOM(form, container);
1808
+ overlay.appendChild(container);
1809
+ document.body.appendChild(overlay);
1810
+ // Animate in
1811
+ requestAnimationFrame(() => {
1812
+ overlay.style.opacity = '1';
1813
+ container.style.transform = 'translateY(0)';
1814
+ container.style.opacity = '1';
1815
+ });
1816
+ // Setup event listeners
1817
+ this.setupFormEvents(form, overlay, container);
1818
+ }
1819
+ /**
1820
+ * Escape HTML to prevent XSS - used only for static structure
1821
+ */
1822
+ escapeHTML(str) {
1823
+ const div = document.createElement('div');
1824
+ div.textContent = str;
1825
+ return div.innerHTML;
1826
+ }
1827
+ /**
1828
+ * Build form using safe DOM APIs (prevents XSS)
1829
+ */
1830
+ buildFormDOM(form, container) {
1831
+ const style = form.style || {};
1832
+ const primaryColor = style.primaryColor || '#10B981';
1833
+ const textColor = style.textColor || '#18181B';
1834
+ // Close button
1835
+ const closeBtn = document.createElement('button');
1836
+ closeBtn.id = 'clianta-form-close';
1837
+ closeBtn.style.cssText = `
1838
+ position: absolute;
1839
+ top: 12px;
1840
+ right: 12px;
1841
+ background: none;
1842
+ border: none;
1843
+ font-size: 20px;
1844
+ cursor: pointer;
1845
+ color: #71717A;
1846
+ padding: 4px;
1847
+ `;
1848
+ closeBtn.textContent = '×';
1849
+ container.appendChild(closeBtn);
1850
+ // Headline
1851
+ const headline = document.createElement('h2');
1852
+ headline.style.cssText = `font-size: 20px; font-weight: 700; margin-bottom: 8px; color: ${this.escapeHTML(textColor)};`;
1853
+ headline.textContent = form.headline || 'Stay in touch';
1854
+ container.appendChild(headline);
1855
+ // Subheadline
1856
+ const subheadline = document.createElement('p');
1857
+ subheadline.style.cssText = 'font-size: 14px; color: #71717A; margin-bottom: 16px;';
1858
+ subheadline.textContent = form.subheadline || 'Get the latest updates';
1859
+ container.appendChild(subheadline);
1860
+ // Form element
1861
+ const formElement = document.createElement('form');
1862
+ formElement.id = 'clianta-form-element';
1863
+ // Build fields
1864
+ form.fields.forEach(field => {
1865
+ const fieldWrapper = document.createElement('div');
1866
+ fieldWrapper.style.marginBottom = '12px';
1867
+ if (field.type === 'checkbox') {
1868
+ // Checkbox layout
1869
+ const label = document.createElement('label');
1870
+ label.style.cssText = `display: flex; align-items: center; gap: 8px; font-size: 14px; color: ${this.escapeHTML(textColor)}; cursor: pointer;`;
1871
+ const input = document.createElement('input');
1872
+ input.type = 'checkbox';
1873
+ input.name = field.name;
1874
+ if (field.required)
1875
+ input.required = true;
1876
+ input.style.cssText = 'width: 16px; height: 16px;';
1877
+ label.appendChild(input);
1878
+ const labelText = document.createTextNode(field.label + ' ');
1879
+ label.appendChild(labelText);
1880
+ if (field.required) {
1881
+ const requiredMark = document.createElement('span');
1882
+ requiredMark.style.color = '#EF4444';
1883
+ requiredMark.textContent = '*';
1884
+ label.appendChild(requiredMark);
1885
+ }
1886
+ fieldWrapper.appendChild(label);
1887
+ }
1888
+ else {
1889
+ // Label
1890
+ const label = document.createElement('label');
1891
+ label.style.cssText = `display: block; font-size: 14px; font-weight: 500; margin-bottom: 4px; color: ${this.escapeHTML(textColor)};`;
1892
+ label.textContent = field.label + ' ';
1893
+ if (field.required) {
1894
+ const requiredMark = document.createElement('span');
1895
+ requiredMark.style.color = '#EF4444';
1896
+ requiredMark.textContent = '*';
1897
+ label.appendChild(requiredMark);
1898
+ }
1899
+ fieldWrapper.appendChild(label);
1900
+ // Input/Textarea/Select
1901
+ if (field.type === 'textarea') {
1902
+ const textarea = document.createElement('textarea');
1903
+ textarea.name = field.name;
1904
+ if (field.placeholder)
1905
+ textarea.placeholder = field.placeholder;
1906
+ if (field.required)
1907
+ textarea.required = true;
1908
+ textarea.style.cssText = 'width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; resize: vertical; min-height: 80px; box-sizing: border-box;';
1909
+ fieldWrapper.appendChild(textarea);
1910
+ }
1911
+ else if (field.type === 'select') {
1912
+ const select = document.createElement('select');
1913
+ select.name = field.name;
1914
+ if (field.required)
1915
+ select.required = true;
1916
+ select.style.cssText = 'width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box; background: white; cursor: pointer;';
1917
+ // Add placeholder option
1918
+ if (field.placeholder) {
1919
+ const placeholderOption = document.createElement('option');
1920
+ placeholderOption.value = '';
1921
+ placeholderOption.textContent = field.placeholder;
1922
+ placeholderOption.disabled = true;
1923
+ placeholderOption.selected = true;
1924
+ select.appendChild(placeholderOption);
1925
+ }
1926
+ // Add options from field.options array if provided
1927
+ if (field.options && Array.isArray(field.options)) {
1928
+ field.options.forEach((opt) => {
1929
+ const option = document.createElement('option');
1930
+ if (typeof opt === 'string') {
1931
+ option.value = opt;
1932
+ option.textContent = opt;
1933
+ }
1934
+ else {
1935
+ option.value = opt.value;
1936
+ option.textContent = opt.label;
1937
+ }
1938
+ select.appendChild(option);
1939
+ });
1940
+ }
1941
+ fieldWrapper.appendChild(select);
1942
+ }
1943
+ else {
1944
+ const input = document.createElement('input');
1945
+ input.type = field.type;
1946
+ input.name = field.name;
1947
+ if (field.placeholder)
1948
+ input.placeholder = field.placeholder;
1949
+ if (field.required)
1950
+ input.required = true;
1951
+ input.style.cssText = 'width: 100%; padding: 8px 12px; border: 1px solid #E4E4E7; border-radius: 6px; font-size: 14px; box-sizing: border-box;';
1952
+ fieldWrapper.appendChild(input);
1953
+ }
1954
+ }
1955
+ formElement.appendChild(fieldWrapper);
1956
+ });
1957
+ // Submit button
1958
+ const submitBtn = document.createElement('button');
1959
+ submitBtn.type = 'submit';
1960
+ submitBtn.style.cssText = `
1961
+ width: 100%;
1962
+ padding: 10px 16px;
1963
+ background: ${this.escapeHTML(primaryColor)};
1964
+ color: white;
1965
+ border: none;
1966
+ border-radius: 6px;
1967
+ font-size: 14px;
1968
+ font-weight: 500;
1969
+ cursor: pointer;
1970
+ margin-top: 8px;
1971
+ `;
1972
+ submitBtn.textContent = form.submitButtonText || 'Subscribe';
1973
+ formElement.appendChild(submitBtn);
1974
+ container.appendChild(formElement);
1975
+ }
1976
+ setupFormEvents(form, overlay, container) {
1977
+ // Close button
1978
+ const closeBtn = container.querySelector('#clianta-form-close');
1979
+ if (closeBtn) {
1980
+ closeBtn.addEventListener('click', () => this.closeForm(form._id, overlay, container));
1981
+ }
1982
+ // Overlay click
1983
+ overlay.addEventListener('click', (e) => {
1984
+ if (e.target === overlay) {
1985
+ this.closeForm(form._id, overlay, container);
1986
+ }
1987
+ });
1988
+ // Form submit
1989
+ const formElement = container.querySelector('#clianta-form-element');
1990
+ if (formElement) {
1991
+ formElement.addEventListener('submit', async (e) => {
1992
+ e.preventDefault();
1993
+ await this.handleSubmit(form, formElement, container);
1994
+ });
1995
+ }
1996
+ }
1997
+ closeForm(formId, overlay, container) {
1998
+ container.style.transform = 'translateY(20px)';
1999
+ container.style.opacity = '0';
2000
+ overlay.style.opacity = '0';
2001
+ setTimeout(() => {
2002
+ overlay.remove();
2003
+ }, 300);
2004
+ }
2005
+ async handleSubmit(form, formElement, container) {
2006
+ if (!this.tracker)
2007
+ return;
2008
+ const config = this.tracker.getConfig();
2009
+ const apiEndpoint = config.apiEndpoint || 'https://api.clianta.online';
2010
+ const visitorId = this.tracker.getVisitorId();
2011
+ // Collect form data
2012
+ const formData = new FormData(formElement);
2013
+ const data = {};
2014
+ formData.forEach((value, key) => {
2015
+ data[key] = value;
2016
+ });
2017
+ // Disable submit button
2018
+ const submitBtn = formElement.querySelector('button[type="submit"]');
2019
+ if (submitBtn) {
2020
+ submitBtn.disabled = true;
2021
+ submitBtn.innerHTML = 'Submitting...';
2022
+ }
2023
+ try {
2024
+ const response = await fetch(`${apiEndpoint}/api/public/lead-forms/${form._id}/submit`, {
2025
+ method: 'POST',
2026
+ headers: { 'Content-Type': 'application/json' },
2027
+ body: JSON.stringify({
2028
+ visitorId,
2029
+ data,
2030
+ url: window.location.href,
2031
+ }),
2032
+ });
2033
+ const result = await response.json();
2034
+ if (result.success) {
2035
+ // Show success message using safe DOM APIs
2036
+ container.innerHTML = '';
2037
+ const successWrapper = document.createElement('div');
2038
+ successWrapper.style.cssText = 'text-align: center; padding: 20px;';
2039
+ const iconWrapper = document.createElement('div');
2040
+ iconWrapper.style.cssText = 'width: 48px; height: 48px; background: #10B981; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center;';
2041
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2042
+ svg.setAttribute('width', '24');
2043
+ svg.setAttribute('height', '24');
2044
+ svg.setAttribute('viewBox', '0 0 24 24');
2045
+ svg.setAttribute('fill', 'none');
2046
+ svg.setAttribute('stroke', 'white');
2047
+ svg.setAttribute('stroke-width', '2');
2048
+ const polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
2049
+ polyline.setAttribute('points', '20 6 9 17 4 12');
2050
+ svg.appendChild(polyline);
2051
+ iconWrapper.appendChild(svg);
2052
+ const message = document.createElement('p');
2053
+ message.style.cssText = 'font-size: 16px; font-weight: 500; color: #18181B;';
2054
+ message.textContent = form.successMessage || 'Thank you!';
2055
+ successWrapper.appendChild(iconWrapper);
2056
+ successWrapper.appendChild(message);
2057
+ container.appendChild(successWrapper);
2058
+ // Track identify
2059
+ if (data.email) {
2060
+ this.tracker?.identify(data.email, data);
2061
+ }
2062
+ // Redirect if configured
2063
+ if (form.redirectUrl) {
2064
+ setTimeout(() => {
2065
+ window.location.href = form.redirectUrl;
2066
+ }, 1500);
2067
+ }
2068
+ // Close after delay
2069
+ setTimeout(() => {
2070
+ const overlay = document.getElementById(`clianta-form-overlay-${form._id}`);
2071
+ if (overlay) {
2072
+ this.closeForm(form._id, overlay, container);
2073
+ }
2074
+ }, 2000);
2075
+ }
2076
+ }
2077
+ catch (error) {
2078
+ console.error('[Clianta] Form submit error:', error);
2079
+ if (submitBtn) {
2080
+ submitBtn.disabled = false;
2081
+ submitBtn.innerHTML = form.submitButtonText || 'Subscribe';
2082
+ }
2083
+ }
2084
+ }
2085
+ }
2086
+
2087
+ /**
2088
+ * Clianta SDK - Plugins Index
2089
+ * Version is defined in core/config.ts as SDK_VERSION
2090
+ */
2091
+ /**
2092
+ * Get plugin instance by name
2093
+ */
2094
+ function getPlugin(name) {
2095
+ switch (name) {
2096
+ case 'pageView':
2097
+ return new PageViewPlugin();
2098
+ case 'scroll':
2099
+ return new ScrollPlugin();
2100
+ case 'forms':
2101
+ return new FormsPlugin();
2102
+ case 'clicks':
2103
+ return new ClicksPlugin();
2104
+ case 'engagement':
2105
+ return new EngagementPlugin();
2106
+ case 'downloads':
2107
+ return new DownloadsPlugin();
2108
+ case 'exitIntent':
2109
+ return new ExitIntentPlugin();
2110
+ case 'errors':
2111
+ return new ErrorsPlugin();
2112
+ case 'performance':
2113
+ return new PerformancePlugin();
2114
+ case 'popupForms':
2115
+ return new PopupFormsPlugin();
2116
+ default:
2117
+ throw new Error(`Unknown plugin: ${name}`);
2118
+ }
2119
+ }
2120
+
2121
+ /**
2122
+ * Clianta SDK - Consent Storage
2123
+ * Handles persistence of consent state
2124
+ * @see SDK_VERSION in core/config.ts
2125
+ */
2126
+ const CONSENT_VERSION = 1;
2127
+ /**
2128
+ * Save consent state to storage
2129
+ */
2130
+ function saveConsent(state) {
2131
+ try {
2132
+ if (typeof localStorage === 'undefined')
2133
+ return false;
2134
+ const stored = {
2135
+ state,
2136
+ timestamp: Date.now(),
2137
+ version: CONSENT_VERSION,
2138
+ };
2139
+ localStorage.setItem(STORAGE_KEYS.CONSENT, JSON.stringify(stored));
2140
+ return true;
2141
+ }
2142
+ catch {
2143
+ return false;
2144
+ }
2145
+ }
2146
+ /**
2147
+ * Load consent state from storage
2148
+ */
2149
+ function loadConsent() {
2150
+ try {
2151
+ if (typeof localStorage === 'undefined')
2152
+ return null;
2153
+ const stored = localStorage.getItem(STORAGE_KEYS.CONSENT);
2154
+ if (!stored)
2155
+ return null;
2156
+ const parsed = JSON.parse(stored);
2157
+ // Validate version
2158
+ if (parsed.version !== CONSENT_VERSION) {
2159
+ clearConsent();
2160
+ return null;
2161
+ }
2162
+ return parsed;
2163
+ }
2164
+ catch {
2165
+ return null;
2166
+ }
2167
+ }
2168
+ /**
2169
+ * Clear consent state from storage
2170
+ */
2171
+ function clearConsent() {
2172
+ try {
2173
+ if (typeof localStorage === 'undefined')
2174
+ return false;
2175
+ localStorage.removeItem(STORAGE_KEYS.CONSENT);
2176
+ return true;
2177
+ }
2178
+ catch {
2179
+ return false;
2180
+ }
2181
+ }
2182
+ /**
2183
+ * Check if consent has been explicitly set
2184
+ */
2185
+ function hasStoredConsent() {
2186
+ return loadConsent() !== null;
2187
+ }
2188
+
2189
+ /**
2190
+ * Clianta SDK - Consent Manager
2191
+ * Manages consent state and event buffering for GDPR/CCPA compliance
2192
+ * @see SDK_VERSION in core/config.ts
2193
+ */
2194
+ /** Maximum events to buffer while waiting for consent */
2195
+ const MAX_BUFFER_SIZE = 100;
2196
+ /**
2197
+ * Manages user consent state for tracking
2198
+ */
2199
+ class ConsentManager {
2200
+ constructor(config = {}) {
2201
+ this.eventBuffer = [];
2202
+ this.callbacks = [];
2203
+ this.hasExplicitConsent = false;
2204
+ this.config = {
2205
+ defaultConsent: { analytics: true, marketing: false, personalization: false },
2206
+ waitForConsent: false,
2207
+ storageKey: 'mb_consent',
2208
+ ...config,
2209
+ };
2210
+ // Load stored consent or use default
2211
+ const stored = loadConsent();
2212
+ if (stored) {
2213
+ this.state = stored.state;
2214
+ this.hasExplicitConsent = true;
2215
+ logger.debug('Loaded stored consent:', this.state);
2216
+ }
2217
+ else {
2218
+ this.state = this.config.defaultConsent || { analytics: true };
2219
+ this.hasExplicitConsent = false;
2220
+ logger.debug('Using default consent:', this.state);
2221
+ }
2222
+ // Register callback if provided
2223
+ if (config.onConsentChange) {
2224
+ this.callbacks.push(config.onConsentChange);
2225
+ }
2226
+ }
2227
+ /**
2228
+ * Grant consent for specified categories
2229
+ */
2230
+ grant(categories) {
2231
+ const previous = { ...this.state };
2232
+ this.state = { ...this.state, ...categories };
2233
+ this.hasExplicitConsent = true;
2234
+ saveConsent(this.state);
2235
+ logger.info('Consent granted:', categories);
2236
+ this.notifyChange(previous);
2237
+ }
2238
+ /**
2239
+ * Revoke consent for specified categories
2240
+ */
2241
+ revoke(categories) {
2242
+ const previous = { ...this.state };
2243
+ for (const category of categories) {
2244
+ this.state[category] = false;
2245
+ }
2246
+ this.hasExplicitConsent = true;
2247
+ saveConsent(this.state);
2248
+ logger.info('Consent revoked:', categories);
2249
+ this.notifyChange(previous);
2250
+ }
2251
+ /**
2252
+ * Update entire consent state
2253
+ */
2254
+ update(state) {
2255
+ const previous = { ...this.state };
2256
+ this.state = { ...state };
2257
+ this.hasExplicitConsent = true;
2258
+ saveConsent(this.state);
2259
+ logger.info('Consent updated:', this.state);
2260
+ this.notifyChange(previous);
2261
+ }
2262
+ /**
2263
+ * Reset consent to default (clear stored consent)
2264
+ */
2265
+ reset() {
2266
+ const previous = { ...this.state };
2267
+ this.state = this.config.defaultConsent || { analytics: true };
2268
+ this.hasExplicitConsent = false;
2269
+ this.eventBuffer = [];
2270
+ clearConsent();
2271
+ logger.info('Consent reset to defaults');
2272
+ this.notifyChange(previous);
2273
+ }
2274
+ /**
2275
+ * Get current consent state
2276
+ */
2277
+ getState() {
2278
+ return { ...this.state };
2279
+ }
2280
+ /**
2281
+ * Check if a specific consent category is granted
2282
+ */
2283
+ hasConsent(category) {
2284
+ return this.state[category] === true;
2285
+ }
2286
+ /**
2287
+ * Check if analytics consent is granted (most common check)
2288
+ */
2289
+ canTrack() {
2290
+ // If waiting for consent and no explicit consent given, cannot track
2291
+ if (this.config.waitForConsent && !this.hasExplicitConsent) {
2292
+ return false;
2293
+ }
2294
+ return this.state.analytics === true;
2295
+ }
2296
+ /**
2297
+ * Check if explicit consent has been given
2298
+ */
2299
+ hasExplicit() {
2300
+ return this.hasExplicitConsent;
2301
+ }
2302
+ /**
2303
+ * Check if there's stored consent
2304
+ */
2305
+ hasStored() {
2306
+ return hasStoredConsent();
2307
+ }
2308
+ /**
2309
+ * Buffer an event (for waitForConsent mode)
2310
+ */
2311
+ bufferEvent(event) {
2312
+ // Prevent unbounded buffer growth
2313
+ if (this.eventBuffer.length >= MAX_BUFFER_SIZE) {
2314
+ logger.warn('Consent event buffer full, dropping oldest event');
2315
+ this.eventBuffer.shift();
2316
+ }
2317
+ this.eventBuffer.push(event);
2318
+ logger.debug('Event buffered (waiting for consent):', event.eventName);
2319
+ }
2320
+ /**
2321
+ * Get and clear buffered events
2322
+ */
2323
+ flushBuffer() {
2324
+ const events = [...this.eventBuffer];
2325
+ this.eventBuffer = [];
2326
+ if (events.length > 0) {
2327
+ logger.debug(`Flushing ${events.length} buffered events`);
2328
+ }
2329
+ return events;
2330
+ }
2331
+ /**
2332
+ * Get buffered event count
2333
+ */
2334
+ getBufferSize() {
2335
+ return this.eventBuffer.length;
2336
+ }
2337
+ /**
2338
+ * Register a consent change callback
2339
+ */
2340
+ onChange(callback) {
2341
+ this.callbacks.push(callback);
2342
+ // Return unsubscribe function
2343
+ return () => {
2344
+ const index = this.callbacks.indexOf(callback);
2345
+ if (index > -1) {
2346
+ this.callbacks.splice(index, 1);
2347
+ }
2348
+ };
2349
+ }
2350
+ /**
2351
+ * Notify all callbacks of consent change
2352
+ */
2353
+ notifyChange(previous) {
2354
+ for (const callback of this.callbacks) {
2355
+ try {
2356
+ callback(this.state, previous);
2357
+ }
2358
+ catch (error) {
2359
+ logger.error('Consent change callback error:', error);
2360
+ }
2361
+ }
2362
+ }
2363
+ }
2364
+
2365
+ /**
2366
+ * Clianta SDK - Main Tracker Class
2367
+ * @see SDK_VERSION in core/config.ts
2368
+ */
2369
+ /**
2370
+ * Main Clianta Tracker Class
2371
+ */
2372
+ class Tracker {
2373
+ constructor(workspaceId, userConfig = {}) {
2374
+ this.plugins = [];
2375
+ this.isInitialized = false;
2376
+ /** Pending identify retry on next flush */
2377
+ this.pendingIdentify = null;
2378
+ if (!workspaceId) {
2379
+ throw new Error('[Clianta] Workspace ID is required');
2380
+ }
2381
+ this.workspaceId = workspaceId;
2382
+ this.config = mergeConfig(userConfig);
2383
+ // Setup debug mode
2384
+ logger.enabled = this.config.debug;
2385
+ logger.info(`Initializing SDK v${SDK_VERSION}`, { workspaceId });
2386
+ // Initialize consent manager
2387
+ this.consentManager = new ConsentManager({
2388
+ ...this.config.consent,
2389
+ onConsentChange: (state, previous) => {
2390
+ this.onConsentChange(state, previous);
2391
+ },
2392
+ });
2393
+ // Initialize transport and queue
2394
+ this.transport = new Transport({ apiEndpoint: this.config.apiEndpoint });
2395
+ this.queue = new EventQueue(this.transport, {
2396
+ batchSize: this.config.batchSize,
2397
+ flushInterval: this.config.flushInterval,
2398
+ });
2399
+ // Get or create visitor and session IDs based on mode
2400
+ this.visitorId = this.createVisitorId();
2401
+ this.sessionId = this.createSessionId();
2402
+ logger.debug('IDs created', { visitorId: this.visitorId, sessionId: this.sessionId });
2403
+ // Initialize plugins
2404
+ this.initPlugins();
2405
+ this.isInitialized = true;
2406
+ logger.info('SDK initialized successfully');
2407
+ }
2408
+ /**
2409
+ * Create visitor ID based on storage mode
2410
+ */
2411
+ createVisitorId() {
2412
+ // Anonymous mode: use temporary ID until consent
2413
+ if (this.config.consent.anonymousMode && !this.consentManager.hasExplicit()) {
2414
+ const key = STORAGE_KEYS.VISITOR_ID + '_anon';
2415
+ let anonId = getSessionStorage(key);
2416
+ if (!anonId) {
2417
+ anonId = 'anon_' + generateUUID();
2418
+ setSessionStorage(key, anonId);
2419
+ }
2420
+ return anonId;
2421
+ }
2422
+ // Cookie-less mode: use sessionStorage only
2423
+ if (this.config.cookielessMode) {
2424
+ let visitorId = getSessionStorage(STORAGE_KEYS.VISITOR_ID);
2425
+ if (!visitorId) {
2426
+ visitorId = generateUUID();
2427
+ setSessionStorage(STORAGE_KEYS.VISITOR_ID, visitorId);
2428
+ }
2429
+ return visitorId;
2430
+ }
2431
+ // Normal mode
2432
+ return getOrCreateVisitorId(this.config.useCookies);
2433
+ }
2434
+ /**
2435
+ * Create session ID
2436
+ */
2437
+ createSessionId() {
2438
+ return getOrCreateSessionId(this.config.sessionTimeout);
2439
+ }
2440
+ /**
2441
+ * Handle consent state changes
2442
+ */
2443
+ onConsentChange(state, previous) {
2444
+ logger.debug('Consent changed:', { from: previous, to: state });
2445
+ // If analytics consent was just granted
2446
+ if (state.analytics && !previous.analytics) {
2447
+ // Upgrade from anonymous ID to persistent ID
2448
+ if (this.config.consent.anonymousMode) {
2449
+ this.visitorId = getOrCreateVisitorId(this.config.useCookies);
2450
+ logger.info('Upgraded from anonymous to persistent visitor ID');
2451
+ }
2452
+ // Flush buffered events
2453
+ const buffered = this.consentManager.flushBuffer();
2454
+ for (const event of buffered) {
2455
+ // Update event with new visitor ID
2456
+ event.visitorId = this.visitorId;
2457
+ this.queue.push(event);
2458
+ }
2459
+ }
2460
+ }
2461
+ /**
2462
+ * Initialize enabled plugins
2463
+ * Handles both sync and async plugin init methods
2464
+ */
2465
+ initPlugins() {
2466
+ const pluginsToLoad = this.config.plugins;
2467
+ // Skip pageView plugin if autoPageView is disabled
2468
+ const filteredPlugins = this.config.autoPageView
2469
+ ? pluginsToLoad
2470
+ : pluginsToLoad.filter((p) => p !== 'pageView');
2471
+ for (const pluginName of filteredPlugins) {
2472
+ try {
2473
+ const plugin = getPlugin(pluginName);
2474
+ // Handle both sync and async init (fire-and-forget for async)
2475
+ const result = plugin.init(this);
2476
+ if (result instanceof Promise) {
2477
+ result.catch((error) => {
2478
+ logger.error(`Async plugin init failed: ${pluginName}`, error);
2479
+ });
2480
+ }
2481
+ this.plugins.push(plugin);
2482
+ logger.debug(`Plugin loaded: ${pluginName}`);
2483
+ }
2484
+ catch (error) {
2485
+ logger.error(`Failed to load plugin: ${pluginName}`, error);
2486
+ }
2487
+ }
2488
+ }
2489
+ /**
2490
+ * Track a custom event
2491
+ */
2492
+ track(eventType, eventName, properties = {}) {
2493
+ if (!this.isInitialized) {
2494
+ logger.warn('SDK not initialized, event dropped');
2495
+ return;
2496
+ }
2497
+ const event = {
2498
+ workspaceId: this.workspaceId,
2499
+ visitorId: this.visitorId,
2500
+ sessionId: this.sessionId,
2501
+ eventType: eventType,
2502
+ eventName,
2503
+ url: typeof window !== 'undefined' ? window.location.href : '',
2504
+ referrer: typeof document !== 'undefined' ? document.referrer || undefined : undefined,
2505
+ properties,
2506
+ device: getDeviceInfo(),
2507
+ ...getUTMParams(),
2508
+ timestamp: new Date().toISOString(),
2509
+ sdkVersion: SDK_VERSION,
2510
+ };
2511
+ // Check consent before tracking
2512
+ if (!this.consentManager.canTrack()) {
2513
+ // Buffer event for later if waitForConsent is enabled
2514
+ if (this.config.consent.waitForConsent) {
2515
+ this.consentManager.bufferEvent(event);
2516
+ return;
2517
+ }
2518
+ // Otherwise drop the event
2519
+ logger.debug('Event dropped (no consent):', eventName);
2520
+ return;
2521
+ }
2522
+ this.queue.push(event);
2523
+ logger.debug('Event tracked:', eventName, properties);
2524
+ }
2525
+ /**
2526
+ * Track a page view
2527
+ */
2528
+ page(name, properties = {}) {
2529
+ const pageName = name || (typeof document !== 'undefined' ? document.title : 'Page View');
2530
+ this.track('page_view', pageName, {
2531
+ ...properties,
2532
+ path: typeof window !== 'undefined' ? window.location.pathname : '',
2533
+ });
2534
+ }
2535
+ /**
2536
+ * Identify a visitor
2537
+ */
2538
+ async identify(email, traits = {}) {
2539
+ if (!email) {
2540
+ logger.warn('Email is required for identification');
2541
+ return;
2542
+ }
2543
+ logger.info('Identifying visitor:', email);
2544
+ const result = await this.transport.sendIdentify({
2545
+ workspaceId: this.workspaceId,
2546
+ visitorId: this.visitorId,
2547
+ email,
2548
+ properties: traits,
2549
+ });
2550
+ if (result.success) {
2551
+ logger.info('Visitor identified successfully');
2552
+ this.pendingIdentify = null;
2553
+ }
2554
+ else {
2555
+ logger.error('Failed to identify visitor:', result.error);
2556
+ // Store for retry on next flush
2557
+ this.pendingIdentify = { email, traits };
2558
+ }
2559
+ }
2560
+ /**
2561
+ * Retry pending identify call
2562
+ */
2563
+ async retryPendingIdentify() {
2564
+ if (!this.pendingIdentify)
2565
+ return;
2566
+ const { email, traits } = this.pendingIdentify;
2567
+ this.pendingIdentify = null;
2568
+ await this.identify(email, traits);
2569
+ }
2570
+ /**
2571
+ * Update consent state
2572
+ */
2573
+ consent(state) {
2574
+ this.consentManager.update(state);
2575
+ }
2576
+ /**
2577
+ * Get current consent state
2578
+ */
2579
+ getConsentState() {
2580
+ return this.consentManager.getState();
2581
+ }
2582
+ /**
2583
+ * Toggle debug mode
2584
+ */
2585
+ debug(enabled) {
2586
+ logger.enabled = enabled;
2587
+ logger.info(`Debug mode ${enabled ? 'enabled' : 'disabled'}`);
2588
+ }
2589
+ /**
2590
+ * Get visitor ID
2591
+ */
2592
+ getVisitorId() {
2593
+ return this.visitorId;
2594
+ }
2595
+ /**
2596
+ * Get session ID
2597
+ */
2598
+ getSessionId() {
2599
+ return this.sessionId;
2600
+ }
2601
+ /**
2602
+ * Get workspace ID
2603
+ */
2604
+ getWorkspaceId() {
2605
+ return this.workspaceId;
2606
+ }
2607
+ /**
2608
+ * Get current configuration
2609
+ */
2610
+ getConfig() {
2611
+ return { ...this.config };
2612
+ }
2613
+ /**
2614
+ * Force flush event queue
2615
+ */
2616
+ async flush() {
2617
+ await this.retryPendingIdentify();
2618
+ await this.queue.flush();
2619
+ }
2620
+ /**
2621
+ * Reset visitor and session (for logout)
2622
+ */
2623
+ reset() {
2624
+ logger.info('Resetting visitor data');
2625
+ resetIds(this.config.useCookies);
2626
+ this.visitorId = this.createVisitorId();
2627
+ this.sessionId = this.createSessionId();
2628
+ this.queue.clear();
2629
+ }
2630
+ /**
2631
+ * Delete all stored user data (GDPR right-to-erasure)
2632
+ */
2633
+ deleteData() {
2634
+ logger.info('Deleting all user data (GDPR request)');
2635
+ // Clear queue
2636
+ this.queue.clear();
2637
+ // Reset consent
2638
+ this.consentManager.reset();
2639
+ // Clear all stored IDs
2640
+ resetIds(this.config.useCookies);
2641
+ // Clear session storage items
2642
+ if (typeof sessionStorage !== 'undefined') {
2643
+ try {
2644
+ sessionStorage.removeItem(STORAGE_KEYS.VISITOR_ID);
2645
+ sessionStorage.removeItem(STORAGE_KEYS.VISITOR_ID + '_anon');
2646
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_ID);
2647
+ sessionStorage.removeItem(STORAGE_KEYS.SESSION_TIMESTAMP);
2648
+ }
2649
+ catch {
2650
+ // Ignore errors
2651
+ }
2652
+ }
2653
+ // Clear localStorage items
2654
+ if (typeof localStorage !== 'undefined') {
2655
+ try {
2656
+ localStorage.removeItem(STORAGE_KEYS.VISITOR_ID);
2657
+ localStorage.removeItem(STORAGE_KEYS.CONSENT);
2658
+ localStorage.removeItem(STORAGE_KEYS.EVENT_QUEUE);
2659
+ }
2660
+ catch {
2661
+ // Ignore errors
2662
+ }
2663
+ }
2664
+ // Generate new IDs
2665
+ this.visitorId = this.createVisitorId();
2666
+ this.sessionId = this.createSessionId();
2667
+ logger.info('All user data deleted');
2668
+ }
2669
+ /**
2670
+ * Destroy tracker and cleanup
2671
+ */
2672
+ async destroy() {
2673
+ logger.info('Destroying tracker');
2674
+ // Flush any remaining events (await to ensure completion)
2675
+ await this.queue.flush();
2676
+ // Destroy plugins
2677
+ for (const plugin of this.plugins) {
2678
+ if (plugin.destroy) {
2679
+ plugin.destroy();
2680
+ }
2681
+ }
2682
+ this.plugins = [];
2683
+ // Destroy queue
2684
+ this.queue.destroy();
2685
+ this.isInitialized = false;
2686
+ }
2687
+ }
2688
+
2689
+ /**
2690
+ * Clianta SDK - Event Triggers Manager
2691
+ * Manages event-driven automation and email notifications
2692
+ */
2693
+ /**
2694
+ * Event Triggers Manager
2695
+ * Handles event-driven automation based on CRM actions
2696
+ *
2697
+ * Similar to:
2698
+ * - Salesforce: Process Builder, Flow Automation
2699
+ * - HubSpot: Workflows, Email Sequences
2700
+ * - Pipedrive: Workflow Automation
2701
+ */
2702
+ class EventTriggersManager {
2703
+ constructor(apiEndpoint, workspaceId, authToken) {
2704
+ this.triggers = new Map();
2705
+ this.listeners = new Map();
2706
+ this.apiEndpoint = apiEndpoint;
2707
+ this.workspaceId = workspaceId;
2708
+ this.authToken = authToken;
2709
+ }
2710
+ /**
2711
+ * Set authentication token
2712
+ */
2713
+ setAuthToken(token) {
2714
+ this.authToken = token;
2715
+ }
2716
+ /**
2717
+ * Make authenticated API request
2718
+ */
2719
+ async request(endpoint, options = {}) {
2720
+ const url = `${this.apiEndpoint}${endpoint}`;
2721
+ const headers = {
2722
+ 'Content-Type': 'application/json',
2723
+ ...(options.headers || {}),
2724
+ };
2725
+ if (this.authToken) {
2726
+ headers['Authorization'] = `Bearer ${this.authToken}`;
2727
+ }
2728
+ try {
2729
+ const response = await fetch(url, {
2730
+ ...options,
2731
+ headers,
2732
+ });
2733
+ const data = await response.json();
2734
+ if (!response.ok) {
2735
+ return {
2736
+ success: false,
2737
+ error: data.message || 'Request failed',
2738
+ status: response.status,
2739
+ };
2740
+ }
2741
+ return {
2742
+ success: true,
2743
+ data: data.data || data,
2744
+ status: response.status,
2745
+ };
2746
+ }
2747
+ catch (error) {
2748
+ return {
2749
+ success: false,
2750
+ error: error instanceof Error ? error.message : 'Network error',
2751
+ status: 0,
2752
+ };
2753
+ }
2754
+ }
2755
+ // ============================================
2756
+ // TRIGGER MANAGEMENT
2757
+ // ============================================
2758
+ /**
2759
+ * Get all event triggers
2760
+ */
2761
+ async getTriggers() {
2762
+ return this.request(`/api/workspaces/${this.workspaceId}/triggers`);
2763
+ }
2764
+ /**
2765
+ * Get a single trigger by ID
2766
+ */
2767
+ async getTrigger(triggerId) {
2768
+ return this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`);
2769
+ }
2770
+ /**
2771
+ * Create a new event trigger
2772
+ */
2773
+ async createTrigger(trigger) {
2774
+ const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers`, {
2775
+ method: 'POST',
2776
+ body: JSON.stringify(trigger),
2777
+ });
2778
+ // Cache the trigger locally if successful
2779
+ if (result.success && result.data?._id) {
2780
+ this.triggers.set(result.data._id, result.data);
2781
+ }
2782
+ return result;
2783
+ }
2784
+ /**
2785
+ * Update an existing trigger
2786
+ */
2787
+ async updateTrigger(triggerId, updates) {
2788
+ const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`, {
2789
+ method: 'PUT',
2790
+ body: JSON.stringify(updates),
2791
+ });
2792
+ // Update cache if successful
2793
+ if (result.success && result.data?._id) {
2794
+ this.triggers.set(result.data._id, result.data);
2795
+ }
2796
+ return result;
2797
+ }
2798
+ /**
2799
+ * Delete a trigger
2800
+ */
2801
+ async deleteTrigger(triggerId) {
2802
+ const result = await this.request(`/api/workspaces/${this.workspaceId}/triggers/${triggerId}`, {
2803
+ method: 'DELETE',
2804
+ });
2805
+ // Remove from cache if successful
2806
+ if (result.success) {
2807
+ this.triggers.delete(triggerId);
2808
+ }
2809
+ return result;
2810
+ }
2811
+ /**
2812
+ * Activate a trigger
2813
+ */
2814
+ async activateTrigger(triggerId) {
2815
+ return this.updateTrigger(triggerId, { isActive: true });
2816
+ }
2817
+ /**
2818
+ * Deactivate a trigger
2819
+ */
2820
+ async deactivateTrigger(triggerId) {
2821
+ return this.updateTrigger(triggerId, { isActive: false });
2822
+ }
2823
+ // ============================================
2824
+ // EVENT HANDLING (CLIENT-SIDE)
2825
+ // ============================================
2826
+ /**
2827
+ * Register a local event listener for client-side triggers
2828
+ * This allows immediate client-side reactions to events
2829
+ */
2830
+ on(eventType, callback) {
2831
+ if (!this.listeners.has(eventType)) {
2832
+ this.listeners.set(eventType, new Set());
2833
+ }
2834
+ this.listeners.get(eventType).add(callback);
2835
+ logger.debug(`Event listener registered: ${eventType}`);
2836
+ }
2837
+ /**
2838
+ * Remove an event listener
2839
+ */
2840
+ off(eventType, callback) {
2841
+ const listeners = this.listeners.get(eventType);
2842
+ if (listeners) {
2843
+ listeners.delete(callback);
2844
+ }
2845
+ }
2846
+ /**
2847
+ * Emit an event (client-side only)
2848
+ * This will trigger any registered local listeners
2849
+ */
2850
+ emit(eventType, data) {
2851
+ logger.debug(`Event emitted: ${eventType}`, data);
2852
+ const listeners = this.listeners.get(eventType);
2853
+ if (listeners) {
2854
+ listeners.forEach(callback => {
2855
+ try {
2856
+ callback(data);
2857
+ }
2858
+ catch (error) {
2859
+ logger.error(`Error in event listener for ${eventType}:`, error);
2860
+ }
2861
+ });
2862
+ }
2863
+ }
2864
+ /**
2865
+ * Check if conditions are met for a trigger
2866
+ * Supports dynamic field evaluation including custom fields and nested paths
2867
+ */
2868
+ evaluateConditions(conditions, data) {
2869
+ if (!conditions || conditions.length === 0) {
2870
+ return true; // No conditions means always fire
2871
+ }
2872
+ return conditions.every(condition => {
2873
+ // Support dot notation for nested fields (e.g., 'customFields.industry')
2874
+ const fieldValue = condition.field.includes('.')
2875
+ ? this.getNestedValue(data, condition.field)
2876
+ : data[condition.field];
2877
+ const targetValue = condition.value;
2878
+ switch (condition.operator) {
2879
+ case 'equals':
2880
+ return fieldValue === targetValue;
2881
+ case 'not_equals':
2882
+ return fieldValue !== targetValue;
2883
+ case 'contains':
2884
+ return String(fieldValue).includes(String(targetValue));
2885
+ case 'greater_than':
2886
+ return Number(fieldValue) > Number(targetValue);
2887
+ case 'less_than':
2888
+ return Number(fieldValue) < Number(targetValue);
2889
+ case 'in':
2890
+ return Array.isArray(targetValue) && targetValue.includes(fieldValue);
2891
+ case 'not_in':
2892
+ return Array.isArray(targetValue) && !targetValue.includes(fieldValue);
2893
+ default:
2894
+ return false;
2895
+ }
2896
+ });
2897
+ }
2898
+ /**
2899
+ * Execute actions for a triggered event (client-side preview)
2900
+ * Note: Actual execution happens on the backend
2901
+ */
2902
+ async executeActions(trigger, data) {
2903
+ logger.info(`Executing actions for trigger: ${trigger.name}`);
2904
+ for (const action of trigger.actions) {
2905
+ try {
2906
+ await this.executeAction(action, data);
2907
+ }
2908
+ catch (error) {
2909
+ logger.error(`Failed to execute action:`, error);
2910
+ }
2911
+ }
2912
+ }
2913
+ /**
2914
+ * Execute a single action
2915
+ */
2916
+ async executeAction(action, data) {
2917
+ switch (action.type) {
2918
+ case 'send_email':
2919
+ await this.executeSendEmail(action, data);
2920
+ break;
2921
+ case 'webhook':
2922
+ await this.executeWebhook(action, data);
2923
+ break;
2924
+ case 'create_task':
2925
+ await this.executeCreateTask(action, data);
2926
+ break;
2927
+ case 'update_contact':
2928
+ await this.executeUpdateContact(action, data);
2929
+ break;
2930
+ default:
2931
+ logger.warn(`Unknown action type:`, action);
2932
+ }
2933
+ }
2934
+ /**
2935
+ * Execute send email action (via backend API)
2936
+ */
2937
+ async executeSendEmail(action, data) {
2938
+ logger.debug('Sending email:', action);
2939
+ const payload = {
2940
+ to: this.replaceVariables(action.to, data),
2941
+ subject: action.subject ? this.replaceVariables(action.subject, data) : undefined,
2942
+ body: action.body ? this.replaceVariables(action.body, data) : undefined,
2943
+ templateId: action.templateId,
2944
+ cc: action.cc,
2945
+ bcc: action.bcc,
2946
+ from: action.from,
2947
+ delayMinutes: action.delayMinutes,
2948
+ };
2949
+ await this.request(`/api/workspaces/${this.workspaceId}/emails/send`, {
2950
+ method: 'POST',
2951
+ body: JSON.stringify(payload),
2952
+ });
2953
+ }
2954
+ /**
2955
+ * Execute webhook action
2956
+ */
2957
+ async executeWebhook(action, data) {
2958
+ logger.debug('Calling webhook:', action.url);
2959
+ const body = action.body ? this.replaceVariables(action.body, data) : JSON.stringify(data);
2960
+ await fetch(action.url, {
2961
+ method: action.method,
2962
+ headers: {
2963
+ 'Content-Type': 'application/json',
2964
+ ...action.headers,
2965
+ },
2966
+ body,
2967
+ });
2968
+ }
2969
+ /**
2970
+ * Execute create task action
2971
+ */
2972
+ async executeCreateTask(action, data) {
2973
+ logger.debug('Creating task:', action.title);
2974
+ const dueDate = action.dueDays
2975
+ ? new Date(Date.now() + action.dueDays * 24 * 60 * 60 * 1000).toISOString()
2976
+ : undefined;
2977
+ await this.request(`/api/workspaces/${this.workspaceId}/tasks`, {
2978
+ method: 'POST',
2979
+ body: JSON.stringify({
2980
+ title: this.replaceVariables(action.title, data),
2981
+ description: action.description ? this.replaceVariables(action.description, data) : undefined,
2982
+ priority: action.priority,
2983
+ dueDate,
2984
+ assignedTo: action.assignedTo,
2985
+ relatedContactId: typeof data.contactId === 'string' ? data.contactId : undefined,
2986
+ }),
2987
+ });
2988
+ }
2989
+ /**
2990
+ * Execute update contact action
2991
+ */
2992
+ async executeUpdateContact(action, data) {
2993
+ const contactId = data.contactId || data._id;
2994
+ if (!contactId) {
2995
+ logger.warn('Cannot update contact: no contactId in data');
2996
+ return;
2997
+ }
2998
+ logger.debug('Updating contact:', contactId);
2999
+ await this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
3000
+ method: 'PUT',
3001
+ body: JSON.stringify(action.updates),
3002
+ });
3003
+ }
3004
+ /**
3005
+ * Replace variables in a string template
3006
+ * Supports syntax like {{contact.email}}, {{opportunity.value}}
3007
+ */
3008
+ replaceVariables(template, data) {
3009
+ return template.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
3010
+ const value = this.getNestedValue(data, path.trim());
3011
+ return value !== undefined ? String(value) : match;
3012
+ });
3013
+ }
3014
+ /**
3015
+ * Get nested value from object using dot notation
3016
+ * Supports dynamic field access including custom fields
3017
+ */
3018
+ getNestedValue(obj, path) {
3019
+ return path.split('.').reduce((current, key) => {
3020
+ return current !== null && current !== undefined && typeof current === 'object'
3021
+ ? current[key]
3022
+ : undefined;
3023
+ }, obj);
3024
+ }
3025
+ /**
3026
+ * Extract all available field paths from a data object
3027
+ * Useful for dynamic field discovery based on platform-specific attributes
3028
+ * @param obj - The data object to extract fields from
3029
+ * @param prefix - Internal use for nested paths
3030
+ * @param maxDepth - Maximum depth to traverse (default: 3)
3031
+ * @returns Array of field paths (e.g., ['email', 'contact.firstName', 'customFields.industry'])
3032
+ */
3033
+ extractAvailableFields(obj, prefix = '', maxDepth = 3) {
3034
+ if (maxDepth <= 0)
3035
+ return [];
3036
+ const fields = [];
3037
+ for (const key in obj) {
3038
+ if (!obj.hasOwnProperty(key))
3039
+ continue;
3040
+ const value = obj[key];
3041
+ const fieldPath = prefix ? `${prefix}.${key}` : key;
3042
+ fields.push(fieldPath);
3043
+ // Recursively traverse nested objects
3044
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
3045
+ const nestedFields = this.extractAvailableFields(value, fieldPath, maxDepth - 1);
3046
+ fields.push(...nestedFields);
3047
+ }
3048
+ }
3049
+ return fields;
3050
+ }
3051
+ /**
3052
+ * Get available fields from sample data
3053
+ * Helps with dynamic field detection for platform-specific attributes
3054
+ * @param sampleData - Sample data object to analyze
3055
+ * @returns Array of available field paths
3056
+ */
3057
+ getAvailableFields(sampleData) {
3058
+ return this.extractAvailableFields(sampleData);
3059
+ }
3060
+ // ============================================
3061
+ // HELPER METHODS FOR COMMON PATTERNS
3062
+ // ============================================
3063
+ /**
3064
+ * Create a simple email trigger
3065
+ * Helper method for common use case
3066
+ */
3067
+ async createEmailTrigger(config) {
3068
+ return this.createTrigger({
3069
+ name: config.name,
3070
+ eventType: config.eventType,
3071
+ conditions: config.conditions,
3072
+ actions: [
3073
+ {
3074
+ type: 'send_email',
3075
+ to: config.to,
3076
+ subject: config.subject,
3077
+ body: config.body,
3078
+ },
3079
+ ],
3080
+ isActive: true,
3081
+ });
3082
+ }
3083
+ /**
3084
+ * Create a task creation trigger
3085
+ */
3086
+ async createTaskTrigger(config) {
3087
+ return this.createTrigger({
3088
+ name: config.name,
3089
+ eventType: config.eventType,
3090
+ conditions: config.conditions,
3091
+ actions: [
3092
+ {
3093
+ type: 'create_task',
3094
+ title: config.taskTitle,
3095
+ description: config.taskDescription,
3096
+ priority: config.priority,
3097
+ dueDays: config.dueDays,
3098
+ },
3099
+ ],
3100
+ isActive: true,
3101
+ });
3102
+ }
3103
+ /**
3104
+ * Create a webhook trigger
3105
+ */
3106
+ async createWebhookTrigger(config) {
3107
+ return this.createTrigger({
3108
+ name: config.name,
3109
+ eventType: config.eventType,
3110
+ conditions: config.conditions,
3111
+ actions: [
3112
+ {
3113
+ type: 'webhook',
3114
+ url: config.webhookUrl,
3115
+ method: config.method || 'POST',
3116
+ },
3117
+ ],
3118
+ isActive: true,
3119
+ });
3120
+ }
3121
+ }
3122
+
3123
+ /**
3124
+ * Clianta SDK - CRM API Client
3125
+ * @see SDK_VERSION in core/config.ts
3126
+ */
3127
+ /**
3128
+ * CRM API Client for managing contacts and opportunities
3129
+ */
3130
+ class CRMClient {
3131
+ constructor(apiEndpoint, workspaceId, authToken) {
3132
+ this.apiEndpoint = apiEndpoint;
3133
+ this.workspaceId = workspaceId;
3134
+ this.authToken = authToken;
3135
+ this.triggers = new EventTriggersManager(apiEndpoint, workspaceId, authToken);
3136
+ }
3137
+ /**
3138
+ * Set authentication token for API requests
3139
+ */
3140
+ setAuthToken(token) {
3141
+ this.authToken = token;
3142
+ this.triggers.setAuthToken(token);
3143
+ }
3144
+ /**
3145
+ * Validate required parameter exists
3146
+ * @throws {Error} if value is null/undefined or empty string
3147
+ */
3148
+ validateRequired(param, value, methodName) {
3149
+ if (value === null || value === undefined || value === '') {
3150
+ throw new Error(`[CRMClient.${methodName}] ${param} is required`);
3151
+ }
3152
+ }
3153
+ /**
3154
+ * Make authenticated API request
3155
+ */
3156
+ async request(endpoint, options = {}) {
3157
+ const url = `${this.apiEndpoint}${endpoint}`;
3158
+ const headers = {
3159
+ 'Content-Type': 'application/json',
3160
+ ...(options.headers || {}),
3161
+ };
3162
+ if (this.authToken) {
3163
+ headers['Authorization'] = `Bearer ${this.authToken}`;
3164
+ }
3165
+ try {
3166
+ const response = await fetch(url, {
3167
+ ...options,
3168
+ headers,
3169
+ });
3170
+ const data = await response.json();
3171
+ if (!response.ok) {
3172
+ return {
3173
+ success: false,
3174
+ error: data.message || 'Request failed',
3175
+ status: response.status,
3176
+ };
3177
+ }
3178
+ return {
3179
+ success: true,
3180
+ data: data.data || data,
3181
+ status: response.status,
3182
+ };
3183
+ }
3184
+ catch (error) {
3185
+ return {
3186
+ success: false,
3187
+ error: error instanceof Error ? error.message : 'Network error',
3188
+ status: 0,
3189
+ };
3190
+ }
3191
+ }
3192
+ // ============================================
3193
+ // CONTACTS API
3194
+ // ============================================
3195
+ /**
3196
+ * Get all contacts with pagination
3197
+ */
3198
+ async getContacts(params) {
3199
+ const queryParams = new URLSearchParams();
3200
+ if (params?.page)
3201
+ queryParams.set('page', params.page.toString());
3202
+ if (params?.limit)
3203
+ queryParams.set('limit', params.limit.toString());
3204
+ if (params?.search)
3205
+ queryParams.set('search', params.search);
3206
+ if (params?.status)
3207
+ queryParams.set('status', params.status);
3208
+ const query = queryParams.toString();
3209
+ const endpoint = `/api/workspaces/${this.workspaceId}/contacts${query ? `?${query}` : ''}`;
3210
+ return this.request(endpoint);
3211
+ }
3212
+ /**
3213
+ * Get a single contact by ID
3214
+ */
3215
+ async getContact(contactId) {
3216
+ this.validateRequired('contactId', contactId, 'getContact');
3217
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`);
3218
+ }
3219
+ /**
3220
+ * Create a new contact
3221
+ */
3222
+ async createContact(contact) {
3223
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts`, {
3224
+ method: 'POST',
3225
+ body: JSON.stringify(contact),
3226
+ });
3227
+ }
3228
+ /**
3229
+ * Update an existing contact
3230
+ */
3231
+ async updateContact(contactId, updates) {
3232
+ this.validateRequired('contactId', contactId, 'updateContact');
3233
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
3234
+ method: 'PUT',
3235
+ body: JSON.stringify(updates),
3236
+ });
3237
+ }
3238
+ /**
3239
+ * Delete a contact
3240
+ */
3241
+ async deleteContact(contactId) {
3242
+ this.validateRequired('contactId', contactId, 'deleteContact');
3243
+ return this.request(`/api/workspaces/${this.workspaceId}/contacts/${contactId}`, {
3244
+ method: 'DELETE',
3245
+ });
3246
+ }
3247
+ // ============================================
3248
+ // OPPORTUNITIES API
3249
+ // ============================================
3250
+ /**
3251
+ * Get all opportunities with pagination
3252
+ */
3253
+ async getOpportunities(params) {
3254
+ const queryParams = new URLSearchParams();
3255
+ if (params?.page)
3256
+ queryParams.set('page', params.page.toString());
3257
+ if (params?.limit)
3258
+ queryParams.set('limit', params.limit.toString());
3259
+ if (params?.pipelineId)
3260
+ queryParams.set('pipelineId', params.pipelineId);
3261
+ if (params?.stageId)
3262
+ queryParams.set('stageId', params.stageId);
3263
+ const query = queryParams.toString();
3264
+ const endpoint = `/api/workspaces/${this.workspaceId}/opportunities${query ? `?${query}` : ''}`;
3265
+ return this.request(endpoint);
3266
+ }
3267
+ /**
3268
+ * Get a single opportunity by ID
3269
+ */
3270
+ async getOpportunity(opportunityId) {
3271
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`);
3272
+ }
3273
+ /**
3274
+ * Create a new opportunity
3275
+ */
3276
+ async createOpportunity(opportunity) {
3277
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities`, {
3278
+ method: 'POST',
3279
+ body: JSON.stringify(opportunity),
3280
+ });
3281
+ }
3282
+ /**
3283
+ * Update an existing opportunity
3284
+ */
3285
+ async updateOpportunity(opportunityId, updates) {
3286
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`, {
3287
+ method: 'PUT',
3288
+ body: JSON.stringify(updates),
3289
+ });
3290
+ }
3291
+ /**
3292
+ * Delete an opportunity
3293
+ */
3294
+ async deleteOpportunity(opportunityId) {
3295
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}`, {
3296
+ method: 'DELETE',
3297
+ });
3298
+ }
3299
+ /**
3300
+ * Move opportunity to a different stage
3301
+ */
3302
+ async moveOpportunity(opportunityId, stageId) {
3303
+ return this.request(`/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}/move`, {
3304
+ method: 'POST',
3305
+ body: JSON.stringify({ stageId }),
3306
+ });
3307
+ }
3308
+ // ============================================
3309
+ // COMPANIES API
3310
+ // ============================================
3311
+ /**
3312
+ * Get all companies with pagination
3313
+ */
3314
+ async getCompanies(params) {
3315
+ const queryParams = new URLSearchParams();
3316
+ if (params?.page)
3317
+ queryParams.set('page', params.page.toString());
3318
+ if (params?.limit)
3319
+ queryParams.set('limit', params.limit.toString());
3320
+ if (params?.search)
3321
+ queryParams.set('search', params.search);
3322
+ if (params?.status)
3323
+ queryParams.set('status', params.status);
3324
+ if (params?.industry)
3325
+ queryParams.set('industry', params.industry);
3326
+ const query = queryParams.toString();
3327
+ const endpoint = `/api/workspaces/${this.workspaceId}/companies${query ? `?${query}` : ''}`;
3328
+ return this.request(endpoint);
3329
+ }
3330
+ /**
3331
+ * Get a single company by ID
3332
+ */
3333
+ async getCompany(companyId) {
3334
+ return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`);
3335
+ }
3336
+ /**
3337
+ * Create a new company
3338
+ */
3339
+ async createCompany(company) {
3340
+ return this.request(`/api/workspaces/${this.workspaceId}/companies`, {
3341
+ method: 'POST',
3342
+ body: JSON.stringify(company),
3343
+ });
3344
+ }
3345
+ /**
3346
+ * Update an existing company
3347
+ */
3348
+ async updateCompany(companyId, updates) {
3349
+ return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`, {
3350
+ method: 'PUT',
3351
+ body: JSON.stringify(updates),
3352
+ });
3353
+ }
3354
+ /**
3355
+ * Delete a company
3356
+ */
3357
+ async deleteCompany(companyId) {
3358
+ return this.request(`/api/workspaces/${this.workspaceId}/companies/${companyId}`, {
3359
+ method: 'DELETE',
3360
+ });
3361
+ }
3362
+ /**
3363
+ * Get contacts belonging to a company
3364
+ */
3365
+ async getCompanyContacts(companyId, params) {
3366
+ const queryParams = new URLSearchParams();
3367
+ if (params?.page)
3368
+ queryParams.set('page', params.page.toString());
3369
+ if (params?.limit)
3370
+ queryParams.set('limit', params.limit.toString());
3371
+ const query = queryParams.toString();
3372
+ const endpoint = `/api/workspaces/${this.workspaceId}/companies/${companyId}/contacts${query ? `?${query}` : ''}`;
3373
+ return this.request(endpoint);
3374
+ }
3375
+ /**
3376
+ * Get deals/opportunities belonging to a company
3377
+ */
3378
+ async getCompanyDeals(companyId, params) {
3379
+ const queryParams = new URLSearchParams();
3380
+ if (params?.page)
3381
+ queryParams.set('page', params.page.toString());
3382
+ if (params?.limit)
3383
+ queryParams.set('limit', params.limit.toString());
3384
+ const query = queryParams.toString();
3385
+ const endpoint = `/api/workspaces/${this.workspaceId}/companies/${companyId}/deals${query ? `?${query}` : ''}`;
3386
+ return this.request(endpoint);
3387
+ }
3388
+ // ============================================
3389
+ // PIPELINES API
3390
+ // ============================================
3391
+ /**
3392
+ * Get all pipelines
3393
+ */
3394
+ async getPipelines() {
3395
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines`);
3396
+ }
3397
+ /**
3398
+ * Get a single pipeline by ID
3399
+ */
3400
+ async getPipeline(pipelineId) {
3401
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`);
3402
+ }
3403
+ /**
3404
+ * Create a new pipeline
3405
+ */
3406
+ async createPipeline(pipeline) {
3407
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines`, {
3408
+ method: 'POST',
3409
+ body: JSON.stringify(pipeline),
3410
+ });
3411
+ }
3412
+ /**
3413
+ * Update an existing pipeline
3414
+ */
3415
+ async updatePipeline(pipelineId, updates) {
3416
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`, {
3417
+ method: 'PUT',
3418
+ body: JSON.stringify(updates),
3419
+ });
3420
+ }
3421
+ /**
3422
+ * Delete a pipeline
3423
+ */
3424
+ async deletePipeline(pipelineId) {
3425
+ return this.request(`/api/workspaces/${this.workspaceId}/pipelines/${pipelineId}`, {
3426
+ method: 'DELETE',
3427
+ });
3428
+ }
3429
+ // ============================================
3430
+ // TASKS API
3431
+ // ============================================
3432
+ /**
3433
+ * Get all tasks with pagination
3434
+ */
3435
+ async getTasks(params) {
3436
+ const queryParams = new URLSearchParams();
3437
+ if (params?.page)
3438
+ queryParams.set('page', params.page.toString());
3439
+ if (params?.limit)
3440
+ queryParams.set('limit', params.limit.toString());
3441
+ if (params?.status)
3442
+ queryParams.set('status', params.status);
3443
+ if (params?.priority)
3444
+ queryParams.set('priority', params.priority);
3445
+ if (params?.contactId)
3446
+ queryParams.set('contactId', params.contactId);
3447
+ if (params?.companyId)
3448
+ queryParams.set('companyId', params.companyId);
3449
+ if (params?.opportunityId)
3450
+ queryParams.set('opportunityId', params.opportunityId);
3451
+ const query = queryParams.toString();
3452
+ const endpoint = `/api/workspaces/${this.workspaceId}/tasks${query ? `?${query}` : ''}`;
3453
+ return this.request(endpoint);
3454
+ }
3455
+ /**
3456
+ * Get a single task by ID
3457
+ */
3458
+ async getTask(taskId) {
3459
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`);
3460
+ }
3461
+ /**
3462
+ * Create a new task
3463
+ */
3464
+ async createTask(task) {
3465
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks`, {
3466
+ method: 'POST',
3467
+ body: JSON.stringify(task),
3468
+ });
3469
+ }
3470
+ /**
3471
+ * Update an existing task
3472
+ */
3473
+ async updateTask(taskId, updates) {
3474
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`, {
3475
+ method: 'PUT',
3476
+ body: JSON.stringify(updates),
3477
+ });
3478
+ }
3479
+ /**
3480
+ * Mark a task as completed
3481
+ */
3482
+ async completeTask(taskId) {
3483
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}/complete`, {
3484
+ method: 'PATCH',
3485
+ });
3486
+ }
3487
+ /**
3488
+ * Delete a task
3489
+ */
3490
+ async deleteTask(taskId) {
3491
+ return this.request(`/api/workspaces/${this.workspaceId}/tasks/${taskId}`, {
3492
+ method: 'DELETE',
3493
+ });
3494
+ }
3495
+ // ============================================
3496
+ // ACTIVITIES API
3497
+ // ============================================
3498
+ /**
3499
+ * Get activities for a contact
3500
+ */
3501
+ async getContactActivities(contactId, params) {
3502
+ const queryParams = new URLSearchParams();
3503
+ if (params?.page)
3504
+ queryParams.set('page', params.page.toString());
3505
+ if (params?.limit)
3506
+ queryParams.set('limit', params.limit.toString());
3507
+ if (params?.type)
3508
+ queryParams.set('type', params.type);
3509
+ const query = queryParams.toString();
3510
+ const endpoint = `/api/workspaces/${this.workspaceId}/contacts/${contactId}/activities${query ? `?${query}` : ''}`;
3511
+ return this.request(endpoint);
3512
+ }
3513
+ /**
3514
+ * Get activities for an opportunity/deal
3515
+ */
3516
+ async getOpportunityActivities(opportunityId, params) {
3517
+ const queryParams = new URLSearchParams();
3518
+ if (params?.page)
3519
+ queryParams.set('page', params.page.toString());
3520
+ if (params?.limit)
3521
+ queryParams.set('limit', params.limit.toString());
3522
+ if (params?.type)
3523
+ queryParams.set('type', params.type);
3524
+ const query = queryParams.toString();
3525
+ const endpoint = `/api/workspaces/${this.workspaceId}/opportunities/${opportunityId}/activities${query ? `?${query}` : ''}`;
3526
+ return this.request(endpoint);
3527
+ }
3528
+ /**
3529
+ * Create a new activity
3530
+ */
3531
+ async createActivity(activity) {
3532
+ // Determine the correct endpoint based on related entity
3533
+ let endpoint;
3534
+ if (activity.opportunityId) {
3535
+ endpoint = `/api/workspaces/${this.workspaceId}/opportunities/${activity.opportunityId}/activities`;
3536
+ }
3537
+ else if (activity.contactId) {
3538
+ endpoint = `/api/workspaces/${this.workspaceId}/contacts/${activity.contactId}/activities`;
3539
+ }
3540
+ else {
3541
+ endpoint = `/api/workspaces/${this.workspaceId}/activities`;
3542
+ }
3543
+ return this.request(endpoint, {
3544
+ method: 'POST',
3545
+ body: JSON.stringify(activity),
3546
+ });
3547
+ }
3548
+ /**
3549
+ * Update an existing activity
3550
+ */
3551
+ async updateActivity(activityId, updates) {
3552
+ return this.request(`/api/workspaces/${this.workspaceId}/activities/${activityId}`, {
3553
+ method: 'PATCH',
3554
+ body: JSON.stringify(updates),
3555
+ });
3556
+ }
3557
+ /**
3558
+ * Delete an activity
3559
+ */
3560
+ async deleteActivity(activityId) {
3561
+ return this.request(`/api/workspaces/${this.workspaceId}/activities/${activityId}`, {
3562
+ method: 'DELETE',
3563
+ });
3564
+ }
3565
+ /**
3566
+ * Log a call activity
3567
+ */
3568
+ async logCall(data) {
3569
+ return this.createActivity({
3570
+ type: 'call',
3571
+ title: `${data.direction === 'inbound' ? 'Inbound' : 'Outbound'} Call`,
3572
+ direction: data.direction,
3573
+ duration: data.duration,
3574
+ outcome: data.outcome,
3575
+ description: data.notes,
3576
+ contactId: data.contactId,
3577
+ opportunityId: data.opportunityId,
3578
+ });
3579
+ }
3580
+ /**
3581
+ * Log a meeting activity
3582
+ */
3583
+ async logMeeting(data) {
3584
+ return this.createActivity({
3585
+ type: 'meeting',
3586
+ title: data.title,
3587
+ duration: data.duration,
3588
+ outcome: data.outcome,
3589
+ description: data.notes,
3590
+ contactId: data.contactId,
3591
+ opportunityId: data.opportunityId,
3592
+ });
3593
+ }
3594
+ /**
3595
+ * Add a note to a contact or opportunity
3596
+ */
3597
+ async addNote(data) {
3598
+ return this.createActivity({
3599
+ type: 'note',
3600
+ title: 'Note',
3601
+ description: data.content,
3602
+ contactId: data.contactId,
3603
+ opportunityId: data.opportunityId,
3604
+ });
3605
+ }
3606
+ // ============================================
3607
+ // EMAIL TEMPLATES API
3608
+ // ============================================
3609
+ /**
3610
+ * Get all email templates
3611
+ */
3612
+ async getEmailTemplates(params) {
3613
+ const queryParams = new URLSearchParams();
3614
+ if (params?.page)
3615
+ queryParams.set('page', params.page.toString());
3616
+ if (params?.limit)
3617
+ queryParams.set('limit', params.limit.toString());
3618
+ const query = queryParams.toString();
3619
+ const endpoint = `/api/workspaces/${this.workspaceId}/email-templates${query ? `?${query}` : ''}`;
3620
+ return this.request(endpoint);
3621
+ }
3622
+ /**
3623
+ * Get a single email template by ID
3624
+ */
3625
+ async getEmailTemplate(templateId) {
3626
+ return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`);
3627
+ }
3628
+ /**
3629
+ * Create a new email template
3630
+ */
3631
+ async createEmailTemplate(template) {
3632
+ return this.request(`/api/workspaces/${this.workspaceId}/email-templates`, {
3633
+ method: 'POST',
3634
+ body: JSON.stringify(template),
3635
+ });
3636
+ }
3637
+ /**
3638
+ * Update an email template
3639
+ */
3640
+ async updateEmailTemplate(templateId, updates) {
3641
+ return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`, {
3642
+ method: 'PUT',
3643
+ body: JSON.stringify(updates),
3644
+ });
3645
+ }
3646
+ /**
3647
+ * Delete an email template
3648
+ */
3649
+ async deleteEmailTemplate(templateId) {
3650
+ return this.request(`/api/workspaces/${this.workspaceId}/email-templates/${templateId}`, {
3651
+ method: 'DELETE',
3652
+ });
3653
+ }
3654
+ /**
3655
+ * Send an email using a template
3656
+ */
3657
+ async sendEmail(data) {
3658
+ return this.request(`/api/workspaces/${this.workspaceId}/emails/send`, {
3659
+ method: 'POST',
3660
+ body: JSON.stringify(data),
3661
+ });
3662
+ }
3663
+ // ============================================
3664
+ // EVENT TRIGGERS API (delegated to triggers manager)
3665
+ // ============================================
3666
+ /**
3667
+ * Get all event triggers
3668
+ */
3669
+ async getEventTriggers() {
3670
+ return this.triggers.getTriggers();
3671
+ }
3672
+ /**
3673
+ * Create a new event trigger
3674
+ */
3675
+ async createEventTrigger(trigger) {
3676
+ return this.triggers.createTrigger(trigger);
3677
+ }
3678
+ /**
3679
+ * Update an event trigger
3680
+ */
3681
+ async updateEventTrigger(triggerId, updates) {
3682
+ return this.triggers.updateTrigger(triggerId, updates);
3683
+ }
3684
+ /**
3685
+ * Delete an event trigger
3686
+ */
3687
+ async deleteEventTrigger(triggerId) {
3688
+ return this.triggers.deleteTrigger(triggerId);
3689
+ }
3690
+ }
3691
+
3692
+ /**
3693
+ * Clianta SDK
3694
+ * Professional CRM and tracking SDK for lead generation
3695
+ * @see SDK_VERSION in core/config.ts
3696
+ */
3697
+ // Global instance cache
3698
+ let globalInstance = null;
3699
+ /**
3700
+ * Initialize or get the Clianta tracker instance
3701
+ *
3702
+ * @example
3703
+ * // Simple initialization
3704
+ * const tracker = clianta('your-workspace-id');
3705
+ *
3706
+ * @example
3707
+ * // With configuration
3708
+ * const tracker = clianta('your-workspace-id', {
3709
+ * debug: true,
3710
+ * plugins: ['pageView', 'forms', 'scroll'],
3711
+ * });
3712
+ *
3713
+ * @example
3714
+ * // With consent configuration
3715
+ * const tracker = clianta('your-workspace-id', {
3716
+ * consent: {
3717
+ * waitForConsent: true,
3718
+ * anonymousMode: true,
3719
+ * },
3720
+ * cookielessMode: true, // GDPR-friendly mode
3721
+ * });
3722
+ */
3723
+ function clianta(workspaceId, config) {
3724
+ // Return existing instance if same workspace
3725
+ if (globalInstance && globalInstance.getWorkspaceId() === workspaceId) {
3726
+ return globalInstance;
3727
+ }
3728
+ // Destroy existing instance if workspace changed
3729
+ if (globalInstance) {
3730
+ globalInstance.destroy();
3731
+ }
3732
+ // Create new instance
3733
+ globalInstance = new Tracker(workspaceId, config);
3734
+ return globalInstance;
3735
+ }
3736
+ // Attach to window for <script> usage
3737
+ if (typeof window !== 'undefined') {
3738
+ window.clianta = clianta;
3739
+ window.Clianta = {
3740
+ clianta,
3741
+ Tracker,
3742
+ CRMClient,
3743
+ ConsentManager,
3744
+ EventTriggersManager,
3745
+ };
3746
+ }
3747
+
3748
+ /**
3749
+ * Clianta SDK - Vue 3 Integration
3750
+ *
3751
+ * Provides plugin and composables for easy Vue 3 integration.
3752
+ */
3753
+ // Injection key for tracker
3754
+ const CliantaKey = Symbol('clianta');
3755
+ /**
3756
+ * Vue plugin for Clianta SDK
3757
+ *
3758
+ * @example
3759
+ * // In main.ts:
3760
+ * import { createApp } from 'vue';
3761
+ * import { CliantaPlugin } from '@clianta/sdk/vue';
3762
+ * import App from './App.vue';
3763
+ *
3764
+ * const app = createApp(App);
3765
+ * app.use(CliantaPlugin, {
3766
+ * projectId: 'your-project-id',
3767
+ * apiEndpoint: 'https://api.clianta.online',
3768
+ * debug: import.meta.env.DEV,
3769
+ * });
3770
+ * app.mount('#app');
3771
+ */
3772
+ const CliantaPlugin = {
3773
+ install(app, options) {
3774
+ if (!options?.projectId) {
3775
+ console.error('[Clianta] Missing projectId in plugin options');
3776
+ return;
3777
+ }
3778
+ const { projectId, ...config } = options;
3779
+ const tracker = clianta(projectId, config);
3780
+ // Provide tracker to all components
3781
+ app.provide(CliantaKey, ref(tracker));
3782
+ // Add global property for Options API access
3783
+ app.config.globalProperties.$clianta = tracker;
3784
+ // Flush on app unmount
3785
+ app.mixin({
3786
+ beforeUnmount() {
3787
+ // Only flush on root component unmount
3788
+ if (this.$.parent === null) {
3789
+ tracker.flush();
3790
+ }
3791
+ },
3792
+ });
3793
+ },
3794
+ };
3795
+ /**
3796
+ * useClianta - Composable to access tracker
3797
+ *
3798
+ * @example
3799
+ * <script setup>
3800
+ * import { useClianta } from '@clianta/sdk/vue';
3801
+ *
3802
+ * const tracker = useClianta();
3803
+ * tracker.value?.track('button_click', 'CTA Button');
3804
+ * </script>
3805
+ */
3806
+ function useClianta() {
3807
+ const tracker = inject(CliantaKey);
3808
+ if (!tracker) {
3809
+ console.warn('[Clianta] useClianta must be used within a component where CliantaPlugin is installed');
3810
+ return ref(null);
3811
+ }
3812
+ return tracker;
3813
+ }
3814
+ /**
3815
+ * useCliantaTrack - Composable for tracking events
3816
+ *
3817
+ * @example
3818
+ * <script setup>
3819
+ * import { useCliantaTrack } from '@clianta/sdk/vue';
3820
+ *
3821
+ * const track = useCliantaTrack();
3822
+ * track('purchase', 'Order Completed', { orderId: '123' });
3823
+ * </script>
3824
+ */
3825
+ function useCliantaTrack() {
3826
+ const tracker = useClianta();
3827
+ return (eventType, eventName, properties) => {
3828
+ tracker.value?.track(eventType, eventName, properties);
3829
+ };
3830
+ }
3831
+ /**
3832
+ * useCliantaIdentify - Composable for identifying users
3833
+ *
3834
+ * @example
3835
+ * <script setup>
3836
+ * import { useCliantaIdentify } from '@clianta/sdk/vue';
3837
+ *
3838
+ * const identify = useCliantaIdentify();
3839
+ * identify('user@example.com', { name: 'John' });
3840
+ * </script>
3841
+ */
3842
+ function useCliantaIdentify() {
3843
+ const tracker = useClianta();
3844
+ return (email, traits) => {
3845
+ return tracker.value?.identify(email, traits);
3846
+ };
3847
+ }
3848
+ /**
3849
+ * useCliantaPageView - Composable for manual page view tracking
3850
+ *
3851
+ * @example
3852
+ * <script setup>
3853
+ * import { useCliantaPageView } from '@clianta/sdk/vue';
3854
+ * import { watch } from 'vue';
3855
+ * import { useRoute } from 'vue-router';
3856
+ *
3857
+ * const route = useRoute();
3858
+ * const trackPageView = useCliantaPageView();
3859
+ *
3860
+ * watch(() => route.path, () => {
3861
+ * trackPageView(route.name?.toString());
3862
+ * });
3863
+ * </script>
3864
+ */
3865
+ function useCliantaPageView() {
3866
+ const tracker = useClianta();
3867
+ return (name, properties) => {
3868
+ tracker.value?.page(name, properties);
3869
+ };
3870
+ }
3871
+ /**
3872
+ * useCliantaConsent - Composable for managing consent
3873
+ *
3874
+ * @example
3875
+ * <script setup>
3876
+ * import { useCliantaConsent } from '@clianta/sdk/vue';
3877
+ *
3878
+ * const { consent, getConsentState } = useCliantaConsent();
3879
+ * consent({ analytics: true, marketing: false });
3880
+ * </script>
3881
+ */
3882
+ function useCliantaConsent() {
3883
+ const tracker = useClianta();
3884
+ return {
3885
+ consent: (state) => {
3886
+ tracker.value?.consent(state);
3887
+ },
3888
+ getConsentState: () => tracker.value?.getConsentState(),
3889
+ };
3890
+ }
3891
+
3892
+ export { CliantaPlugin, useClianta, useCliantaConsent, useCliantaIdentify, useCliantaPageView, useCliantaTrack };
3893
+ //# sourceMappingURL=vue.esm.js.map