@clianta/sdk 1.6.8 → 1.7.1

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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Clianta SDK v1.6.8
2
+ * Clianta SDK v1.7.1
3
3
  * (c) 2026 Clianta
4
4
  * Released under the MIT License.
5
5
  */
@@ -15,7 +15,7 @@
15
15
  * @see SDK_VERSION in core/config.ts
16
16
  */
17
17
  /** SDK Version */
18
- const SDK_VERSION = '1.6.7';
18
+ const SDK_VERSION = '1.7.0';
19
19
  /** Default API endpoint — reads from env or falls back to localhost */
20
20
  const getDefaultApiEndpoint = () => {
21
21
  // Next.js (process.env)
@@ -41,6 +41,15 @@
41
41
  if (typeof process !== 'undefined' && process.env?.CLIANTA_API_ENDPOINT) {
42
42
  return process.env.CLIANTA_API_ENDPOINT;
43
43
  }
44
+ // No env var found — warn if we're not on localhost (likely a production misconfiguration)
45
+ const isLocalhost = typeof window !== 'undefined' &&
46
+ (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
47
+ if (!isLocalhost && typeof console !== 'undefined') {
48
+ console.warn('[Clianta] No API endpoint configured. ' +
49
+ 'Set NEXT_PUBLIC_CLIANTA_API_ENDPOINT (Next.js), VITE_CLIANTA_API_ENDPOINT (Vite), ' +
50
+ 'or pass apiEndpoint directly to clianta(). ' +
51
+ 'Falling back to localhost — tracking will not work in production.');
52
+ }
44
53
  return 'http://localhost:5000';
45
54
  };
46
55
  /** Core plugins enabled by default — all auto-track with zero config */
@@ -186,7 +195,9 @@
186
195
  */
187
196
  const DEFAULT_TIMEOUT = 10000; // 10 seconds
188
197
  const DEFAULT_MAX_RETRIES = 3;
189
- const DEFAULT_RETRY_DELAY = 1000; // 1 second
198
+ const DEFAULT_RETRY_DELAY = 1000; // 1 second base — doubles each attempt (exponential backoff)
199
+ /** fetch keepalive hard limit in browsers (64KB) */
200
+ const KEEPALIVE_SIZE_LIMIT = 60000; // leave 4KB margin
190
201
  /**
191
202
  * Transport class for sending data to the backend
192
203
  */
@@ -205,6 +216,11 @@
205
216
  async sendEvents(events) {
206
217
  const url = `${this.config.apiEndpoint}/api/public/track/event`;
207
218
  const payload = JSON.stringify({ events });
219
+ // keepalive has a 64KB hard limit — fall back to beacon if too large
220
+ if (payload.length > KEEPALIVE_SIZE_LIMIT) {
221
+ const sent = this.sendBeacon(events);
222
+ return sent ? { success: true } : this.send(url, payload, 1, false);
223
+ }
208
224
  return this.send(url, payload);
209
225
  }
210
226
  /**
@@ -269,6 +285,15 @@
269
285
  return false;
270
286
  }
271
287
  }
288
+ /**
289
+ * Send an arbitrary POST request through the transport (with timeout + retry).
290
+ * Used for one-off calls like alias() that don't fit the event-batch or identify shapes.
291
+ */
292
+ async sendPost(path, body) {
293
+ const url = `${this.config.apiEndpoint}${path}`;
294
+ const payload = JSON.stringify(body);
295
+ return this.send(url, payload);
296
+ }
272
297
  /**
273
298
  * Fetch data from the tracking API (GET request)
274
299
  * Used for read-back APIs (visitor profile, activity, etc.)
@@ -303,38 +328,44 @@
303
328
  }
304
329
  }
305
330
  /**
306
- * Internal send with retry logic
331
+ * Internal send with exponential backoff retry logic
307
332
  */
308
- async send(url, payload, attempt = 1) {
333
+ async send(url, payload, attempt = 1, useKeepalive = true) {
334
+ // Don't bother sending when offline — caller should re-queue
335
+ if (typeof navigator !== 'undefined' && !navigator.onLine) {
336
+ logger.warn('Device offline, skipping send');
337
+ return { success: false, error: new Error('offline') };
338
+ }
309
339
  try {
310
340
  const response = await this.fetchWithTimeout(url, {
311
341
  method: 'POST',
312
- headers: {
313
- 'Content-Type': 'application/json',
314
- },
342
+ headers: { 'Content-Type': 'application/json' },
315
343
  body: payload,
316
- keepalive: true,
344
+ keepalive: useKeepalive,
317
345
  });
318
346
  if (response.ok) {
319
347
  logger.debug('Request successful:', url);
320
348
  return { success: true, status: response.status };
321
349
  }
322
- // Server error - may retry
350
+ // Server error retry with exponential backoff
323
351
  if (response.status >= 500 && attempt < this.config.maxRetries) {
324
- logger.warn(`Server error (${response.status}), retrying...`);
325
- await this.delay(this.config.retryDelay * attempt);
326
- return this.send(url, payload, attempt + 1);
352
+ const backoff = this.config.retryDelay * Math.pow(2, attempt - 1);
353
+ logger.warn(`Server error (${response.status}), retrying in ${backoff}ms...`);
354
+ await this.delay(backoff);
355
+ return this.send(url, payload, attempt + 1, useKeepalive);
327
356
  }
328
- // Client error - don't retry
357
+ // 4xx don't retry (bad payload, auth failure, etc.)
329
358
  logger.error(`Request failed with status ${response.status}`);
330
359
  return { success: false, status: response.status };
331
360
  }
332
361
  catch (error) {
333
- // Network error - retry if possible
334
- if (attempt < this.config.maxRetries) {
335
- logger.warn(`Network error, retrying (${attempt}/${this.config.maxRetries})...`);
336
- await this.delay(this.config.retryDelay * attempt);
337
- return this.send(url, payload, attempt + 1);
362
+ // Network error retry with exponential backoff if still online
363
+ const isOnline = typeof navigator === 'undefined' || navigator.onLine;
364
+ if (isOnline && attempt < this.config.maxRetries) {
365
+ const backoff = this.config.retryDelay * Math.pow(2, attempt - 1);
366
+ logger.warn(`Network error, retrying in ${backoff}ms (${attempt}/${this.config.maxRetries})...`);
367
+ await this.delay(backoff);
368
+ return this.send(url, payload, attempt + 1, useKeepalive);
338
369
  }
339
370
  logger.error('Request failed after retries:', error);
340
371
  return { success: false, error: error };
@@ -683,12 +714,17 @@
683
714
  this.queue = [];
684
715
  this.flushTimer = null;
685
716
  this.isFlushing = false;
717
+ this.isOnline = true;
686
718
  /** Rate limiting: timestamps of recent events */
687
719
  this.eventTimestamps = [];
688
720
  /** Unload handler references for cleanup */
689
721
  this.boundBeforeUnload = null;
690
722
  this.boundVisibilityChange = null;
691
723
  this.boundPageHide = null;
724
+ this.boundOnline = null;
725
+ this.boundOffline = null;
726
+ /** Guards against double-flush on unload (beforeunload + pagehide + visibilitychange all fire) */
727
+ this.unloadFlushed = false;
692
728
  this.transport = transport;
693
729
  this.config = {
694
730
  batchSize: config.batchSize ?? 10,
@@ -697,6 +733,7 @@
697
733
  storageKey: config.storageKey ?? STORAGE_KEYS.EVENT_QUEUE,
698
734
  };
699
735
  this.persistMode = config.persistMode || 'session';
736
+ this.isOnline = typeof navigator === 'undefined' || navigator.onLine;
700
737
  // Restore persisted queue
701
738
  this.restoreQueue();
702
739
  // Start auto-flush timer
@@ -745,7 +782,7 @@
745
782
  * Flush the queue (send all events)
746
783
  */
747
784
  async flush() {
748
- if (this.isFlushing || this.queue.length === 0) {
785
+ if (this.isFlushing || this.queue.length === 0 || !this.isOnline) {
749
786
  return;
750
787
  }
751
788
  this.isFlushing = true;
@@ -776,11 +813,14 @@
776
813
  }
777
814
  }
778
815
  /**
779
- * Flush synchronously using sendBeacon (for page unload)
816
+ * Flush synchronously using sendBeacon (for page unload).
817
+ * Guarded: no-ops after the first call per navigation to prevent
818
+ * triple-flush from beforeunload + visibilitychange + pagehide.
780
819
  */
781
820
  flushSync() {
782
- if (this.queue.length === 0)
821
+ if (this.unloadFlushed || this.queue.length === 0)
783
822
  return;
823
+ this.unloadFlushed = true;
784
824
  const events = this.queue.splice(0, this.queue.length);
785
825
  logger.debug(`Sync flushing ${events.length} events via beacon`);
786
826
  const success = this.transport.sendBeacon(events);
@@ -818,17 +858,17 @@
818
858
  clearInterval(this.flushTimer);
819
859
  this.flushTimer = null;
820
860
  }
821
- // Remove unload handlers
822
861
  if (typeof window !== 'undefined') {
823
- if (this.boundBeforeUnload) {
862
+ if (this.boundBeforeUnload)
824
863
  window.removeEventListener('beforeunload', this.boundBeforeUnload);
825
- }
826
- if (this.boundVisibilityChange) {
864
+ if (this.boundVisibilityChange)
827
865
  window.removeEventListener('visibilitychange', this.boundVisibilityChange);
828
- }
829
- if (this.boundPageHide) {
866
+ if (this.boundPageHide)
830
867
  window.removeEventListener('pagehide', this.boundPageHide);
831
- }
868
+ if (this.boundOnline)
869
+ window.removeEventListener('online', this.boundOnline);
870
+ if (this.boundOffline)
871
+ window.removeEventListener('offline', this.boundOffline);
832
872
  }
833
873
  }
834
874
  /**
@@ -843,24 +883,38 @@
843
883
  }, this.config.flushInterval);
844
884
  }
845
885
  /**
846
- * Setup page unload handlers
886
+ * Setup page unload handlers and online/offline listeners
847
887
  */
848
888
  setupUnloadHandlers() {
849
889
  if (typeof window === 'undefined')
850
890
  return;
851
- // Flush on page unload
891
+ // All three unload events share the same guarded flushSync()
852
892
  this.boundBeforeUnload = () => this.flushSync();
853
893
  window.addEventListener('beforeunload', this.boundBeforeUnload);
854
- // Flush when page becomes hidden
855
894
  this.boundVisibilityChange = () => {
856
895
  if (document.visibilityState === 'hidden') {
857
896
  this.flushSync();
858
897
  }
898
+ else {
899
+ // Page became visible again (e.g. tab switch back) — reset guard
900
+ this.unloadFlushed = false;
901
+ }
859
902
  };
860
903
  window.addEventListener('visibilitychange', this.boundVisibilityChange);
861
- // Flush on page hide (iOS Safari)
862
904
  this.boundPageHide = () => this.flushSync();
863
905
  window.addEventListener('pagehide', this.boundPageHide);
906
+ // Pause queue when offline, resume + flush when back online
907
+ this.boundOnline = () => {
908
+ logger.info('Connection restored — flushing queued events');
909
+ this.isOnline = true;
910
+ this.flush();
911
+ };
912
+ this.boundOffline = () => {
913
+ logger.warn('Connection lost — pausing event queue');
914
+ this.isOnline = false;
915
+ };
916
+ window.addEventListener('online', this.boundOnline);
917
+ window.addEventListener('offline', this.boundOffline);
864
918
  }
865
919
  /**
866
920
  * Persist queue to storage based on persistMode
@@ -943,6 +997,8 @@
943
997
  * Clianta SDK - Page View Plugin
944
998
  * @see SDK_VERSION in core/config.ts
945
999
  */
1000
+ /** Sentinel flag to prevent double-wrapping history methods across multiple SDK instances */
1001
+ const WRAPPED_FLAG = '__clianta_pv_wrapped__';
946
1002
  /**
947
1003
  * Page View Plugin - Tracks page views
948
1004
  */
@@ -952,50 +1008,64 @@
952
1008
  this.name = 'pageView';
953
1009
  this.originalPushState = null;
954
1010
  this.originalReplaceState = null;
1011
+ this.navHandler = null;
955
1012
  this.popstateHandler = null;
956
1013
  }
957
1014
  init(tracker) {
958
1015
  super.init(tracker);
959
1016
  // Track initial page view
960
1017
  this.trackPageView();
961
- // Track SPA navigation (History API)
962
- if (typeof window !== 'undefined') {
963
- // Store originals for cleanup
1018
+ if (typeof window === 'undefined')
1019
+ return;
1020
+ // Only wrap history methods once — guard against multiple SDK instances (e.g. microfrontends)
1021
+ // wrapping them repeatedly, which would cause duplicate navigation events and broken cleanup.
1022
+ if (!history.pushState[WRAPPED_FLAG]) {
964
1023
  this.originalPushState = history.pushState;
965
1024
  this.originalReplaceState = history.replaceState;
966
- // Intercept pushState and replaceState
967
- const self = this;
1025
+ const originalPush = this.originalPushState;
1026
+ const originalReplace = this.originalReplaceState;
968
1027
  history.pushState = function (...args) {
969
- self.originalPushState.apply(history, args);
970
- self.trackPageView();
971
- // Notify other plugins (e.g. ScrollPlugin) about navigation
1028
+ originalPush.apply(history, args);
1029
+ // Dispatch event so all listening instances track the navigation
972
1030
  window.dispatchEvent(new Event('clianta:navigation'));
973
1031
  };
1032
+ history.pushState[WRAPPED_FLAG] = true;
974
1033
  history.replaceState = function (...args) {
975
- self.originalReplaceState.apply(history, args);
976
- self.trackPageView();
1034
+ originalReplace.apply(history, args);
977
1035
  window.dispatchEvent(new Event('clianta:navigation'));
978
1036
  };
979
- // Handle back/forward navigation
980
- this.popstateHandler = () => this.trackPageView();
981
- window.addEventListener('popstate', this.popstateHandler);
1037
+ history.replaceState[WRAPPED_FLAG] = true;
982
1038
  }
1039
+ // Each instance listens to the shared navigation event rather than embedding
1040
+ // tracking directly in the pushState wrapper — decouples tracking from wrapping.
1041
+ this.navHandler = () => this.trackPageView();
1042
+ window.addEventListener('clianta:navigation', this.navHandler);
1043
+ // Handle back/forward navigation
1044
+ this.popstateHandler = () => this.trackPageView();
1045
+ window.addEventListener('popstate', this.popstateHandler);
983
1046
  }
984
1047
  destroy() {
985
- // Restore original history methods
1048
+ if (typeof window !== 'undefined') {
1049
+ if (this.navHandler) {
1050
+ window.removeEventListener('clianta:navigation', this.navHandler);
1051
+ this.navHandler = null;
1052
+ }
1053
+ if (this.popstateHandler) {
1054
+ window.removeEventListener('popstate', this.popstateHandler);
1055
+ this.popstateHandler = null;
1056
+ }
1057
+ }
1058
+ // Restore original history methods only if this instance was the one that wrapped them
986
1059
  if (this.originalPushState) {
987
1060
  history.pushState = this.originalPushState;
1061
+ delete history.pushState[WRAPPED_FLAG];
988
1062
  this.originalPushState = null;
989
1063
  }
990
1064
  if (this.originalReplaceState) {
991
1065
  history.replaceState = this.originalReplaceState;
1066
+ delete history.replaceState[WRAPPED_FLAG];
992
1067
  this.originalReplaceState = null;
993
1068
  }
994
- // Remove popstate listener
995
- if (this.popstateHandler && typeof window !== 'undefined') {
996
- window.removeEventListener('popstate', this.popstateHandler);
997
- this.popstateHandler = null;
998
- }
999
1069
  super.destroy();
1000
1070
  }
1001
1071
  trackPageView() {
@@ -1124,6 +1194,7 @@
1124
1194
  this.trackedForms = new WeakSet();
1125
1195
  this.formInteractions = new Set();
1126
1196
  this.observer = null;
1197
+ this.observerTimer = null;
1127
1198
  this.listeners = [];
1128
1199
  }
1129
1200
  init(tracker) {
@@ -1132,13 +1203,21 @@
1132
1203
  return;
1133
1204
  // Track existing forms
1134
1205
  this.trackAllForms();
1135
- // Watch for dynamically added forms
1206
+ // Watch for dynamically added forms — debounced to avoid O(DOM) cost on every mutation
1136
1207
  if (typeof MutationObserver !== 'undefined') {
1137
- this.observer = new MutationObserver(() => this.trackAllForms());
1208
+ this.observer = new MutationObserver(() => {
1209
+ if (this.observerTimer)
1210
+ clearTimeout(this.observerTimer);
1211
+ this.observerTimer = setTimeout(() => this.trackAllForms(), 100);
1212
+ });
1138
1213
  this.observer.observe(document.body, { childList: true, subtree: true });
1139
1214
  }
1140
1215
  }
1141
1216
  destroy() {
1217
+ if (this.observerTimer) {
1218
+ clearTimeout(this.observerTimer);
1219
+ this.observerTimer = null;
1220
+ }
1142
1221
  if (this.observer) {
1143
1222
  this.observer.disconnect();
1144
1223
  this.observer = null;
@@ -1260,8 +1339,13 @@
1260
1339
  super.destroy();
1261
1340
  }
1262
1341
  handleClick(e) {
1263
- const target = e.target;
1264
- if (!target || !isTrackableClickElement(target))
1342
+ // Walk up the DOM to find the nearest trackable ancestor.
1343
+ // Without this, clicks on <span> or <img> inside a <button> are silently dropped.
1344
+ let target = e.target;
1345
+ while (target && !isTrackableClickElement(target)) {
1346
+ target = target.parentElement;
1347
+ }
1348
+ if (!target)
1265
1349
  return;
1266
1350
  const buttonText = getElementText(target, 100);
1267
1351
  const elementInfo = getElementInfo(target);
@@ -1294,6 +1378,8 @@
1294
1378
  this.engagementStartTime = 0;
1295
1379
  this.isEngaged = false;
1296
1380
  this.engagementTimeout = null;
1381
+ /** Guard: beforeunload + visibilitychange:hidden both fire on tab close — only report once */
1382
+ this.unloadReported = false;
1297
1383
  this.boundMarkEngaged = null;
1298
1384
  this.boundTrackTimeOnPage = null;
1299
1385
  this.boundVisibilityHandler = null;
@@ -1315,8 +1401,9 @@
1315
1401
  this.trackTimeOnPage();
1316
1402
  }
1317
1403
  else {
1318
- // Reset engagement timer when page becomes visible again
1404
+ // Page is visible again reset both the time counter and the unload guard
1319
1405
  this.engagementStartTime = Date.now();
1406
+ this.unloadReported = false;
1320
1407
  }
1321
1408
  };
1322
1409
  ['mousemove', 'keydown', 'touchstart', 'scroll'].forEach((event) => {
@@ -1362,6 +1449,7 @@
1362
1449
  this.pageLoadTime = Date.now();
1363
1450
  this.engagementStartTime = Date.now();
1364
1451
  this.isEngaged = false;
1452
+ this.unloadReported = false;
1365
1453
  if (this.engagementTimeout) {
1366
1454
  clearTimeout(this.engagementTimeout);
1367
1455
  this.engagementTimeout = null;
@@ -1383,6 +1471,10 @@
1383
1471
  }, 30000); // 30 seconds of inactivity
1384
1472
  }
1385
1473
  trackTimeOnPage() {
1474
+ // Guard: beforeunload and visibilitychange:hidden both fire on tab close — only report once
1475
+ if (this.unloadReported)
1476
+ return;
1477
+ this.unloadReported = true;
1386
1478
  const timeSpent = Math.floor((Date.now() - this.engagementStartTime) / 1000);
1387
1479
  if (timeSpent > 0) {
1388
1480
  this.track('time_on_page', 'Time Spent', {
@@ -1541,12 +1633,16 @@
1541
1633
  /**
1542
1634
  * Error Tracking Plugin - Tracks JavaScript errors
1543
1635
  */
1636
+ /** Max unique errors to track per page (prevents queue flooding from error loops) */
1637
+ const MAX_UNIQUE_ERRORS = 20;
1544
1638
  class ErrorsPlugin extends BasePlugin {
1545
1639
  constructor() {
1546
1640
  super(...arguments);
1547
1641
  this.name = 'errors';
1548
1642
  this.boundErrorHandler = null;
1549
1643
  this.boundRejectionHandler = null;
1644
+ /** Seen error fingerprints — deduplicates repeated identical errors */
1645
+ this.seenErrors = new Set();
1550
1646
  }
1551
1647
  init(tracker) {
1552
1648
  super.init(tracker);
@@ -1569,6 +1665,9 @@
1569
1665
  super.destroy();
1570
1666
  }
1571
1667
  handleError(e) {
1668
+ const fingerprint = `${e.message}:${e.filename}:${e.lineno}`;
1669
+ if (!this.dedup(fingerprint))
1670
+ return;
1572
1671
  this.track('error', 'JavaScript Error', {
1573
1672
  message: e.message,
1574
1673
  filename: e.filename,
@@ -1578,9 +1677,22 @@
1578
1677
  });
1579
1678
  }
1580
1679
  handleRejection(e) {
1581
- this.track('error', 'Unhandled Promise Rejection', {
1582
- reason: String(e.reason).substring(0, 200),
1583
- });
1680
+ const reason = String(e.reason).substring(0, 200);
1681
+ if (!this.dedup(reason))
1682
+ return;
1683
+ this.track('error', 'Unhandled Promise Rejection', { reason });
1684
+ }
1685
+ /**
1686
+ * Returns true if this error fingerprint is new (should be tracked).
1687
+ * Caps at MAX_UNIQUE_ERRORS to prevent queue flooding from error loops.
1688
+ */
1689
+ dedup(fingerprint) {
1690
+ if (this.seenErrors.has(fingerprint))
1691
+ return false;
1692
+ if (this.seenErrors.size >= MAX_UNIQUE_ERRORS)
1693
+ return false;
1694
+ this.seenErrors.add(fingerprint);
1695
+ return true;
1584
1696
  }
1585
1697
  }
1586
1698
 
@@ -3519,28 +3631,17 @@
3519
3631
  }
3520
3632
  const prevId = previousId || this.visitorId;
3521
3633
  logger.info('Aliasing visitor:', { from: prevId, to: newId });
3522
- try {
3523
- const url = `${this.config.apiEndpoint}/api/public/track/alias`;
3524
- const response = await fetch(url, {
3525
- method: 'POST',
3526
- headers: { 'Content-Type': 'application/json' },
3527
- body: JSON.stringify({
3528
- workspaceId: this.workspaceId,
3529
- previousId: prevId,
3530
- newId,
3531
- }),
3532
- });
3533
- if (response.ok) {
3534
- logger.info('Alias successful');
3535
- return true;
3536
- }
3537
- logger.error('Alias failed:', response.status);
3538
- return false;
3539
- }
3540
- catch (error) {
3541
- logger.error('Alias request failed:', error);
3542
- return false;
3634
+ const result = await this.transport.sendPost('/api/public/track/alias', {
3635
+ workspaceId: this.workspaceId,
3636
+ previousId: prevId,
3637
+ newId,
3638
+ });
3639
+ if (result.success) {
3640
+ logger.info('Alias successful');
3641
+ return true;
3543
3642
  }
3643
+ logger.error('Alias failed:', result.error ?? result.status);
3644
+ return false;
3544
3645
  }
3545
3646
  /**
3546
3647
  * Track a screen view (for mobile-first PWAs and SPAs).
@@ -3903,13 +4004,24 @@
3903
4004
  * });
3904
4005
  */
3905
4006
  function clianta(workspaceId, config) {
3906
- // Return existing instance if same workspace
4007
+ // Return existing instance if same workspace and no config change
3907
4008
  if (globalInstance && globalInstance.getWorkspaceId() === workspaceId) {
4009
+ if (config && Object.keys(config).length > 0) {
4010
+ // Config was passed to an already-initialized instance — warn the developer
4011
+ // because the new config is ignored. They must call destroy() first to reconfigure.
4012
+ if (typeof console !== 'undefined') {
4013
+ console.warn('[Clianta] clianta() called with config on an already-initialized instance ' +
4014
+ 'for workspace "' + workspaceId + '". The new config was ignored. ' +
4015
+ 'Call tracker.destroy() first if you need to reconfigure.');
4016
+ }
4017
+ }
3908
4018
  return globalInstance;
3909
4019
  }
3910
- // Destroy existing instance if workspace changed
4020
+ // Destroy existing instance if workspace changed (fire-and-forget flush, then destroy)
3911
4021
  if (globalInstance) {
3912
- globalInstance.destroy();
4022
+ // Kick off async flush+destroy without blocking the new instance creation.
4023
+ // Using void to make the intentional fire-and-forget explicit.
4024
+ void globalInstance.destroy();
3913
4025
  }
3914
4026
  // Create new instance
3915
4027
  globalInstance = new Tracker(workspaceId, config);
@@ -3937,8 +4049,21 @@
3937
4049
  const projectId = script.getAttribute('data-project-id');
3938
4050
  if (!projectId)
3939
4051
  return;
3940
- const debug = script.hasAttribute('data-debug');
3941
- const instance = clianta(projectId, { debug });
4052
+ const initConfig = {
4053
+ debug: script.hasAttribute('data-debug'),
4054
+ };
4055
+ // Support additional config via script tag attributes:
4056
+ // data-api-endpoint="https://api.yourhost.com"
4057
+ // data-cookieless (boolean flag)
4058
+ // data-use-cookies (boolean flag)
4059
+ const apiEndpoint = script.getAttribute('data-api-endpoint');
4060
+ if (apiEndpoint)
4061
+ initConfig.apiEndpoint = apiEndpoint;
4062
+ if (script.hasAttribute('data-cookieless'))
4063
+ initConfig.cookielessMode = true;
4064
+ if (script.hasAttribute('data-use-cookies'))
4065
+ initConfig.useCookies = true;
4066
+ const instance = clianta(projectId, initConfig);
3942
4067
  // Expose the auto-initialized instance globally
3943
4068
  window.__clianta = instance;
3944
4069
  };