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