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