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