@datalyr/web 1.7.0 → 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
- * @datalyr/web v1.7.0
2
+ * @datalyr/web v1.7.1
3
3
  * Datalyr Web SDK - Modern attribution tracking for web applications
4
4
  * (c) 2026 Datalyr Inc.
5
5
  * Released under the MIT License
@@ -1408,13 +1408,19 @@ class AttributionManager {
1408
1408
  attribution[key] = value;
1409
1409
  }
1410
1410
  }
1411
- // Capture click IDs
1411
+ // Capture click IDs. The first present (by CLICK_IDS priority) is the primary
1412
+ // clickId/clickIdType, but ALSO capture every present click ID as its own named
1413
+ // field — a single URL can carry both fbclid and gclid (redirect chains, forwarded
1414
+ // / re-shared links), and keeping only the first dropped the others' platform
1415
+ // attribution entirely. (WEB NEW-3)
1412
1416
  for (const clickId of this.CLICK_IDS) {
1413
1417
  const value = params[clickId];
1414
1418
  if (value) {
1415
- attribution.clickId = value;
1416
- attribution.clickIdType = clickId;
1417
- break; // Use first found click ID
1419
+ if (!attribution.clickId) {
1420
+ attribution.clickId = value;
1421
+ attribution.clickIdType = clickId;
1422
+ }
1423
+ attribution[clickId] = value;
1418
1424
  }
1419
1425
  }
1420
1426
  // Capture custom tracked parameters
@@ -1544,7 +1550,10 @@ class AttributionManager {
1544
1550
  // Generate _fbp if missing (Facebook browser ID)
1545
1551
  if (!adCookies._fbp && (this.hasClickId('fbclid') || adCookies._fbc)) {
1546
1552
  const timestamp = Date.now();
1547
- const randomId = Math.random().toString(36).substring(2, 15);
1553
+ // Meta's _fbp format is fb.1.<creationTimeMs>.<randomNumber> where the last
1554
+ // segment MUST be a decimal integer. The old base36 string was non-conformant —
1555
+ // Meta ignores it (and it can shadow a real _fbp), degrading EMQ. (WEB-17)
1556
+ const randomId = Math.floor(Math.random() * 1e10).toString();
1548
1557
  adCookies._fbp = `fb.1.${timestamp}.${randomId}`;
1549
1558
  // Optionally set the cookie for future use
1550
1559
  cookies.set('_fbp', adCookies._fbp, 90);
@@ -1603,23 +1612,30 @@ class AttributionManager {
1603
1612
  const lastTouch = this.getLastTouch();
1604
1613
  const journey = this.getJourney();
1605
1614
  let current = this.captureAttribution();
1606
- // CRITICAL FIX: If current session has no attribution (direct/organic),
1607
- // fallback to persistent attribution from localStorage (90-day window)
1608
- const hasCurrentAttribution = !!(current.source || current.medium || current.clickId || current.campaign);
1609
- if (!hasCurrentAttribution && firstTouch) {
1610
- // Check if persistent attribution is still valid
1615
+ // A "real" attribution signal on THIS pageview = a click ID, a UTM/campaign, or a
1616
+ // referrer/UTM-derived source. determineSource()/determineMedium() FLOOR to
1617
+ // 'direct'/'none', so the mere presence of current.source/medium is NOT a signal.
1618
+ // The old `hasCurrentAttribution` (truthy because source is always at least 'direct')
1619
+ // made the fallback below dead code AND caused storeLastTouch to overwrite a real
1620
+ // paid last-touch with 'direct'/'none' on the next internal navigation. (WEB NEW-1)
1621
+ const hasRealAttribution = !!(current.clickId ||
1622
+ current.campaign ||
1623
+ (current.source && current.source !== 'direct'));
1624
+ if (!hasRealAttribution && firstTouch) {
1625
+ // Direct / internal navigation: fall back to persistent attribution (90-day
1626
+ // window) so the event isn't mis-attributed to 'direct', keeping page context.
1611
1627
  if (!firstTouch.expires_at || Date.now() < firstTouch.expires_at) {
1612
- // Use persistent attribution but keep current page context
1613
1628
  current = Object.assign(Object.assign({}, firstTouch), { referrer: current.referrer, referrerHost: current.referrerHost, landingPage: current.landingPage, landingPath: current.landingPath });
1614
1629
  }
1615
1630
  }
1616
1631
  // Capture advertising cookies automatically
1617
1632
  const adCookies = this.captureAdCookies();
1618
- // Update first/last touch if needed
1619
- if (!firstTouch && Object.keys(current).length > 1) {
1633
+ // Only (re)write first/last touch when this pageview carried a REAL signal — never
1634
+ // overwrite stored attribution with the 'direct'/'none' floor of an internal nav.
1635
+ if (!firstTouch && hasRealAttribution) {
1620
1636
  this.storeFirstTouch(current);
1621
1637
  }
1622
- if (Object.keys(current).length > 1) {
1638
+ if (hasRealAttribution) {
1623
1639
  this.storeLastTouch(current);
1624
1640
  }
1625
1641
  return Object.assign(Object.assign(Object.assign({}, current), adCookies), {
@@ -1656,6 +1672,15 @@ class AttributionManager {
1656
1672
  // Check referrer
1657
1673
  if (attribution.referrerHost) {
1658
1674
  const host = attribution.referrerHost.toLowerCase();
1675
+ // Same-site referrer = internal navigation, NOT a new acquisition source.
1676
+ // Without this, a full-page internal nav (referrer = our own domain, common on
1677
+ // classic multi-page stores) classifies as 'referral', which makes
1678
+ // hasRealAttribution true and overwrites the real paid last-touch. Treat it as
1679
+ // direct so the last-touch guard preserves the genuine source.
1680
+ const currentHost = (typeof window !== 'undefined' ? window.location.hostname : '').toLowerCase();
1681
+ if (currentHost && (host === currentHost || this.isSameRootDomain(host, currentHost))) {
1682
+ return 'direct';
1683
+ }
1659
1684
  // Social sources
1660
1685
  if (host.includes('facebook.com') || host.includes('fb.com'))
1661
1686
  return 'facebook';
@@ -1713,6 +1738,16 @@ class AttributionManager {
1713
1738
  }
1714
1739
  return 'referral';
1715
1740
  }
1741
+ /**
1742
+ * Whether two hosts share the same root domain (eTLD+1 approximation), so that
1743
+ * cross-subdomain internal navigation (e.g. shop.example.com → checkout.example.com)
1744
+ * is also treated as same-site. Not a full public-suffix parse — good enough to keep
1745
+ * internal navs from being mis-classified as referral.
1746
+ */
1747
+ isSameRootDomain(a, b) {
1748
+ const root = (h) => h.split('.').slice(-2).join('.');
1749
+ return root(a) === root(b);
1750
+ }
1716
1751
  /**
1717
1752
  * Extract hostname from URL
1718
1753
  */
@@ -1754,6 +1789,11 @@ class AttributionManager {
1754
1789
  const DEFAULT_CRITICAL_EVENTS = ['purchase', 'signup', 'subscribe', 'lead', 'conversion'];
1755
1790
  // Default high priority events that use faster batching
1756
1791
  const DEFAULT_HIGH_PRIORITY_EVENTS = ['add_to_cart', 'begin_checkout', 'view_item', 'search'];
1792
+ // A 429 is a deliberate backpressure signal, not a transient failure — tagged so the
1793
+ // send path can route it to the offline queue WITHOUT retrying (which would storm the
1794
+ // already-overloaded server). See sendBatch / the rateLimitedUntil gate.
1795
+ class RateLimitError extends Error {
1796
+ }
1757
1797
  class EventQueue {
1758
1798
  constructor(config) {
1759
1799
  this.queue = [];
@@ -1766,18 +1806,29 @@ class EventQueue {
1766
1806
  this.OFFLINE_QUEUE_KEY = 'dl_offline_queue';
1767
1807
  this.flushLock = false; // FIXED (DATA-03): Mutex to prevent race conditions
1768
1808
  this.offlineQueueLock = false; // FIXED (DATA-03): Separate lock for offline queue operations
1809
+ this.offlineProcessing = false; // FIXED (WEB-1): re-entrancy guard for processOfflineQueue
1810
+ this.inFlight = []; // FIXED (WEB-3): batch currently in _flight's keepalive fetch — forceFlush must NOT re-beacon it
1811
+ this.enabled = true; // FIXED (consent): when false (opt-out / withdrawn analytics consent) all enqueue/flush/drain is a no-op
1812
+ this.rateLimitedUntil = 0; // FIXED (429): skip flush/drain until the server's Retry-After window passes
1813
+ // Coerce numeric config to sane values. The old `config.X || default` both turned a
1814
+ // legitimate 0 into the default AND let invalid values through — a NEGATIVE batchSize
1815
+ // made processOfflineQueue's `splice(0, -1)` loop forever and FREEZE the host tab.
1816
+ const clampInt = (v, def, min, max) => {
1817
+ const n = Number(v);
1818
+ return Number.isFinite(n) ? Math.min(Math.max(Math.floor(n), min), max) : def;
1819
+ };
1769
1820
  this.config = {
1770
- batchSize: config.batchSize || 10,
1771
- flushInterval: config.flushInterval || 5000,
1772
- maxRetries: config.maxRetries || 5,
1773
- retryDelay: config.retryDelay || 1000,
1821
+ batchSize: clampInt(config.batchSize, 10, 1, 1000),
1822
+ flushInterval: clampInt(config.flushInterval, 5000, 250, 3600000),
1823
+ maxRetries: clampInt(config.maxRetries, 5, 0, 20),
1824
+ retryDelay: clampInt(config.retryDelay, 1000, 0, 60000),
1774
1825
  endpoint: config.endpoint || 'https://ingest.datalyr.com',
1775
- fallbackEndpoints: config.fallbackEndpoints || [],
1826
+ fallbackEndpoints: Array.isArray(config.fallbackEndpoints) ? config.fallbackEndpoints : [],
1776
1827
  workspaceId: config.workspaceId,
1777
1828
  debug: config.debug || false,
1778
1829
  criticalEvents: config.criticalEvents || DEFAULT_CRITICAL_EVENTS,
1779
1830
  highPriorityEvents: config.highPriorityEvents || DEFAULT_HIGH_PRIORITY_EVENTS,
1780
- maxOfflineQueueSize: config.maxOfflineQueueSize || 100
1831
+ maxOfflineQueueSize: clampInt(config.maxOfflineQueueSize, 100, 1, 100000)
1781
1832
  };
1782
1833
  this.networkStatus = {
1783
1834
  isOnline: navigator.onLine !== false,
@@ -1787,11 +1838,22 @@ class EventQueue {
1787
1838
  this.loadOfflineQueue();
1788
1839
  this.setupNetworkListeners();
1789
1840
  this.startPeriodicFlush();
1841
+ // WEB-1: a previous session may have left events in the persisted offline queue.
1842
+ // The 'online' listener only fires on an offline→online TRANSITION, which never
1843
+ // happens for a visitor who returns already-online — so drain on startup too,
1844
+ // otherwise those events (incl. failed revenue conversions) just age out.
1845
+ if (this.networkStatus.isOnline && this.offlineQueue.length > 0) {
1846
+ setTimeout(() => this.processOfflineQueue(), 1000);
1847
+ }
1790
1848
  }
1791
1849
  /**
1792
1850
  * Add event to queue
1793
1851
  */
1794
1852
  enqueue(event) {
1853
+ // Consent gate: opt-out / withdrawn analytics consent stops all sending. (The SDK
1854
+ // also gates at track(), but this is the backstop for anything that reaches here.)
1855
+ if (!this.enabled)
1856
+ return;
1795
1857
  const eventName = event.event_name; // Use snake_case
1796
1858
  // Check for duplicates (within 500ms window)
1797
1859
  if (this.isDuplicateEvent(event)) {
@@ -1890,6 +1952,11 @@ class EventQueue {
1890
1952
  */
1891
1953
  flush() {
1892
1954
  return __awaiter(this, void 0, void 0, function* () {
1955
+ if (!this.enabled)
1956
+ return;
1957
+ // FIXED (429): respect the server's Retry-After window instead of hammering it.
1958
+ if (Date.now() < this.rateLimitedUntil)
1959
+ return;
1893
1960
  // FIXED (DATA-03): Check both promise and lock for concurrent flush protection
1894
1961
  if (this.flushPromise || this.flushLock) {
1895
1962
  return this.flushPromise || Promise.resolve();
@@ -1931,6 +1998,12 @@ class EventQueue {
1931
1998
  // Only remove after successful send to prevent data loss
1932
1999
  const batchSize = Math.min(this.config.batchSize, this.queue.length);
1933
2000
  const events = this.queue.slice(0, batchSize);
2001
+ // WEB-3 (HIGH-1): mark this batch as in-flight. sendBatch's fetch uses
2002
+ // keepalive:true, so it survives an unload that fires mid-flush — forceFlush
2003
+ // reads `inFlight` to avoid re-beaconing the very events this fetch is sending.
2004
+ // `inFlight` is always the FRONT `batchSize` of this.queue while flushLock holds
2005
+ // (enqueue only pushes to the back; flushLock serializes _flush bodies).
2006
+ this.inFlight = events;
1934
2007
  try {
1935
2008
  yield this.sendBatch(events);
1936
2009
  // SUCCESS: Now it's safe to remove events from queue
@@ -1939,10 +2012,17 @@ class EventQueue {
1939
2012
  }
1940
2013
  catch (error) {
1941
2014
  this.log('Failed to send batch:', error);
1942
- // Don't remove from queue - events stay for retry
1943
- // Move to offline queue for persistent storage
2015
+ // WEB-8: make the offline queue the SINGLE owner of these events. Previously
2016
+ // they stayed in the live queue AND were copied to the offline queue, so a
2017
+ // later success on both paths double-sent (relying on server-side dedup).
2018
+ // Remove the same slice from the live queue; the offline queue now drains on
2019
+ // every periodic tick (WEB-1/WEB-2), so they are still retried, not stranded.
2020
+ this.queue.splice(0, batchSize);
1944
2021
  this.moveToOfflineQueue(events);
1945
2022
  }
2023
+ finally {
2024
+ this.inFlight = [];
2025
+ }
1946
2026
  });
1947
2027
  }
1948
2028
  /**
@@ -1972,21 +2052,27 @@ class EventQueue {
1972
2052
  // Handle rate limiting
1973
2053
  if (response.status === 429) {
1974
2054
  const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
1975
- this.log(`Rate limited, retrying after ${retryAfter}s`);
1976
- // FIXED (CRITICAL-06): Don't unshift() - events are still in queue!
1977
- // With the new fix, events aren't removed until success, so they're
1978
- // already in the queue. Just schedule a retry flush.
1979
- setTimeout(() => {
1980
- this.flush();
1981
- }, retryAfter * 1000);
1982
- // Throw to trigger catch block which moves events to offline queue
1983
- throw new Error(`Rate limited (429), retry after ${retryAfter}s`);
2055
+ // FIXED (429 retry-storm): honor Retry-After as a SINGLE backoff window. The
2056
+ // old code scheduled a flush AND let the throw fall into the generic
2057
+ // exponential-backoff retry below firing ~6 requests inside the window the
2058
+ // server asked us to wait, amplifying an ingest overload. Now: record the
2059
+ // window and throw a RateLimitError (which the catch does NOT retry). The
2060
+ // events move to the offline queue and drain once the window passes.
2061
+ this.rateLimitedUntil = Date.now() + Math.max(retryAfter, 1) * 1000;
2062
+ this.log(`Rate limited; backing off ${retryAfter}s`);
2063
+ throw new RateLimitError('Rate limited (429)');
1984
2064
  }
1985
2065
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1986
2066
  }
1987
2067
  this.log(`Batch sent successfully to ${currentEndpoint}: ${events.length} events`);
1988
2068
  }
1989
2069
  catch (error) {
2070
+ // A 429 is deliberate backpressure — do NOT retry it here (neither fallback nor
2071
+ // backoff). Propagate so the batch moves to the offline queue; the periodic drain
2072
+ // resumes only after rateLimitedUntil. This is what prevents the retry storm.
2073
+ if (error instanceof RateLimitError) {
2074
+ throw error;
2075
+ }
1990
2076
  // Try next fallback endpoint if available
1991
2077
  if (endpointIndex < endpoints.length - 1) {
1992
2078
  this.log(`Failed on ${currentEndpoint}, trying fallback ${endpointIndex + 1}`);
@@ -2028,6 +2114,13 @@ class EventQueue {
2028
2114
  if (this.queue.length > 0) {
2029
2115
  this.flush();
2030
2116
  }
2117
+ // WEB-1/WEB-2: also drain persisted offline events (including failed critical
2118
+ // events that enqueue() parked here) on every tick — not only on an 'online'
2119
+ // transition that may never fire. This is what gives parked purchase/lead
2120
+ // events a retry path while the user stays online.
2121
+ if (this.networkStatus.isOnline && this.offlineQueue.length > 0) {
2122
+ this.processOfflineQueue();
2123
+ }
2031
2124
  }, this.config.flushInterval);
2032
2125
  }
2033
2126
  /**
@@ -2046,6 +2139,12 @@ class EventQueue {
2046
2139
  * FIXED (CRITICAL-06): Can now accept specific events or move entire queue
2047
2140
  */
2048
2141
  moveToOfflineQueue(events) {
2142
+ // Consent leak fix: do NOT persist for a disabled queue. Without this, an
2143
+ // in-flight _flush (or critical-event send) that FAILS after optOut() has purged
2144
+ // the offline queue would re-write the PII-bearing event to storage AFTER the
2145
+ // purge. Gating here (a persistence sink, not just the send sinks) closes it.
2146
+ if (!this.enabled)
2147
+ return;
2049
2148
  // FIXED (DATA-03): Check if offline queue operation already in progress
2050
2149
  if (this.offlineQueueLock) {
2051
2150
  console.warn('[Datalyr Queue] Offline queue operation already in progress');
@@ -2089,6 +2188,10 @@ class EventQueue {
2089
2188
  * Save offline queue to storage
2090
2189
  */
2091
2190
  saveOfflineQueue() {
2191
+ // Defense-in-depth twin of the moveToOfflineQueue gate: never write PII to disk
2192
+ // for a disabled (opted-out) queue.
2193
+ if (!this.enabled)
2194
+ return;
2092
2195
  // Keep max events based on config
2093
2196
  const toSave = this.offlineQueue.slice(-this.config.maxOfflineQueueSize);
2094
2197
  storage.set(this.OFFLINE_QUEUE_KEY, toSave);
@@ -2098,25 +2201,46 @@ class EventQueue {
2098
2201
  */
2099
2202
  processOfflineQueue() {
2100
2203
  return __awaiter(this, void 0, void 0, function* () {
2204
+ // WEB-1: guard against re-entrancy. This is now driven from three places (the
2205
+ // 'online' listener, the periodic flush, and the on-load kick); without a guard
2206
+ // two of them could splice the same offlineQueue concurrently and double-send.
2207
+ if (!this.enabled)
2208
+ return;
2209
+ if (Date.now() < this.rateLimitedUntil)
2210
+ return; // FIXED (429): honor Retry-After window
2211
+ if (this.offlineProcessing)
2212
+ return;
2101
2213
  if (this.offlineQueue.length === 0)
2102
2214
  return;
2103
- this.log(`Processing ${this.offlineQueue.length} offline events`);
2104
- while (this.offlineQueue.length > 0) {
2105
- const batch = this.offlineQueue.splice(0, this.config.batchSize);
2106
- try {
2107
- yield this.sendBatch(batch);
2108
- this.saveOfflineQueue();
2215
+ if (!this.networkStatus.isOnline)
2216
+ return;
2217
+ this.offlineProcessing = true;
2218
+ try {
2219
+ this.log(`Processing ${this.offlineQueue.length} offline events`);
2220
+ while (this.offlineQueue.length > 0) {
2221
+ // Stop mid-drain if disabled (opt-out during an active drain) — otherwise the
2222
+ // unshift-on-failure below would re-persist a batch after optOut's purge.
2223
+ if (!this.enabled)
2224
+ break;
2225
+ const batch = this.offlineQueue.splice(0, this.config.batchSize);
2226
+ try {
2227
+ yield this.sendBatch(batch);
2228
+ this.saveOfflineQueue();
2229
+ }
2230
+ catch (error) {
2231
+ this.log('Failed to send offline batch:', error);
2232
+ // Put back in queue
2233
+ this.offlineQueue.unshift(...batch);
2234
+ this.saveOfflineQueue();
2235
+ break;
2236
+ }
2109
2237
  }
2110
- catch (error) {
2111
- this.log('Failed to send offline batch:', error);
2112
- // Put back in queue
2113
- this.offlineQueue.unshift(...batch);
2114
- this.saveOfflineQueue();
2115
- break;
2238
+ if (this.offlineQueue.length === 0) {
2239
+ storage.remove(this.OFFLINE_QUEUE_KEY);
2116
2240
  }
2117
2241
  }
2118
- if (this.offlineQueue.length === 0) {
2119
- storage.remove(this.OFFLINE_QUEUE_KEY);
2242
+ finally {
2243
+ this.offlineProcessing = false;
2120
2244
  }
2121
2245
  });
2122
2246
  }
@@ -2138,30 +2262,103 @@ class EventQueue {
2138
2262
  getNetworkStatus() {
2139
2263
  return Object.assign({}, this.networkStatus);
2140
2264
  }
2265
+ /**
2266
+ * Build a batch payload from a set of events.
2267
+ */
2268
+ buildBatch(events) {
2269
+ return {
2270
+ events,
2271
+ batchId: generateUUID(),
2272
+ timestamp: new Date().toISOString()
2273
+ };
2274
+ }
2141
2275
  /**
2142
2276
  * Force flush (for page unload)
2277
+ * FIXED (WEB-3): include the offline queue, chunk under sendBeacon's ~64KB cap,
2278
+ * and persist any chunk the browser refuses so it survives to the next page load.
2279
+ * Previously this beaconed the live queue as one blob — ignoring the offline queue
2280
+ * entirely and silently failing (returning false) whenever the payload exceeded 64KB.
2281
+ *
2282
+ * Two follow-up review fixes:
2283
+ * - HIGH-1: exclude any batch currently in-flight in _flush(). That batch is being
2284
+ * sent with a keepalive fetch that already survives unload; re-beaconing it would
2285
+ * double-send. (`inFlight` is the front `inFlight.length` events of this.queue.)
2286
+ * - HIGH-2: handleUnload is wired to visibilitychange+pagehide+beforeunload, so this
2287
+ * runs multiple times per lifecycle. Detach what we beacon SYNCHRONOUSLY (clear the
2288
+ * in-memory queues, persist a refused remainder straight to storage rather than back
2289
+ * into this.offlineQueue) so a repeat call finds nothing to re-send.
2143
2290
  */
2144
2291
  forceFlush() {
2145
2292
  return __awaiter(this, void 0, void 0, function* () {
2146
- // Try sendBeacon first for reliability
2147
- if (navigator.sendBeacon && this.queue.length > 0) {
2148
- const batchPayload = {
2149
- events: this.queue,
2150
- batchId: generateUUID(),
2151
- timestamp: new Date().toISOString()
2152
- };
2153
- const blob = new Blob([JSON.stringify(batchPayload)], {
2293
+ if (!this.enabled)
2294
+ return;
2295
+ if (!navigator.sendBeacon) {
2296
+ // No beacon API — best-effort keepalive-fetch drain of both queues.
2297
+ yield this.flush();
2298
+ yield this.processOfflineQueue();
2299
+ return;
2300
+ }
2301
+ // Exclude the in-flight batch (its keepalive fetch already carries it).
2302
+ const live = this.queue.slice(this.inFlight.length);
2303
+ const pending = [...live, ...this.offlineQueue];
2304
+ // Detach synchronously: keep only the in-flight front (for _flush to settle) and
2305
+ // empty the offline queue, so a second unload event this lifecycle re-enters with
2306
+ // nothing to re-beacon. The refused remainder (if any) is persisted to STORAGE
2307
+ // below, not back into this.offlineQueue, for exactly this reason.
2308
+ this.queue = this.queue.slice(0, this.inFlight.length);
2309
+ this.offlineQueue = [];
2310
+ if (pending.length === 0)
2311
+ return;
2312
+ const MAX_BEACON_BYTES = 60000; // headroom under the browser's ~64KB cap
2313
+ // Greedily pack events into chunks bounded by BOTH batchSize and byte size.
2314
+ const chunks = [];
2315
+ let current = [];
2316
+ let currentBytes = 2; // approx for the JSON array/object wrapper
2317
+ for (const ev of pending) {
2318
+ // Byte length (not UTF-16 .length) so multibyte product names / emoji can't
2319
+ // under-count and overflow the cap.
2320
+ const evBytes = new Blob([JSON.stringify(ev)]).size + 1;
2321
+ if (current.length > 0 &&
2322
+ (current.length >= this.config.batchSize || currentBytes + evBytes > MAX_BEACON_BYTES)) {
2323
+ chunks.push(current);
2324
+ current = [];
2325
+ currentBytes = 2;
2326
+ }
2327
+ current.push(ev);
2328
+ currentBytes += evBytes;
2329
+ }
2330
+ if (current.length > 0)
2331
+ chunks.push(current);
2332
+ // Send each chunk; the moment the browser refuses to enqueue one, keep it and
2333
+ // everything after it for the next session.
2334
+ let failedFrom = -1;
2335
+ for (let c = 0; c < chunks.length; c++) {
2336
+ const blob = new Blob([JSON.stringify(this.buildBatch(chunks[c]))], {
2154
2337
  type: 'application/json'
2155
2338
  });
2156
- const success = navigator.sendBeacon(this.config.endpoint, blob);
2157
- if (success) {
2158
- this.log('Events sent via sendBeacon');
2159
- this.queue = [];
2160
- return;
2339
+ if (!navigator.sendBeacon(this.config.endpoint, blob)) {
2340
+ failedFrom = c;
2341
+ break;
2342
+ }
2343
+ }
2344
+ if (failedFrom >= 0) {
2345
+ const remainder = chunks
2346
+ .slice(failedFrom)
2347
+ .reduce((acc, c) => acc.concat(c), []);
2348
+ // Persist straight to storage (NOT this.offlineQueue) so a repeat unload event
2349
+ // won't re-beacon it; the next page load's drain (which uses a normal fetch with
2350
+ // no 64KB cap) delivers it. MED-2: log if the maxOfflineQueueSize cap truncates.
2351
+ const toPersist = remainder.slice(-this.config.maxOfflineQueueSize);
2352
+ if (remainder.length > toPersist.length) {
2353
+ this.log(`Offline cap dropped ${remainder.length - toPersist.length} oldest events at unload`);
2161
2354
  }
2355
+ storage.set(this.OFFLINE_QUEUE_KEY, toPersist);
2356
+ this.log(`sendBeacon refused ${remainder.length} events; persisted ${toPersist.length} for next load`);
2357
+ }
2358
+ else {
2359
+ this.log('Events sent via sendBeacon');
2360
+ storage.remove(this.OFFLINE_QUEUE_KEY);
2162
2361
  }
2163
- // Fallback to regular flush
2164
- yield this.flush();
2165
2362
  });
2166
2363
  }
2167
2364
  /**
@@ -2174,6 +2371,22 @@ class EventQueue {
2174
2371
  this.batchTimer = null;
2175
2372
  }
2176
2373
  }
2374
+ /**
2375
+ * Enable/disable all sending. Used by opt-out / withdrawn analytics consent so that
2376
+ * events persisted BEFORE opt-out aren't drained afterwards (the periodic drain and
2377
+ * the on-load drain both honor this).
2378
+ */
2379
+ setEnabled(enabled) {
2380
+ this.enabled = enabled;
2381
+ }
2382
+ /**
2383
+ * Clear the offline queue and its persisted copy (used by opt-out to purge any
2384
+ * PII-bearing events that were parked before the user opted out).
2385
+ */
2386
+ clearOffline() {
2387
+ this.offlineQueue = [];
2388
+ storage.remove(this.OFFLINE_QUEUE_KEY);
2389
+ }
2177
2390
  /**
2178
2391
  * Debug logging
2179
2392
  */
@@ -2870,7 +3083,7 @@ class ContainerManager {
2870
3083
  * Track event to all initialized pixels
2871
3084
  */
2872
3085
  trackToPixels(eventName, properties = {}, eventId) {
2873
- var _a, _b, _c, _e, _f, _g, _h, _j;
3086
+ var _a, _b, _c, _e, _f, _g, _h, _j, _k, _l;
2874
3087
  // Datalyr-internal events ($identify, $group, $alias, $auto_identify,
2875
3088
  // $app_download_click, …) are not conversions — never forward them to ad
2876
3089
  // pixels. (Previously they fired as noise custom events with the $ stripped.)
@@ -2936,16 +3149,31 @@ class ContainerManager {
2936
3149
  // Track to TikTok Pixel
2937
3150
  if (((_j = (_h = this.pixels) === null || _h === void 0 ? void 0 : _h.tiktok) === null || _j === void 0 ? void 0 : _j.enabled) && window.ttq) {
2938
3151
  try {
2939
- // Map common events to TikTok names
3152
+ // Map our event names to TikTok's standard vocabulary. BUG FIX (TikTok-dead):
3153
+ // this map was keyed on Meta-standard names ('Purchase') but looked up with the
3154
+ // sanitized RAW event ('purchase'), so EVERY standard event missed and fired as
3155
+ // a literal custom event (e.g. "purchase" instead of "CompletePayment") — all
3156
+ // TikTok conversions were mis-categorized. Now keyed on the lowercased raw name
3157
+ // and looked up the same way the Meta block does, with a workspace rule map first.
2940
3158
  const tiktokEventMap = {
2941
- 'Purchase': 'CompletePayment',
2942
- 'AddToCart': 'AddToCart',
2943
- 'InitiateCheckout': 'InitiateCheckout',
2944
- 'ViewContent': 'ViewContent',
2945
- 'Search': 'Search',
2946
- 'Lead': 'SubmitForm'
3159
+ view_content: 'ViewContent', product_viewed: 'ViewContent', view_item: 'ViewContent',
3160
+ search: 'Search',
3161
+ add_to_wishlist: 'AddToWishlist',
3162
+ add_to_cart: 'AddToCart', product_added: 'AddToCart',
3163
+ initiate_checkout: 'InitiateCheckout', begin_checkout: 'InitiateCheckout', checkout_started: 'InitiateCheckout',
3164
+ add_payment_info: 'AddPaymentInfo',
3165
+ purchase: 'CompletePayment', order_completed: 'CompletePayment', order_paid: 'CompletePayment',
3166
+ place_an_order: 'PlaceAnOrder',
3167
+ contact: 'Contact',
3168
+ download: 'Download',
3169
+ lead: 'SubmitForm', submit_form: 'SubmitForm',
3170
+ complete_registration: 'CompleteRegistration', sign_up: 'CompleteRegistration', signup: 'CompleteRegistration',
3171
+ subscribe: 'Subscribe', subscription_created: 'Subscribe',
2947
3172
  };
2948
- const tiktokEvent = tiktokEventMap[sanitizedEventName] || sanitizedEventName;
3173
+ const tiktokRuleMap = (_l = (_k = this.pixels) === null || _k === void 0 ? void 0 : _k.tiktok) === null || _l === void 0 ? void 0 : _l.event_mappings;
3174
+ const tiktokEvent = (tiktokRuleMap === null || tiktokRuleMap === void 0 ? void 0 : tiktokRuleMap[eventName])
3175
+ || tiktokEventMap[String(eventName).toLowerCase()]
3176
+ || sanitizedEventName;
2949
3177
  window.ttq.track(tiktokEvent, sanitizedProperties);
2950
3178
  }
2951
3179
  catch (error) {
@@ -3094,6 +3322,7 @@ class AutoIdentifyManager {
3094
3322
  this.formListeners = [];
3095
3323
  this.lastIdentifyTime = 0;
3096
3324
  this.RATE_LIMIT_MS = 5000; // Don't auto-identify more than once per 5 seconds
3325
+ this.destroyed = false; // set by destroy() (e.g. on opt-out) — stops any in-flight capture from re-persisting email
3097
3326
  this.config = {
3098
3327
  enabled: config.enabled !== false,
3099
3328
  captureFromForms: config.captureFromForms !== false,
@@ -3107,29 +3336,49 @@ class AutoIdentifyManager {
3107
3336
  * Initialize auto-identify system
3108
3337
  */
3109
3338
  initialize(identifyCallback) {
3110
- if (!this.config.enabled) {
3111
- this.log('Auto-identify disabled');
3112
- return;
3113
- }
3114
- this.identifyCallback = identifyCallback;
3115
- // Check if already identified
3116
- const existingEmail = storage.get('dl_auto_identified_email');
3117
- if (existingEmail) {
3118
- this.log('User already auto-identified:', existingEmail);
3119
- return;
3120
- }
3121
- // Setup monitoring
3122
- if (this.config.captureFromForms) {
3123
- this.setupFormMonitoring();
3124
- }
3125
- if (this.config.captureFromAPI) {
3126
- this.setupFetchInterception();
3127
- this.setupXHRInterception();
3128
- }
3129
- if (this.config.captureFromShopify) {
3130
- this.setupShopifyMonitoring();
3131
- }
3132
- this.log('Auto-identify initialized');
3339
+ return __awaiter(this, void 0, void 0, function* () {
3340
+ if (!this.config.enabled) {
3341
+ this.log('Auto-identify disabled');
3342
+ return;
3343
+ }
3344
+ this.identifyCallback = identifyCallback;
3345
+ // Check if already identified.
3346
+ // WEB-5: the captured email is PII — store it AES-GCM-encrypted (consistent with
3347
+ // dl_user_traits), not plaintext localStorage.
3348
+ const existingEmail = yield storage.getEncrypted('dl_auto_identified_email');
3349
+ if (existingEmail) {
3350
+ // Migration: a value written by a pre-1.7.1 build is PLAINTEXT. getEncrypted
3351
+ // returns it anyway — decrypt() has a backwards-compat fallback that hands back
3352
+ // the raw string when AES decryption fails — so without this step the PII would
3353
+ // stay in plaintext localStorage forever. Detect a legacy plaintext email by
3354
+ // inspecting the RAW stored bytes (ciphertext is base64, so an '@' means it was
3355
+ // never encrypted) and re-write it encrypted in place.
3356
+ const raw = storage.get('dl_auto_identified_email');
3357
+ if (typeof raw === 'string' && raw.includes('@')) {
3358
+ try {
3359
+ yield storage.setEncrypted('dl_auto_identified_email', existingEmail);
3360
+ this.log('Migrated legacy plaintext auto-identified email to encrypted storage');
3361
+ }
3362
+ catch (error) {
3363
+ this.log('Failed to migrate legacy auto-identified email:', error);
3364
+ }
3365
+ }
3366
+ this.log('User already auto-identified');
3367
+ return;
3368
+ }
3369
+ // Setup monitoring
3370
+ if (this.config.captureFromForms) {
3371
+ this.setupFormMonitoring();
3372
+ }
3373
+ if (this.config.captureFromAPI) {
3374
+ this.setupFetchInterception();
3375
+ this.setupXHRInterception();
3376
+ }
3377
+ if (this.config.captureFromShopify) {
3378
+ this.setupShopifyMonitoring();
3379
+ }
3380
+ this.log('Auto-identify initialized');
3381
+ });
3133
3382
  }
3134
3383
  /**
3135
3384
  * Setup form monitoring for email capture
@@ -3285,10 +3534,21 @@ class AutoIdentifyManager {
3285
3534
  this.log('Shopify detected, setting up monitoring');
3286
3535
  // Try to fetch customer data immediately
3287
3536
  this.checkShopifyCustomer();
3288
- // Check periodically (in case customer logs in later)
3537
+ // Check periodically (in case the customer logs in later), but CAP the attempts so a
3538
+ // visitor who never logs in — the vast majority of storefront traffic — doesn't poll
3539
+ // /account.json forever (it used to run every 10s for the whole session). A logged-in
3540
+ // customer surfaces well within ~2 minutes. (WEB-10)
3541
+ let checks = 0;
3542
+ const MAX_CHECKS = 12; // ~2 minutes at 10s
3289
3543
  this.shopifyCheckInterval = setInterval(() => {
3544
+ checks++;
3290
3545
  this.checkShopifyCustomer();
3291
- }, 10000); // Check every 10 seconds
3546
+ if (checks >= MAX_CHECKS && this.shopifyCheckInterval) {
3547
+ clearInterval(this.shopifyCheckInterval);
3548
+ this.shopifyCheckInterval = undefined;
3549
+ this.log('Shopify monitoring stopped after max checks (no login detected)');
3550
+ }
3551
+ }, 10000);
3292
3552
  this.log('Shopify monitoring active');
3293
3553
  }
3294
3554
  /**
@@ -3445,31 +3705,51 @@ class AutoIdentifyManager {
3445
3705
  * Trigger identify with rate limiting
3446
3706
  */
3447
3707
  triggerIdentify(email, source) {
3448
- // Rate limiting
3449
- const now = Date.now();
3450
- if (now - this.lastIdentifyTime < this.RATE_LIMIT_MS) {
3451
- this.log('Rate limited, skipping identify');
3452
- return;
3453
- }
3454
- // Check if already identified
3455
- const existingEmail = storage.get('dl_auto_identified_email');
3456
- if (existingEmail === email) {
3457
- this.log('Already identified with this email');
3458
- return;
3459
- }
3460
- // Store email to prevent duplicate identification
3461
- storage.set('dl_auto_identified_email', email);
3462
- this.lastIdentifyTime = now;
3463
- // Trigger callback
3464
- if (this.identifyCallback) {
3465
- this.log(`Auto-identifying user: ${email} (source: ${source})`);
3466
- this.identifyCallback(email, source);
3467
- }
3708
+ return __awaiter(this, void 0, void 0, function* () {
3709
+ if (this.destroyed)
3710
+ return;
3711
+ // Rate limiting
3712
+ const now = Date.now();
3713
+ if (now - this.lastIdentifyTime < this.RATE_LIMIT_MS) {
3714
+ this.log('Rate limited, skipping identify');
3715
+ return;
3716
+ }
3717
+ // Stamp the rate-limit timer synchronously, BEFORE the async storage calls below,
3718
+ // so two near-simultaneous triggers can't both slip past into a double-identify
3719
+ // (the storage read/write is now async — a window the old sync code didn't have).
3720
+ this.lastIdentifyTime = now;
3721
+ // Check if already identified.
3722
+ // WEB-5: encrypted store (the email is PII at rest).
3723
+ const existingEmail = yield storage.getEncrypted('dl_auto_identified_email');
3724
+ if (existingEmail === email) {
3725
+ this.log('Already identified with this email');
3726
+ return;
3727
+ }
3728
+ // If we were destroyed (e.g. user opted out) during the async read above, do NOT
3729
+ // re-persist the email or fire the callback.
3730
+ if (this.destroyed)
3731
+ return;
3732
+ // Store email (encrypted) to prevent duplicate identification. Best-effort: a
3733
+ // storage/encryption failure must not block the identify, since the identify
3734
+ // event carries the email to the backend regardless.
3735
+ try {
3736
+ yield storage.setEncrypted('dl_auto_identified_email', email);
3737
+ }
3738
+ catch (error) {
3739
+ this.log('Failed to persist auto-identified email:', error);
3740
+ }
3741
+ // Trigger callback
3742
+ if (this.identifyCallback) {
3743
+ this.log(`Auto-identifying user: ${email} (source: ${source})`);
3744
+ this.identifyCallback(email, source);
3745
+ }
3746
+ });
3468
3747
  }
3469
3748
  /**
3470
3749
  * Destroy and cleanup
3471
3750
  */
3472
3751
  destroy() {
3752
+ this.destroyed = true;
3473
3753
  // Restore original fetch
3474
3754
  if (this.originalFetch) {
3475
3755
  window.fetch = this.originalFetch;
@@ -3560,9 +3840,12 @@ class Datalyr {
3560
3840
  this.superProperties = {};
3561
3841
  this.userProperties = {};
3562
3842
  this.optedOut = false;
3843
+ // Consent preferences (setConsent). null = not set → no consent-based restriction.
3844
+ this.consent = null;
3563
3845
  this.initialized = false;
3564
3846
  this.errors = [];
3565
3847
  this.MAX_ERRORS = 50;
3848
+ this.lastSpaPath = null; // dedups SPA pageviews (replaceState-on-mount double-fire)
3566
3849
  // FIXED (ISSUE-01): Async initialization promise to prevent race conditions
3567
3850
  this.initializationPromise = null;
3568
3851
  // Opt-out check moved to init() after cookies configured (Issue #14)
@@ -3604,6 +3887,9 @@ class Datalyr {
3604
3887
  storage.migrateFromLegacyPrefix();
3605
3888
  // Check opt-out AFTER cookies configured (Issue #14)
3606
3889
  this.optedOut = this.cookies.get('__dl_opt_out') === 'true';
3890
+ // Load persisted consent so shouldTrack()/container gating honor it from the
3891
+ // first event (setConsent persists it; see optOut for the enforcement on opt-out).
3892
+ this.consent = storage.get('dl_consent', null);
3607
3893
  // CC funnel page entry: restore the _dl_* URL bridge BEFORE IdentityManager
3608
3894
  // initializes so the storefront's visitor_id is the one used here (instead
3609
3895
  // of auto-generating a fresh one on this domain).
@@ -3625,6 +3911,9 @@ class Datalyr {
3625
3911
  // Set session ID in identity manager
3626
3912
  const sessionId = this.session.getSessionId();
3627
3913
  this.identity.setSessionId(sessionId);
3914
+ // Gate the queue by the FULL tracking policy (opt-out + analytics consent + DNT +
3915
+ // GPC) so a returning opted-out / DNT / GPC visitor's persisted events don't drain.
3916
+ this.queue.setEnabled(this.shouldTrack());
3628
3917
  // FIXED (ISSUE-01): Start async initialization immediately but don't block constructor
3629
3918
  // This allows encryption to initialize before any events are tracked
3630
3919
  this.initializeAsync();
@@ -3661,18 +3950,33 @@ class Datalyr {
3661
3950
  this.initializationPromise = (() => __awaiter(this, void 0, void 0, function* () {
3662
3951
  var _a;
3663
3952
  try {
3664
- // SEC-03 Fix: Initialize encryption for PII data
3665
- const deviceId = this.identity.getAnonymousId();
3666
- yield dataEncryption.initialize(this.config.workspaceId, deviceId);
3667
- // Load encrypted user properties
3668
- this.userProperties = yield storage.getEncrypted('dl_user_traits', {});
3669
- this.log('Encryption initialized, user properties loaded');
3953
+ // SEC-03: encryption is for PII-AT-REST only — it must NOT gate event delivery,
3954
+ // pageviews, or pixels. On a non-secure context (http://) or an old browser,
3955
+ // crypto.subtle is absent and initialize() throws; isolate it so the rest of init
3956
+ // (SPA tracking, container/pixels, initial pageview) still runs. (http:// fix)
3957
+ try {
3958
+ const deviceId = this.identity.getAnonymousId();
3959
+ yield dataEncryption.initialize(this.config.workspaceId, deviceId);
3960
+ this.userProperties = yield storage.getEncrypted('dl_user_traits', {});
3961
+ this.log('Encryption initialized, user properties loaded');
3962
+ }
3963
+ catch (encErr) {
3964
+ console.warn('[Datalyr] Encryption unavailable (non-secure context?); continuing WITHOUT PII-at-rest encryption:', encErr);
3965
+ this.userProperties = storage.get('dl_user_traits', {});
3966
+ }
3670
3967
  // Setup SPA tracking if enabled
3671
3968
  if (this.config.trackSPA) {
3672
3969
  this.setupSPATracking();
3673
3970
  }
3674
- // Initialize container manager if enabled
3675
- if (this.config.enableContainer !== false) {
3971
+ // Initialize container manager if enabled.
3972
+ // WEB-4 (privacy gate): the container loads third-party pixels (Meta/Google/
3973
+ // TikTok) and calls fbq('init', …, advancedMatching) with the visitor's
3974
+ // SHA-256 email/id — so it must NOT initialize for opted-out / DNT / GPC
3975
+ // visitors, nor when privacyMode is explicitly 'strict'. (Remote config can't
3976
+ // gate this: the container fetch is what delivers the remote config, so only
3977
+ // local consent signals + an explicit strict init() are knowable here.)
3978
+ const privacyStrict = this.config.privacyMode === 'strict';
3979
+ if (this.config.enableContainer !== false && this.shouldTrack() && !privacyStrict && this.consentAllowsMarketing()) {
3676
3980
  this.container = new ContainerManager({
3677
3981
  workspaceId: this.config.workspaceId,
3678
3982
  endpoint: this.config.endpoint,
@@ -3762,7 +4066,9 @@ class Datalyr {
3762
4066
  // Storefront → CC bridge: stamp _dl_* params on outbound links to the
3763
4067
  // configured CC domains so visitor_id + click signals cross the domain
3764
4068
  // boundary. Inert unless checkoutChampDomains is set.
3765
- if (Array.isArray(this.config.checkoutChampDomains) && this.config.checkoutChampDomains.length > 0) {
4069
+ if (Array.isArray(this.config.checkoutChampDomains) && this.config.checkoutChampDomains.length > 0 && this.shouldTrack()) {
4070
+ // MED-4: gated on shouldTrack() (like syncShopifyCartAttributes) so an
4071
+ // opted-out / DNT / GPC visitor's id + click-ids aren't stamped on outbound links.
3766
4072
  this.syncOutboundLinkParams(this.config.checkoutChampDomains);
3767
4073
  }
3768
4074
  // Track initial page view if enabled (AFTER encryption ready)
@@ -3847,51 +4153,56 @@ class Datalyr {
3847
4153
  * so the mobile SDK can retrieve them deterministically after install.
3848
4154
  */
3849
4155
  trackAppDownloadClick(options) {
3850
- if (!this.initialized) {
3851
- console.warn('[Datalyr] SDK not initialized. Call init() first.');
3852
- return;
3853
- }
3854
- if (!this.shouldTrack())
3855
- return;
3856
- // Fire the event with target platform info — attribution data is
3857
- // automatically merged by createEventPayload via getAttributionData()
3858
- this.track('$app_download_click', {
3859
- target_platform: options.targetPlatform,
3860
- app_store_url: options.appStoreUrl,
3861
- });
3862
- // Flush immediately via sendBeacon before page navigates away
3863
- this.queue.forceFlush();
3864
- // For Android: append referrer param to Play Store URL with click attribution
3865
- if (options.targetPlatform === 'android' && options.appStoreUrl.includes('play.google.com')) {
3866
- const lastTouch = this.attribution.getLastTouch();
3867
- const referrerParams = new URLSearchParams();
3868
- if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.clickId)
3869
- referrerParams.set('dl_click_id', lastTouch.clickId);
3870
- if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.clickIdType)
3871
- referrerParams.set('dl_click_id_type', lastTouch.clickIdType);
3872
- if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.source)
3873
- referrerParams.set('utm_source', lastTouch.source);
3874
- if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.medium)
3875
- referrerParams.set('utm_medium', lastTouch.medium);
3876
- if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.campaign)
3877
- referrerParams.set('utm_campaign', lastTouch.campaign);
3878
- if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.content)
3879
- referrerParams.set('utm_content', lastTouch.content);
3880
- if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.term)
3881
- referrerParams.set('utm_term', lastTouch.term);
3882
- try {
3883
- const url = new URL(options.appStoreUrl);
3884
- url.searchParams.set('referrer', referrerParams.toString());
3885
- window.location.href = url.toString();
4156
+ return __awaiter(this, void 0, void 0, function* () {
4157
+ if (!this.initialized) {
4158
+ console.warn('[Datalyr] SDK not initialized. Call init() first.');
4159
+ return;
3886
4160
  }
3887
- catch (_a) {
3888
- // If URL parsing fails, redirect without referrer
4161
+ if (!this.shouldTrack())
4162
+ return;
4163
+ // Fire the event with target platform info — attribution data is
4164
+ // automatically merged by createEventPayload via getAttributionData()
4165
+ this.track('$app_download_click', {
4166
+ target_platform: options.targetPlatform,
4167
+ app_store_url: options.appStoreUrl,
4168
+ });
4169
+ // AWAIT the flush before navigating away (M5). sendBeacon dispatches synchronously,
4170
+ // but on browsers WITHOUT sendBeacon forceFlush falls back to a keepalive fetch —
4171
+ // and the synchronous window.location assignment below would tear the page down
4172
+ // before that fetch dispatched, losing the click event.
4173
+ yield this.queue.forceFlush();
4174
+ // For Android: append referrer param to Play Store URL with click attribution
4175
+ if (options.targetPlatform === 'android' && options.appStoreUrl.includes('play.google.com')) {
4176
+ const lastTouch = this.attribution.getLastTouch();
4177
+ const referrerParams = new URLSearchParams();
4178
+ if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.clickId)
4179
+ referrerParams.set('dl_click_id', lastTouch.clickId);
4180
+ if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.clickIdType)
4181
+ referrerParams.set('dl_click_id_type', lastTouch.clickIdType);
4182
+ if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.source)
4183
+ referrerParams.set('utm_source', lastTouch.source);
4184
+ if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.medium)
4185
+ referrerParams.set('utm_medium', lastTouch.medium);
4186
+ if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.campaign)
4187
+ referrerParams.set('utm_campaign', lastTouch.campaign);
4188
+ if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.content)
4189
+ referrerParams.set('utm_content', lastTouch.content);
4190
+ if (lastTouch === null || lastTouch === void 0 ? void 0 : lastTouch.term)
4191
+ referrerParams.set('utm_term', lastTouch.term);
4192
+ try {
4193
+ const url = new URL(options.appStoreUrl);
4194
+ url.searchParams.set('referrer', referrerParams.toString());
4195
+ window.location.href = url.toString();
4196
+ }
4197
+ catch (_a) {
4198
+ // If URL parsing fails, redirect without referrer
4199
+ window.location.href = options.appStoreUrl;
4200
+ }
4201
+ }
4202
+ else {
3889
4203
  window.location.href = options.appStoreUrl;
3890
4204
  }
3891
- }
3892
- else {
3893
- window.location.href = options.appStoreUrl;
3894
- }
4205
+ });
3895
4206
  }
3896
4207
  /**
3897
4208
  * Identify a user
@@ -3956,6 +4267,17 @@ class Datalyr {
3956
4267
  }
3957
4268
  if (!this.shouldTrack())
3958
4269
  return;
4270
+ // WEB-6: record one customer-journey touchpoint per session so touchpoint_count /
4271
+ // days_since_first_touch become real multi-touch signals (addTouchpoint had no
4272
+ // callers before, so the journey was always empty). Dedup against the PERSISTED
4273
+ // journey (not an in-memory field) so a hard page reload within the same session
4274
+ // doesn't append a duplicate touchpoint on a classic multi-page site.
4275
+ const sid = this.session.getSessionId();
4276
+ const journey = this.attribution.getJourney();
4277
+ const lastTouchpoint = journey.length ? journey[journey.length - 1] : null;
4278
+ if (!lastTouchpoint || lastTouchpoint.sessionId !== sid) {
4279
+ this.attribution.addTouchpoint(sid, this.attribution.captureAttribution());
4280
+ }
3959
4281
  const pageData = Object.assign({ title: document.title, url: window.location.href, path: window.location.pathname, search: window.location.search, referrer: document.referrer }, properties);
3960
4282
  // Add referrer data
3961
4283
  const referrerData = getReferrerData();
@@ -4004,6 +4326,8 @@ class Datalyr {
4004
4326
  console.warn('[Datalyr] SDK not initialized. Call init() first.');
4005
4327
  return;
4006
4328
  }
4329
+ if (!this.shouldTrack())
4330
+ return;
4007
4331
  this.track('$group', {
4008
4332
  group_id: groupId,
4009
4333
  traits
@@ -4017,6 +4341,13 @@ class Datalyr {
4017
4341
  console.warn('[Datalyr] SDK not initialized. Call init() first.');
4018
4342
  return;
4019
4343
  }
4344
+ if (!userId) {
4345
+ console.warn('[Datalyr] alias() requires a non-empty userId');
4346
+ return;
4347
+ }
4348
+ // Gate before mutating persisted identity (identity.alias writes dl_user_id).
4349
+ if (!this.shouldTrack())
4350
+ return;
4020
4351
  const aliasData = this.identity.alias(userId, previousId);
4021
4352
  this.track('$alias', aliasData);
4022
4353
  }
@@ -4030,7 +4361,17 @@ class Datalyr {
4030
4361
  }
4031
4362
  this.identity.reset();
4032
4363
  this.userProperties = {};
4364
+ // Clear super properties too — they'd otherwise keep attaching the previous user's
4365
+ // values to the next user's events (cross-user contamination on shared devices).
4366
+ this.superProperties = {};
4033
4367
  storage.remove('dl_user_traits');
4368
+ // Clear the auto-identify guard so a different user on the same browser is
4369
+ // re-captured (it short-circuits while dl_auto_identified_email is present), and so
4370
+ // the prior user's email isn't left at rest after logout.
4371
+ storage.remove('dl_auto_identified_email');
4372
+ // Clear the journey too, or the next user's touchpoints append to the previous
4373
+ // user's (cross-user contamination of touchpoint_count / days_since_first_touch).
4374
+ storage.remove('dl_journey');
4034
4375
  this.session.createNewSession();
4035
4376
  this.log('User reset');
4036
4377
  }
@@ -4141,19 +4482,44 @@ class Datalyr {
4141
4482
  setAttribution(attribution) {
4142
4483
  const current = this.attribution.captureAttribution();
4143
4484
  const merged = Object.assign(Object.assign({}, current), attribution);
4485
+ // M6: actually make this affect events. Previously it only wrote a session key that
4486
+ // NOTHING in the event path reads, so setAttribution() was a silent no-op. Route it
4487
+ // through the AttributionManager so last_touch_* reflects it (and first_touch_* when
4488
+ // none is set yet — storeFirstTouch is immutable-unless-expired, so it won't clobber
4489
+ // an existing first touch).
4490
+ this.attribution.storeLastTouch(merged);
4491
+ this.attribution.storeFirstTouch(merged);
4144
4492
  this.session.storeAttribution(merged);
4145
4493
  }
4146
4494
  /**
4147
4495
  * Opt out of tracking
4148
4496
  */
4149
4497
  optOut() {
4498
+ var _a;
4150
4499
  if (!this.initialized) {
4151
4500
  console.warn('[Datalyr] SDK not initialized. Call init() first.');
4152
4501
  return;
4153
4502
  }
4154
4503
  this.optedOut = true;
4155
4504
  this.cookies.set('__dl_opt_out', 'true', this.config.cookieExpires);
4505
+ // Stop the queue from sending OR draining anything persisted before opt-out, and
4506
+ // purge what's already buffered (the periodic/on-load drain has no other gate).
4507
+ this.queue.setEnabled(false);
4156
4508
  this.queue.clear();
4509
+ this.queue.clearOffline();
4510
+ // Tear down auto-identify so it stops capturing email into storage post-opt-out.
4511
+ (_a = this.autoIdentify) === null || _a === void 0 ? void 0 : _a.destroy();
4512
+ this.autoIdentify = undefined;
4513
+ // Stop forwarding to (and drop) third-party pixels for this visitor.
4514
+ if (this.container) {
4515
+ this.container.cleanupAllIframes();
4516
+ this.container = undefined;
4517
+ }
4518
+ // Purge PII at rest.
4519
+ this.userProperties = {};
4520
+ storage.remove('dl_user_traits');
4521
+ storage.remove('dl_auto_identified_email');
4522
+ storage.remove('dl_journey');
4157
4523
  this.log('User opted out');
4158
4524
  }
4159
4525
  /**
@@ -4166,6 +4532,10 @@ class Datalyr {
4166
4532
  }
4167
4533
  this.optedOut = false;
4168
4534
  this.cookies.set('__dl_opt_out', 'false', this.config.cookieExpires);
4535
+ // Re-enable only if the full policy now allows (analytics consent + DNT/GPC), not
4536
+ // merely because opt-out was lifted — otherwise a GPC/DNT visitor's persisted
4537
+ // events would start draining again. (Pixels / auto-identify resume on next load.)
4538
+ this.queue.setEnabled(this.shouldTrack());
4169
4539
  this.log('User opted in');
4170
4540
  }
4171
4541
  /**
@@ -4178,7 +4548,26 @@ class Datalyr {
4178
4548
  * Set consent preferences
4179
4549
  */
4180
4550
  setConsent(consent) {
4551
+ this.consent = consent;
4181
4552
  storage.set('dl_consent', consent);
4553
+ // Enforce it live (not just persist it). Gate the queue by the full policy
4554
+ // (analytics consent + opt-out + DNT/GPC), and on withdrawal purge buffered events
4555
+ // too — mirroring optOut — so events captured before withdrawal can't drain if
4556
+ // consent is later re-granted.
4557
+ const allowed = this.shouldTrack();
4558
+ this.queue.setEnabled(allowed);
4559
+ if (!allowed) {
4560
+ this.queue.clear();
4561
+ this.queue.clearOffline();
4562
+ }
4563
+ // Marketing / "do not sell" withdrawal: stop FEEDING the third-party pixels and
4564
+ // prevent them from being initialized on the next page load. NOTE: an
4565
+ // already-injected pixel global (fbq/gtag/ttq) keeps running in the page — we
4566
+ // can't fully unload a third-party script mid-session; full removal is on reload.
4567
+ if (!this.consentAllowsMarketing() && this.container) {
4568
+ this.container.cleanupAllIframes();
4569
+ this.container = undefined;
4570
+ }
4182
4571
  this.log('Consent updated:', consent);
4183
4572
  }
4184
4573
  /**
@@ -4544,18 +4933,21 @@ class Datalyr {
4544
4933
  };
4545
4934
  const observer = new MutationObserver(scheduleRestamp);
4546
4935
  observer.observe(document.documentElement, { childList: true, subtree: true });
4547
- // Observer + click listener live for the session; pagehide cleans up on
4548
- // full-page unload. SPA route changes are fine we WANT stamping to keep
4549
- // working across virtual navigations.
4550
- window.addEventListener("pagehide", () => {
4936
+ // Observer + click listener live for the session; pagehide cleans up on full-page
4937
+ // unload, and destroy() can tear them down early via this disposer (H2 — otherwise
4938
+ // a destroy()+re-init() leaks the observer + capturing click listener).
4939
+ this.outboundDisposer = () => {
4551
4940
  try {
4552
4941
  observer.disconnect();
4553
4942
  }
4554
4943
  catch ( /* idempotent */_a) { /* idempotent */ }
4555
- if (restampTimer != null)
4944
+ if (restampTimer != null) {
4556
4945
  clearTimeout(restampTimer);
4946
+ restampTimer = null;
4947
+ }
4557
4948
  document.removeEventListener("click", onClick, true);
4558
- }, { once: true });
4949
+ };
4950
+ window.addEventListener("pagehide", () => { var _a; return (_a = this.outboundDisposer) === null || _a === void 0 ? void 0 : _a.call(this); }, { once: true });
4559
4951
  }
4560
4952
  catch (error) {
4561
4953
  this.log("MutationObserver setup failed (CC link sync):", error);
@@ -4566,6 +4958,12 @@ class Datalyr {
4566
4958
  * Create event payload
4567
4959
  */
4568
4960
  createEventPayload(eventName, properties, eventIdArg) {
4961
+ // NEW-2: keep the identity's cached session id in lockstep with the LIVE session.
4962
+ // The session id changes on identify() (rotateSessionId) and on session timeout, but
4963
+ // identity only synced it at init/start — so the top-level payload.session_id (from
4964
+ // identity) disagreed with event_data.session_id (from session.getMetrics()). Sync
4965
+ // here, before reading either, so every event carries a single consistent session id.
4966
+ this.identity.setSessionId(this.session.getSessionId());
4569
4967
  // Sanitize and merge properties
4570
4968
  const sanitizedProperties = sanitizeEventData(properties);
4571
4969
  const eventData = deepMerge({}, this.superProperties, sanitizedProperties);
@@ -4622,7 +5020,7 @@ class Datalyr {
4622
5020
  resolution_method: 'browser_sdk',
4623
5021
  resolution_confidence: 1.0,
4624
5022
  // SDK metadata (keep in sync with package.json version)
4625
- sdk_version: '1.6.5',
5023
+ sdk_version: '1.7.1',
4626
5024
  sdk_name: 'datalyr-web-sdk'
4627
5025
  };
4628
5026
  return payload;
@@ -4635,6 +5033,10 @@ class Datalyr {
4635
5033
  if (this.optedOut) {
4636
5034
  return false;
4637
5035
  }
5036
+ // Explicit analytics-consent withdrawal (setConsent) blocks first-party tracking.
5037
+ if (this.consent && this.consent.analytics === false) {
5038
+ return false;
5039
+ }
4638
5040
  // Check Do Not Track
4639
5041
  if (this.config.respectDoNotTrack && isDoNotTrackEnabled()) {
4640
5042
  return false;
@@ -4645,6 +5047,14 @@ class Datalyr {
4645
5047
  }
4646
5048
  return true;
4647
5049
  }
5050
+ /**
5051
+ * Whether marketing/third-party pixels are allowed. Withdrawing `marketing` or `sale`
5052
+ * (CCPA "do not sell") consent via setConsent() blocks loading the Meta/Google/TikTok
5053
+ * pixels (which share data). No consent set = allowed (default).
5054
+ */
5055
+ consentAllowsMarketing() {
5056
+ return !this.consent || (this.consent.marketing !== false && this.consent.sale !== false);
5057
+ }
4648
5058
  /**
4649
5059
  * Setup SPA tracking
4650
5060
  * Fixed Issue #15: Store original methods for cleanup
@@ -4655,56 +5065,55 @@ class Datalyr {
4655
5065
  this.originalPushState = history.pushState;
4656
5066
  this.originalReplaceState = history.replaceState;
4657
5067
  const self = this;
5068
+ // Seed with the current URL so a router's replaceState-on-mount (same URL) doesn't
5069
+ // fire a duplicate pageview on top of the initial page() call. (M2/M3)
5070
+ this.lastSpaPath = window.location.pathname + window.location.search + window.location.hash;
4658
5071
  // Override pushState
4659
5072
  history.pushState = function (...args) {
4660
5073
  self.originalPushState.apply(history, args);
4661
- setTimeout(() => {
4662
- // Clear attribution cache to capture fresh URL params
4663
- self.attribution.clearCache();
4664
- self.page();
4665
- }, 0);
5074
+ setTimeout(() => self.handleSpaNavigation(), 0);
4666
5075
  };
4667
5076
  // Override replaceState
4668
5077
  history.replaceState = function (...args) {
4669
5078
  self.originalReplaceState.apply(history, args);
4670
- setTimeout(() => {
4671
- // Clear attribution cache to capture fresh URL params
4672
- self.attribution.clearCache();
4673
- self.page();
4674
- }, 0);
5079
+ setTimeout(() => self.handleSpaNavigation(), 0);
4675
5080
  };
4676
5081
  // Listen for popstate
4677
- this.popstateHandler = () => {
4678
- setTimeout(() => {
4679
- // Clear attribution cache to capture fresh URL params
4680
- self.attribution.clearCache();
4681
- self.page();
4682
- }, 0);
4683
- };
5082
+ this.popstateHandler = () => { setTimeout(() => self.handleSpaNavigation(), 0); };
4684
5083
  window.addEventListener('popstate', this.popstateHandler);
4685
5084
  // Listen for hashchange
4686
- this.hashchangeHandler = () => {
4687
- // Clear attribution cache to capture fresh URL params
4688
- self.attribution.clearCache();
4689
- self.page();
4690
- };
5085
+ this.hashchangeHandler = () => { self.handleSpaNavigation(); };
4691
5086
  window.addEventListener('hashchange', this.hashchangeHandler);
4692
5087
  }
5088
+ /**
5089
+ * Handle an SPA virtual navigation. Dedups consecutive same-URL fires (M2/M3): many
5090
+ * routers call history.replaceState on mount/hydration, which previously fired a
5091
+ * SECOND `pageview` on top of the initial `page()`. Only fires when the full URL
5092
+ * (path+search+hash) actually changed.
5093
+ */
5094
+ handleSpaNavigation() {
5095
+ const path = window.location.pathname + window.location.search + window.location.hash;
5096
+ if (path === this.lastSpaPath)
5097
+ return;
5098
+ this.lastSpaPath = path;
5099
+ this.attribution.clearCache();
5100
+ this.page();
5101
+ }
4693
5102
  /**
4694
5103
  * Setup page unload handler
4695
5104
  */
4696
5105
  setupUnloadHandler() {
4697
- // Use both events for maximum compatibility
4698
- const handleUnload = () => {
4699
- this.queue.forceFlush();
5106
+ // Store refs so destroy() can remove these — otherwise a destroy()+re-init() cycle
5107
+ // leaks listeners that keep firing forceFlush() on the OLD (destroyed) queue. (H2)
5108
+ this.unloadHandler = () => { this.queue.forceFlush(); };
5109
+ this.visibilityHandler = () => {
5110
+ if (document.visibilityState === 'hidden')
5111
+ this.queue.forceFlush();
4700
5112
  };
4701
- window.addEventListener('beforeunload', handleUnload);
4702
- window.addEventListener('pagehide', handleUnload);
4703
- window.addEventListener('visibilitychange', () => {
4704
- if (document.visibilityState === 'hidden') {
4705
- handleUnload();
4706
- }
4707
- });
5113
+ // Use multiple events for maximum compatibility.
5114
+ window.addEventListener('beforeunload', this.unloadHandler);
5115
+ window.addEventListener('pagehide', this.unloadHandler);
5116
+ window.addEventListener('visibilitychange', this.visibilityHandler);
4708
5117
  }
4709
5118
  /**
4710
5119
  * Get performance metrics
@@ -4809,6 +5218,22 @@ class Datalyr {
4809
5218
  if (this.hashchangeHandler) {
4810
5219
  window.removeEventListener('hashchange', this.hashchangeHandler);
4811
5220
  }
5221
+ // H2: also remove the unload/visibility listeners and tear down the CC outbound-link
5222
+ // observer/listener — these were leaking across destroy()+re-init(), keeping the OLD
5223
+ // queue alive and firing on every navigation.
5224
+ if (this.unloadHandler) {
5225
+ window.removeEventListener('beforeunload', this.unloadHandler);
5226
+ window.removeEventListener('pagehide', this.unloadHandler);
5227
+ this.unloadHandler = undefined;
5228
+ }
5229
+ if (this.visibilityHandler) {
5230
+ window.removeEventListener('visibilitychange', this.visibilityHandler);
5231
+ this.visibilityHandler = undefined;
5232
+ }
5233
+ if (this.outboundDisposer) {
5234
+ this.outboundDisposer();
5235
+ this.outboundDisposer = undefined;
5236
+ }
4812
5237
  // Clean up queue
4813
5238
  if (this.queue) {
4814
5239
  this.queue.destroy();
@@ -4827,6 +5252,13 @@ class Datalyr {
4827
5252
  }
4828
5253
  // SEC-03 Fix: Clean up encryption keys
4829
5254
  dataEncryption.destroy();
5255
+ // H3: reset init state so a subsequent init() fully re-runs. Without nulling the
5256
+ // initializationPromise, initializeAsync() early-returns the stale (resolved)
5257
+ // promise and the SDK comes back half-initialized (no container/pixels/SPA/pageview).
5258
+ this.initializationPromise = null;
5259
+ this.container = undefined;
5260
+ this.autoIdentify = undefined;
5261
+ this.lastSpaPath = null;
4830
5262
  // Clear any remaining data
4831
5263
  this.superProperties = {};
4832
5264
  this.userProperties = {};