@datalyr/web 1.7.6 → 1.7.8

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.
Files changed (42) hide show
  1. package/README.md +542 -476
  2. package/dist/attribution-lyr.test.d.ts +2 -0
  3. package/dist/attribution-lyr.test.d.ts.map +1 -0
  4. package/dist/attribution-oppref.test.d.ts +2 -0
  5. package/dist/attribution-oppref.test.d.ts.map +1 -0
  6. package/dist/attribution.d.ts.map +1 -1
  7. package/dist/config.d.ts +1 -0
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/datalyr.cjs.js +751 -46
  10. package/dist/datalyr.cjs.js.map +1 -1
  11. package/dist/datalyr.esm.js +751 -47
  12. package/dist/datalyr.esm.js.map +1 -1
  13. package/dist/datalyr.esm.min.js +1 -1
  14. package/dist/datalyr.esm.min.js.map +1 -1
  15. package/dist/datalyr.js +751 -46
  16. package/dist/datalyr.js.map +1 -1
  17. package/dist/datalyr.min.js +1 -1
  18. package/dist/datalyr.min.js.map +1 -1
  19. package/dist/identify-dedupe.test.d.ts +2 -0
  20. package/dist/identify-dedupe.test.d.ts.map +1 -0
  21. package/dist/identity-pii.test.d.ts +2 -0
  22. package/dist/identity-pii.test.d.ts.map +1 -0
  23. package/dist/identity.d.ts +46 -0
  24. package/dist/identity.d.ts.map +1 -1
  25. package/dist/index.d.ts +68 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.test.d.ts +3 -0
  28. package/dist/index.test.d.ts.map +1 -0
  29. package/dist/queue-403.test.d.ts +2 -0
  30. package/dist/queue-403.test.d.ts.map +1 -0
  31. package/dist/queue.d.ts +17 -0
  32. package/dist/queue.d.ts.map +1 -1
  33. package/dist/storage-migration.test.d.ts +2 -0
  34. package/dist/storage-migration.test.d.ts.map +1 -0
  35. package/dist/storage.d.ts.map +1 -1
  36. package/dist/stripe-session.d.ts +75 -0
  37. package/dist/stripe-session.d.ts.map +1 -0
  38. package/dist/stripe-session.test.d.ts +2 -0
  39. package/dist/stripe-session.test.d.ts.map +1 -0
  40. package/dist/types.d.ts +1 -0
  41. package/dist/types.d.ts.map +1 -1
  42. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @datalyr/web v1.7.6
2
+ * @datalyr/web v1.7.8
3
3
  * Datalyr Web SDK - Modern attribution tracking for web applications
4
4
  * (c) 2026 Datalyr Inc.
5
5
  * Released under the MIT License
@@ -419,8 +419,23 @@ class SafeStorage {
419
419
  // Get value from legacy key
420
420
  const value = this.storage.getItem(legacyKey);
421
421
  if (value) {
422
- // Extract the actual key name (remove '__dl_' prefix, keep 'dl_' part)
423
- const actualKey = legacyKey.slice('__dl_'.length); // e.g., '__dl_dl_anonymous_id' -> 'dl_anonymous_id'
422
+ // WEB-29: strip ONLY the leading '__'.
423
+ //
424
+ // This used to strip '__dl_', producing 'dl_anonymous_id' — but that
425
+ // is the LOGICAL key callers pass to get(), not the key it reads.
426
+ // get() prepends this.prefix ('dl_'), so the value actually lives at
427
+ // 'dl_dl_anonymous_id'. The migration therefore wrote to an address
428
+ // nothing reads AND then deleted the legacy key below, destroying
429
+ // the visitor's id instead of migrating it: a silent visitor reset
430
+ // and attribution loss for anyone still on the old prefix.
431
+ //
432
+ // legacy real key : __dl_dl_anonymous_id
433
+ // current real key: dl_dl_anonymous_id ← strip '__'
434
+ // logical key : dl_anonymous_id ← what get() is called with
435
+ //
436
+ // NOTE: the double 'dl_dl_' looks like a typo and is not. Renaming
437
+ // the prefix would orphan every stored id across the install base.
438
+ const actualKey = legacyKey.slice('__'.length); // '__dl_dl_anonymous_id' -> 'dl_dl_anonymous_id'
424
439
  // Only migrate if new key doesn't already exist (don't overwrite newer data)
425
440
  if (!this.storage.getItem(actualKey)) {
426
441
  this.storage.setItem(actualKey, value);
@@ -1093,6 +1108,9 @@ class IdentityManager {
1093
1108
  constructor(options = {}) {
1094
1109
  this.userId = null;
1095
1110
  this.sessionId = null;
1111
+ /** WEB-26: bumps whenever the persisted identity changes, so an in-flight
1112
+ * encrypted write can tell it has been superseded. */
1113
+ this.piiGeneration = 0;
1096
1114
  this.persistNewId = options.persistNewId !== false;
1097
1115
  this.anonymousId = this.getOrCreateAnonymousId();
1098
1116
  this.userId = this.getStoredUserId();
@@ -1219,6 +1237,126 @@ class IdentityManager {
1219
1237
  // corrupted by JSON.parse — both would fragment identity from the second page on.
1220
1238
  return storage.getString('dl_user_id');
1221
1239
  }
1240
+ /**
1241
+ * WEB-22 — is this user id personally identifying, and therefore not
1242
+ * something we may write to localStorage in the clear?
1243
+ *
1244
+ * The auto-identify path calls `identify(email, { email })`, so the raw
1245
+ * address became the `user_id` and was written unencrypted to `dl_user_id`.
1246
+ * Measured 2026-07-25: on the four workspaces using auto-identify, **every**
1247
+ * event carrying a `user_id` had an email in that column (20,502 / 20,502 on
1248
+ * `f6260736` over 7 days) — while the surrounding code went to real lengths to
1249
+ * encrypt the *same* address in `dl_auto_identified_email`.
1250
+ *
1251
+ * Deliberately narrow: an email is the case that actually occurs and the one
1252
+ * the SDK itself creates. Opaque application ids — the overwhelming majority —
1253
+ * keep the existing fast, synchronous, plaintext path with no behaviour change.
1254
+ */
1255
+ static looksLikePII(userId) {
1256
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userId);
1257
+ }
1258
+ /**
1259
+ * Persist the user id, encrypting it when it is PII.
1260
+ *
1261
+ * Three-way, and the ordering matters:
1262
+ * - not PII → plaintext `dl_user_id`, exactly as before (sync, always works)
1263
+ * - PII + crypto → encrypted `dl_user_id_pii`, and the plaintext key is REMOVED
1264
+ * - PII, no crypto → memory only, and both keys removed
1265
+ *
1266
+ * That last branch is the deliberate trade. `crypto.subtle` is absent on
1267
+ * http:// and old browsers, and index.ts is explicit that encryption is for
1268
+ * PII-at-rest only and "must NOT gate event delivery". So we never block an
1269
+ * event — `this.userId` is set in memory first and every event still carries
1270
+ * it — we only decline to *persist* an address we cannot protect. The cost is
1271
+ * that a returning visitor on an insecure origin is re-identified by the next
1272
+ * `identify()` call rather than restored from storage; the alternative is
1273
+ * writing their email to disk in the clear, which is what this fixes.
1274
+ */
1275
+ persistUserId(userId) {
1276
+ if (!IdentityManager.looksLikePII(userId)) {
1277
+ storage.set('dl_user_id', userId);
1278
+ // WEB-26: a previous PII user's encrypted id must not linger once an
1279
+ // opaque id takes over. Reachable when identify('opaque') runs before
1280
+ // hydrateEncryptedUserId() has populated this.userId, so index.ts sees no
1281
+ // current user and skips its account-switch reset().
1282
+ this.piiGeneration += 1;
1283
+ storage.remove('dl_user_id_pii');
1284
+ return;
1285
+ }
1286
+ // Never leave a plaintext copy behind — including one written by a previous
1287
+ // SDK version before this fix existed.
1288
+ storage.remove('dl_user_id');
1289
+ // WEB-26: the encrypted write is async, and reset()/optOut()/consent
1290
+ // withdrawal are not. Without a generation guard this sequence resurrects a
1291
+ // logged-out user's email: identify(email) → write pending →
1292
+ // remove('dl_user_id_pii') deletes NOTHING because the write has not landed
1293
+ // → the write lands → next page load hydrates the previous user's address
1294
+ // and every event ships user_id = their email. Stamp the write and discard
1295
+ // it if the identity moved on while it was in flight.
1296
+ const generation = ++this.piiGeneration;
1297
+ storage.setEncrypted('dl_user_id_pii', userId)
1298
+ .then(() => {
1299
+ if (generation !== this.piiGeneration)
1300
+ storage.remove('dl_user_id_pii');
1301
+ })
1302
+ .catch(() => {
1303
+ // No crypto.subtle (http://, legacy browser) or a storage failure. Drop
1304
+ // the at-rest copy rather than falling back to plaintext PII — but only
1305
+ // if this write is still the current one, or we would delete a newer
1306
+ // user's successfully-written value.
1307
+ if (generation === this.piiGeneration)
1308
+ storage.remove('dl_user_id_pii');
1309
+ });
1310
+ }
1311
+ /**
1312
+ * Restore a PII user id that was persisted encrypted. Async by necessity, so
1313
+ * it cannot run in the constructor; index.ts calls it during init, right after
1314
+ * `dataEncryption.initialize()`.
1315
+ *
1316
+ * Never overwrites an id already established this page load — an explicit
1317
+ * `identify()` that has already run is fresher than anything on disk.
1318
+ */
1319
+ hydrateEncryptedUserId() {
1320
+ return __awaiter(this, void 0, void 0, function* () {
1321
+ // WEB-26 (a) — migrate a plaintext address written by <= 1.7.7.
1322
+ //
1323
+ // persistUserId() only removes `dl_user_id` when identify() runs again, and
1324
+ // for the exact population this fix targets it never does:
1325
+ // AutoIdentifyManager.initialize() returns early while
1326
+ // `dl_auto_identified_email` exists (auto-identify.ts:88), so the callback
1327
+ // never fires. Without this the raw email would sit in localStorage forever
1328
+ // on every already-auto-identified browser.
1329
+ const legacy = storage.getString('dl_user_id');
1330
+ if (legacy && IdentityManager.looksLikePII(legacy)) {
1331
+ if (!this.userId)
1332
+ this.userId = legacy;
1333
+ this.persistUserId(legacy);
1334
+ return;
1335
+ }
1336
+ // WEB-26 (b) — recover a write that was dropped because encryption was not
1337
+ // keyed yet. index.ts sets `initialized = true` before initializeAsync()
1338
+ // finishes, so the documented `init(); identify(email)` pattern can reach
1339
+ // persistUserId() before dataEncryption has a key; that write rejects and
1340
+ // nothing is persisted. By here the key exists, so retry once.
1341
+ if (this.userId && IdentityManager.looksLikePII(this.userId)) {
1342
+ const alreadyStored = yield storage.getEncrypted('dl_user_id_pii', null);
1343
+ if (!alreadyStored)
1344
+ this.persistUserId(this.userId);
1345
+ return;
1346
+ }
1347
+ if (this.userId)
1348
+ return;
1349
+ try {
1350
+ const stored = yield storage.getEncrypted('dl_user_id_pii', null);
1351
+ if (typeof stored === 'string' && stored && !this.userId) {
1352
+ this.userId = stored;
1353
+ }
1354
+ }
1355
+ catch (_a) {
1356
+ // Undecryptable (rotated key, corrupt blob) — stay anonymous.
1357
+ }
1358
+ });
1359
+ }
1222
1360
  /**
1223
1361
  * Get the anonymous ID
1224
1362
  */
@@ -1267,8 +1405,9 @@ class IdentityManager {
1267
1405
  }
1268
1406
  const previousUserId = this.userId;
1269
1407
  this.userId = userId;
1270
- // Persist for future sessions
1271
- storage.set('dl_user_id', userId);
1408
+ // Persist for future sessions. WEB-22: encrypted when the id is PII (the
1409
+ // auto-identify path makes it the raw email); plaintext otherwise.
1410
+ this.persistUserId(userId);
1272
1411
  // Return identity link data (will be sent as $identify event)
1273
1412
  return {
1274
1413
  anonymous_id: this.anonymousId,
@@ -1291,7 +1430,7 @@ class IdentityManager {
1291
1430
  // Update current user ID if aliasing to current anonymous ID
1292
1431
  if (!previousId || previousId === this.anonymousId) {
1293
1432
  this.userId = userId;
1294
- storage.set('dl_user_id', userId);
1433
+ this.persistUserId(userId);
1295
1434
  }
1296
1435
  return aliasData;
1297
1436
  }
@@ -1301,7 +1440,12 @@ class IdentityManager {
1301
1440
  */
1302
1441
  reset() {
1303
1442
  this.userId = null;
1443
+ // WEB-26: invalidate any encrypted write still in flight.
1444
+ this.piiGeneration += 1;
1304
1445
  storage.remove('dl_user_id');
1446
+ // WEB-22: the encrypted PII copy must go too, or a logout would leave the
1447
+ // previous user's email at rest.
1448
+ storage.remove('dl_user_id_pii');
1305
1449
  storage.remove('dl_user_traits');
1306
1450
  // Generate new anonymous ID for privacy
1307
1451
  this.anonymousId = `anon_${generateUUID()}`;
@@ -1628,6 +1772,12 @@ class AttributionManager {
1628
1772
  'gbraid', // Google Ads (iOS)
1629
1773
  'wbraid', // Google Ads (web)
1630
1774
  'ttclid', // TikTok
1775
+ // WEB-28: OpenAI Ads. Captured by iOS and React Native since launch but
1776
+ // never by the web SDK, so every OpenAI Ads *web* conversion delivered with
1777
+ // attribution_type: none unless the customer passed the value by hand.
1778
+ // Placed after the Google block to match the mobile SDKs' ordering — the
1779
+ // first click id present wins, and this must not outrank fbclid/gclid.
1780
+ 'oppref', // OpenAI Ads
1631
1781
  'msclkid', // Microsoft/Bing
1632
1782
  'twclid', // Twitter/X
1633
1783
  'li_fat_id', // LinkedIn
@@ -1976,8 +2126,21 @@ class AttributionManager {
1976
2126
  // The old `hasCurrentAttribution` (truthy because source is always at least 'direct')
1977
2127
  // made the fallback below dead code AND caused storeLastTouch to overwrite a real
1978
2128
  // paid last-touch with 'direct'/'none' on the next internal navigation. (WEB NEW-1)
2129
+ // `lyr` counts as a real signal. It is the Datalyr tracking-link tag — the one
2130
+ // attribution parameter the product itself tells customers to put on a URL — and
2131
+ // omitting it meant a bare `?lyr=X` landing (no UTMs, no click id) scored FALSE:
2132
+ // the fallback below then replaced `current` wholesale with the stored touch,
2133
+ // discarding the tag that had just been parsed, and neither store* call ran, so it
2134
+ // never persisted either. Measured 2026-07-25 on the one workspace whose links are
2135
+ // bare: 96 landing URLs carried `lyr=`, 93 events kept it — 3 lost (3.1%), all of
2136
+ // them returning visitors (a first-time visitor has no stored touch to be replaced
2137
+ // by, which is the only reason the number is 3 and not 96). The edge worker's own
2138
+ // `buildDestination` emits exactly this URL shape when a link defines no UTMs.
2139
+ // iOS (AttributionManager.swift) and React Native persist `lyr` unconditionally;
2140
+ // this brings web into line.
1979
2141
  const hasRealAttribution = !!(current.clickId ||
1980
2142
  current.campaign ||
2143
+ current.lyr ||
1981
2144
  (current.source && current.source !== 'direct'));
1982
2145
  // Direct / internal navigation: fall back to persisted attribution so the event
1983
2146
  // isn't mis-attributed to 'direct'. FSR-48: prefer the LAST touch (the most recent
@@ -2177,15 +2340,20 @@ class AttributionManager {
2177
2340
  const DEFAULT_CRITICAL_EVENTS = ['purchase', 'signup', 'subscribe', 'lead', 'conversion'];
2178
2341
  // Default high priority events that use faster batching
2179
2342
  const DEFAULT_HIGH_PRIORITY_EVENTS = ['add_to_cart', 'begin_checkout', 'view_item', 'search'];
2180
- // A 429 is a deliberate backpressure signal, not a transient failure tagged so the
2181
- // send path can route it to the offline queue WITHOUT retrying (which would storm the
2182
- // already-overloaded server). See sendBatch / the rateLimitedUntil gate.
2343
+ // WEB-23: how long to stop sending after a 403 (origin not allowed). Long enough not to
2344
+ // hammer a rejecting origin, short enough that a server-side config fix is picked up
2345
+ // within the same visit. A 403 carries no Retry-After, so this is fixed.
2346
+ const ORIGIN_REJECTED_BACKOFF_MS = 5 * 60 * 1000;
2347
+ // Backpressure, not failure — routed to the offline queue WITHOUT retrying (which would
2348
+ // storm an already-overloaded server) and gated behind rateLimitedUntil. Raised for a 429
2349
+ // and, since WEB-23, for a 403: both mean "not now", not "never". See sendBatch.
2183
2350
  class RateLimitError extends Error {
2184
2351
  }
2185
- // A permanent (non-retryable) failure — a 4xx other than 408/429 (invalid event shape,
2186
- // origin not allowed, auth). Retrying or parking it just head-of-line-blocks the offline
2187
- // queue forever and hammers ingest. Tagged so the send paths DROP the batch instead of
2188
- // unshifting it back to the head. (FSR-55)
2352
+ // A permanent (non-retryable) failure — a 4xx other than 403/408/429, i.e. an invalid
2353
+ // event shape (400) or bad auth (401). Retrying or parking it just head-of-line-blocks
2354
+ // the offline queue forever and hammers ingest. Tagged so the send paths DROP the batch
2355
+ // instead of unshifting it back to the head. (FSR-55, narrowed by WEB-23 — a 403 is
2356
+ // server *configuration* state and does change, so it is no longer in this class.)
2189
2357
  class PermanentError extends Error {
2190
2358
  constructor(status, message) {
2191
2359
  super(message || `HTTP ${status}`);
@@ -2208,6 +2376,11 @@ class EventQueue {
2208
2376
  this.inFlight = []; // FIXED (WEB-3): batch currently in _flight's keepalive fetch — forceFlush must NOT re-beacon it
2209
2377
  this.enabled = true; // FIXED (consent): when false (opt-out / withdrawn analytics consent) all enqueue/flush/drain is a no-op
2210
2378
  this.rateLimitedUntil = 0; // FIXED (429): skip flush/drain until the server's Retry-After window passes
2379
+ // WEB-23: permanent drops used to be invisible — a debug-gated log line and
2380
+ // nothing else, so 11 days of 403s looked identical to a healthy queue. Counted
2381
+ // here and exposed via getStats() so a drop is at least observable.
2382
+ this.droppedEventCount = 0;
2383
+ this.lastDropStatus = null;
2211
2384
  // Coerce numeric config to sane values. The old `config.X || default` both turned a
2212
2385
  // legitimate 0 into the default AND let invalid values through — a NEGATIVE batchSize
2213
2386
  // made processOfflineQueue's `splice(0, -1)` loop forever and FREEZE the host tab.
@@ -2433,7 +2606,12 @@ class EventQueue {
2433
2606
  // FSR-55: don't park a permanently-rejected batch — it would never succeed and
2434
2607
  // would block the offline drain. Drop it.
2435
2608
  if (error instanceof PermanentError) {
2436
- this.log(`Dropping ${events.length} events — permanent error ${error.status}`);
2609
+ this.droppedEventCount += events.length;
2610
+ this.lastDropStatus = error.status;
2611
+ // console.warn, not this.log: a silent drop is the failure mode that let the
2612
+ // 2026-07-13 outage run for 11 days. This must be visible without debug mode.
2613
+ console.warn(`[Datalyr Queue] Dropped ${events.length} events — permanent error ${error.status}. ` +
2614
+ `${this.droppedEventCount} dropped this session.`);
2437
2615
  }
2438
2616
  else {
2439
2617
  this.moveToOfflineQueue(events);
@@ -2495,9 +2673,24 @@ class EventQueue {
2495
2673
  this.log(`Rate limited; backing off ${retryAfter}s`);
2496
2674
  throw new RateLimitError('Rate limited (429)');
2497
2675
  }
2498
- // FSR-55: a 4xx other than 408 (timeout) is PERMANENT invalid event shape
2499
- // (400), origin not allowed (403), auth (401). Retrying / parking it just blocks
2500
- // the queue and hammers ingest forever. Tag it so the caller drops the batch.
2676
+ // WEB-23: a 403 is NOT permanent it is server *configuration* state, and it
2677
+ // changes. On 2026-07-13 an allowed_origins regression made ingest reject three
2678
+ // workspaces with 403; the config was fixed 11 days later, but every event sent
2679
+ // in between had already been dropped on the floor by the FSR-55 rule below.
2680
+ // Eleven days of data, unrecoverable, with only a debug log to show for it.
2681
+ //
2682
+ // Treated like 429 instead: park the events offline behind a backoff window, so
2683
+ // we neither hammer a rejecting origin (FSR-55's real concern) nor discard data
2684
+ // that would have been accepted an hour later. The window is fixed because a 403
2685
+ // carries no Retry-After.
2686
+ if (response.status === 403) {
2687
+ this.rateLimitedUntil = Date.now() + ORIGIN_REJECTED_BACKOFF_MS;
2688
+ this.log(`Origin rejected (403); backing off ${ORIGIN_REJECTED_BACKOFF_MS / 1000}s and parking events`);
2689
+ throw new RateLimitError('Origin rejected (403)');
2690
+ }
2691
+ // FSR-55: a 4xx other than 403/408 (timeout) is PERMANENT — invalid event shape
2692
+ // (400) or auth (401). Retrying / parking it just blocks the queue and hammers
2693
+ // ingest forever. Tag it so the caller drops the batch.
2501
2694
  if (response.status >= 400 && response.status < 500 && response.status !== 408) {
2502
2695
  throw new PermanentError(response.status, `HTTP ${response.status}: ${response.statusText}`);
2503
2696
  }
@@ -2584,9 +2777,25 @@ class EventQueue {
2584
2777
  // purge. Gating here (a persistence sink, not just the send sinks) closes it.
2585
2778
  if (!this.enabled)
2586
2779
  return;
2587
- // FIXED (DATA-03): Check if offline queue operation already in progress
2780
+ // WEB-24. This early return used to `return` outright — losing the batch, because
2781
+ // _flush() has ALREADY spliced these events out of the live queue before calling
2782
+ // here, so they would exist in neither queue.
2783
+ //
2784
+ // Verified 2026-07-25 that the loss is NOT currently reachable: this method is the
2785
+ // only user of offlineQueueLock, its critical section is fully synchronous (push,
2786
+ // splice, then a synchronous saveOfflineQueue → storage.set), and JS is
2787
+ // single-threaded — so the flag can never be observed set on entry. The path is
2788
+ // dead code today, and the review's "drops the batch on lock contention" is REFUTED
2789
+ // as a live loss path.
2790
+ //
2791
+ // It is kept and made safe anyway, because it is one `await` away from being live:
2792
+ // the moment saveOfflineQueue becomes async (IndexedDB, encrypted-at-rest storage,
2793
+ // anything), contention becomes real and silent data loss returns instantly.
2794
+ // Enqueue first, then bail — the events are never dropped either way.
2588
2795
  if (this.offlineQueueLock) {
2589
- console.warn('[Datalyr Queue] Offline queue operation already in progress');
2796
+ console.warn('[Datalyr Queue] Offline queue busy; buffering events without persisting');
2797
+ if (events)
2798
+ this.offlineQueue.push(...events);
2590
2799
  return;
2591
2800
  }
2592
2801
  // Acquire lock
@@ -2605,6 +2814,10 @@ class EventQueue {
2605
2814
  if (this.offlineQueue.length > this.config.maxOfflineQueueSize) {
2606
2815
  const excess = this.offlineQueue.length - this.config.maxOfflineQueueSize;
2607
2816
  this.offlineQueue.splice(0, excess); // Remove oldest events
2817
+ // WEB-27: overflow is data loss too, and a sustained 403/park loop is
2818
+ // exactly what produces it. Count it rather than trimming silently.
2819
+ this.droppedEventCount += excess;
2820
+ console.warn(`[Datalyr Queue] Offline queue full — dropped ${excess} oldest event(s).`);
2608
2821
  }
2609
2822
  this.saveOfflineQueue();
2610
2823
  }
@@ -2713,7 +2926,15 @@ class EventQueue {
2713
2926
  // that would block every event behind it forever and hammer ingest every tick.
2714
2927
  // Drop it (already spliced off the front) and keep draining the rest.
2715
2928
  if (error instanceof PermanentError) {
2716
- this.log(`Dropping poison offline batch (${batch.length}) permanent error ${error.status}`);
2929
+ // WEB-27: count and surface these too. WEB-23's whole effect is to
2930
+ // PARK more batches offline, so the drain — not the live flush — is
2931
+ // where drops now predominantly happen. Counting only _flush left the
2932
+ // dominant loss path invisible, which is the exact failure mode the
2933
+ // counter was added to end.
2934
+ this.droppedEventCount += batch.length;
2935
+ this.lastDropStatus = error.status;
2936
+ console.warn(`[Datalyr Queue] Dropped ${batch.length} offline events — permanent error ${error.status}. ` +
2937
+ `${this.droppedEventCount} dropped this session.`);
2717
2938
  this.saveOfflineQueue();
2718
2939
  continue;
2719
2940
  }
@@ -2746,6 +2967,23 @@ class EventQueue {
2746
2967
  getOfflineQueueSize() {
2747
2968
  return this.offlineQueue.length;
2748
2969
  }
2970
+ /**
2971
+ * WEB-23: queue health, including events the SDK gave up on.
2972
+ *
2973
+ * `droppedEvents` is the number this session discarded as permanently rejected
2974
+ * (a 400/401). It exists because a silent drop is precisely the failure mode
2975
+ * that let the 2026-07-13 `allowed_origins` outage run for eleven days looking
2976
+ * exactly like a healthy queue. A non-zero value here means data was lost.
2977
+ */
2978
+ getStats() {
2979
+ return {
2980
+ queued: this.queue.length,
2981
+ offline: this.offlineQueue.length,
2982
+ droppedEvents: this.droppedEventCount,
2983
+ lastDropStatus: this.lastDropStatus,
2984
+ backoffUntil: this.rateLimitedUntil,
2985
+ };
2986
+ }
2749
2987
  /**
2750
2988
  * Get network status
2751
2989
  */
@@ -4374,6 +4612,256 @@ class AutoIdentifyManager {
4374
4612
  // someone else (and feeds that person's email to Meta advanced matching).
4375
4613
  AutoIdentifyManager.THIRD_PARTY_EMAIL_FIELD = /(recipient|friend|gift|refer|invite|colleague|coworker|share|to[-_]?email|email[-_]?to|second(ary)?[-_]?email)/i;
4376
4614
 
4615
+ /**
4616
+ * Stripe Checkout Session capture.
4617
+ *
4618
+ * WHY THIS EXISTS
4619
+ * syncStripePaymentLinks stamps `client_reference_id` onto buy.stripe.com
4620
+ * anchors, and deliberately never onto checkout.stripe.com — a Checkout Session
4621
+ * URL ignores the param because the session already exists server-side. That
4622
+ * leaves the single most common SaaS pattern uncovered: the merchant's backend
4623
+ * creates a Session and the browser is sent to checkout.stripe.com/c/pay/cs_...
4624
+ * The payment then reaches our webhook with no visitor at all.
4625
+ *
4626
+ * Measured 2026-07-25, 30d: of payers arriving via Stripe webhooks, 0.5% (one
4627
+ * tenant, 128/28,187) and 13.3% (another, 13/98) had ANY web pageview on the
4628
+ * same visitor. Not a misconfiguration — no tenant is wired, because being
4629
+ * wired currently requires the merchant to hand-write client_reference_id.
4630
+ *
4631
+ * WHAT THIS DOES
4632
+ * The session id must reach the browser for the redirect to happen at all, so
4633
+ * we observe it rather than trying to inject anything:
4634
+ * 1. fetch/XHR response bodies — `{url}` or `{sessionId}` from the
4635
+ * merchant's own create-session endpoint
4636
+ * 2. anchor clicks + window.open — direct links to checkout.stripe.com
4637
+ * A server-side 302 straight to Stripe never exposes the id to JS and is NOT
4638
+ * covered here; that case falls back to the email bridge.
4639
+ *
4640
+ * WHY THIS IS SAFE TO DEFAULT ON, WHEN autoIdentifyAPI IS NOT
4641
+ * autoIdentifyAPI scans the same traffic for EMAILS, which is why it defaults
4642
+ * off: an admin viewing a customer record gets identified as that customer, and
4643
+ * a wrong email propagates into Meta advanced matching. A `cs_live_...` token is
4644
+ * unambiguous, belongs to exactly one checkout, and is not PII. There is no
4645
+ * mis-identification failure mode to guard against — only the wrapper itself,
4646
+ * which is why every hook below is transparent and failure-isolated.
4647
+ */
4648
+ /** Stripe Checkout Session ids: cs_live_… / cs_test_… */
4649
+ const SESSION_ID_RE = /cs_(?:live|test)_[A-Za-z0-9]{8,}/;
4650
+ /** Hosts whose URLs carry a session id in the path. Exact match, never substring. */
4651
+ const CHECKOUT_HOSTS = new Set(['checkout.stripe.com']);
4652
+ /**
4653
+ * Response bodies are scanned in full, so cap what we're willing to read. A
4654
+ * create-session response is a few hundred bytes; anything large is not it, and
4655
+ * reading it would cost the merchant's page real memory and main-thread time.
4656
+ */
4657
+ const MAX_SCAN_BYTES = 65536;
4658
+ /** Bodies worth scanning. Stripe ids arrive as JSON or text, never as binary. */
4659
+ const SCANNABLE_TYPE_RE = /(json|text|javascript)/i;
4660
+ function extractSessionId(text) {
4661
+ if (!text)
4662
+ return null;
4663
+ const m = SESSION_ID_RE.exec(text);
4664
+ return m ? m[0] : null;
4665
+ }
4666
+ /**
4667
+ * True when `href` points at a Stripe-hosted checkout. Uses the URL API and
4668
+ * exact host equality — `a[href*="checkout.stripe.com"]` would match
4669
+ * `evil.com/checkout.stripe.com/x` and `checkout.stripe.com.evil.com`.
4670
+ */
4671
+ function isCheckoutUrl(href, base) {
4672
+ try {
4673
+ const host = new URL(href, base !== null && base !== void 0 ? base : (typeof window !== 'undefined' ? window.location.href : undefined)).hostname.toLowerCase();
4674
+ return CHECKOUT_HOSTS.has(host);
4675
+ }
4676
+ catch (_a) {
4677
+ return false;
4678
+ }
4679
+ }
4680
+ class StripeSessionWatcher {
4681
+ constructor(options = {}) {
4682
+ var _a, _b;
4683
+ this.seen = new Set();
4684
+ this.disposers = [];
4685
+ this.started = false;
4686
+ this.maxSessions = (_a = options.maxSessions) !== null && _a !== void 0 ? _a : 5;
4687
+ this.maxScanBytes = (_b = options.maxScanBytes) !== null && _b !== void 0 ? _b : MAX_SCAN_BYTES;
4688
+ }
4689
+ start(sink) {
4690
+ if (this.started || typeof window === 'undefined')
4691
+ return;
4692
+ this.started = true;
4693
+ this.sink = sink;
4694
+ this.hookFetch();
4695
+ this.hookXhr();
4696
+ this.hookClicks();
4697
+ this.hookWindowOpen();
4698
+ }
4699
+ stop() {
4700
+ // Restore in reverse so a later wrapper never re-installs an earlier one.
4701
+ for (const dispose of this.disposers.reverse()) {
4702
+ try {
4703
+ dispose();
4704
+ }
4705
+ catch (_a) {
4706
+ /* idempotent */
4707
+ }
4708
+ }
4709
+ this.disposers = [];
4710
+ this.started = false;
4711
+ this.sink = undefined;
4712
+ }
4713
+ /** Report a session id at most once, and never more than maxSessions per page. */
4714
+ emit(sessionId) {
4715
+ var _a;
4716
+ if (!sessionId || this.seen.has(sessionId))
4717
+ return;
4718
+ if (this.seen.size >= this.maxSessions)
4719
+ return;
4720
+ this.seen.add(sessionId);
4721
+ try {
4722
+ (_a = this.sink) === null || _a === void 0 ? void 0 : _a.call(this, sessionId);
4723
+ }
4724
+ catch (_b) {
4725
+ // A throwing sink must never surface inside the merchant's fetch chain.
4726
+ }
4727
+ }
4728
+ /**
4729
+ * Scan a Response WITHOUT disturbing the merchant's own read. `clone()` must
4730
+ * happen synchronously, before the caller can consume the body; the read of
4731
+ * the clone is deliberately not awaited by the caller.
4732
+ */
4733
+ scanResponse(response) {
4734
+ var _a, _b, _c, _d, _e, _f;
4735
+ try {
4736
+ const type = (_c = (_b = (_a = response.headers) === null || _a === void 0 ? void 0 : _a.get) === null || _b === void 0 ? void 0 : _b.call(_a, 'content-type')) !== null && _c !== void 0 ? _c : '';
4737
+ if (type && !SCANNABLE_TYPE_RE.test(type))
4738
+ return;
4739
+ const declared = Number((_f = (_e = (_d = response.headers) === null || _d === void 0 ? void 0 : _d.get) === null || _e === void 0 ? void 0 : _e.call(_d, 'content-length')) !== null && _f !== void 0 ? _f : NaN);
4740
+ if (Number.isFinite(declared) && declared > this.maxScanBytes)
4741
+ return;
4742
+ const clone = typeof response.clone === 'function' ? response.clone() : null;
4743
+ if (!clone)
4744
+ return;
4745
+ void clone
4746
+ .text()
4747
+ .then((body) => this.emit(extractSessionId(body.slice(0, this.maxScanBytes))))
4748
+ .catch(() => {
4749
+ /* body already disturbed / opaque response — nothing to do */
4750
+ });
4751
+ }
4752
+ catch (_g) {
4753
+ /* never let observation break the request */
4754
+ }
4755
+ }
4756
+ hookFetch() {
4757
+ if (typeof window.fetch !== 'function')
4758
+ return;
4759
+ const original = window.fetch;
4760
+ const self = this;
4761
+ const patched = function patchedFetch(...args) {
4762
+ const result = original.apply(this !== null && this !== void 0 ? this : window, args);
4763
+ try {
4764
+ // Attach passively: the merchant still gets the original promise, and a
4765
+ // rejection here is theirs to handle, not ours to observe twice.
4766
+ result.then((response) => self.scanResponse(response)).catch(() => { });
4767
+ }
4768
+ catch (_a) {
4769
+ /* ignore */
4770
+ }
4771
+ return result;
4772
+ };
4773
+ window.fetch = patched;
4774
+ this.disposers.push(() => {
4775
+ // Only restore if nobody wrapped us afterwards — clobbering a later
4776
+ // wrapper would silently disable whatever installed it.
4777
+ if (window.fetch === patched)
4778
+ window.fetch = original;
4779
+ });
4780
+ }
4781
+ hookXhr() {
4782
+ if (typeof XMLHttpRequest === 'undefined')
4783
+ return;
4784
+ const proto = XMLHttpRequest.prototype;
4785
+ const originalSend = proto.send;
4786
+ if (typeof originalSend !== 'function')
4787
+ return;
4788
+ const self = this;
4789
+ const patched = function patchedSend(...args) {
4790
+ try {
4791
+ this.addEventListener('load', () => {
4792
+ try {
4793
+ // responseText throws for blob/arraybuffer response types.
4794
+ if (this.responseType !== '' && this.responseType !== 'text')
4795
+ return;
4796
+ const body = this.responseText;
4797
+ if (!body || body.length > self.maxScanBytes)
4798
+ return;
4799
+ self.emit(extractSessionId(body));
4800
+ }
4801
+ catch (_a) {
4802
+ /* ignore */
4803
+ }
4804
+ });
4805
+ }
4806
+ catch (_a) {
4807
+ /* ignore */
4808
+ }
4809
+ return originalSend.apply(this, args);
4810
+ };
4811
+ proto.send = patched;
4812
+ this.disposers.push(() => {
4813
+ if (proto.send === patched)
4814
+ proto.send = originalSend;
4815
+ });
4816
+ }
4817
+ /**
4818
+ * Direct links to checkout.stripe.com. Capture phase so we still see the click
4819
+ * when the merchant's own handler calls stopPropagation().
4820
+ */
4821
+ hookClicks() {
4822
+ if (typeof document === 'undefined')
4823
+ return;
4824
+ const onClick = (e) => {
4825
+ var _a, _b;
4826
+ try {
4827
+ const target = (_b = (_a = e.target) === null || _a === void 0 ? void 0 : _a.closest) === null || _b === void 0 ? void 0 : _b.call(_a, 'a[href]');
4828
+ if (!target || !target.href || !isCheckoutUrl(target.href))
4829
+ return;
4830
+ this.emit(extractSessionId(target.href));
4831
+ }
4832
+ catch (_c) {
4833
+ /* never block navigation */
4834
+ }
4835
+ };
4836
+ document.addEventListener('click', onClick, true);
4837
+ this.disposers.push(() => document.removeEventListener('click', onClick, true));
4838
+ }
4839
+ hookWindowOpen() {
4840
+ if (typeof window.open !== 'function')
4841
+ return;
4842
+ const original = window.open;
4843
+ const self = this;
4844
+ const patched = function patchedOpen(...args) {
4845
+ var _a;
4846
+ try {
4847
+ const url = args[0];
4848
+ const href = typeof url === 'string' ? url : (_a = url === null || url === void 0 ? void 0 : url.toString) === null || _a === void 0 ? void 0 : _a.call(url);
4849
+ if (href && isCheckoutUrl(href))
4850
+ self.emit(extractSessionId(href));
4851
+ }
4852
+ catch (_b) {
4853
+ /* ignore */
4854
+ }
4855
+ return original.apply(this !== null && this !== void 0 ? this : window, args);
4856
+ };
4857
+ window.open = patched;
4858
+ this.disposers.push(() => {
4859
+ if (window.open === patched)
4860
+ window.open = original;
4861
+ });
4862
+ }
4863
+ }
4864
+
4377
4865
  /** Keys the remote config is allowed to fill on DatalyrConfig. */
4378
4866
  const REMOTE_KEYS = [
4379
4867
  'autoIdentify',
@@ -4381,6 +4869,7 @@ const REMOTE_KEYS = [
4381
4869
  'autoIdentifyAPI',
4382
4870
  'autoIdentifyShopify',
4383
4871
  'shopifyCartAttributes',
4872
+ 'stripeCheckoutSessions',
4384
4873
  'checkoutChampDomains',
4385
4874
  'respectGlobalPrivacyControl',
4386
4875
  'respectDoNotTrack',
@@ -4419,6 +4908,16 @@ function applyRemoteConfig(config, remote, explicitKeys) {
4419
4908
  * Datalyr Web SDK
4420
4909
  * Modern attribution tracking for web applications
4421
4910
  */
4911
+ /**
4912
+ * WEB-20. Fingerprint of the last identify() that actually emitted, so a host
4913
+ * app calling identify() on every route change does not re-emit an unchanged
4914
+ * identity. Cleared by reset(). Mirrors iOS `datalyr_last_identity_fingerprint`
4915
+ * and RN `@datalyr/last_identity_fingerprint`.
4916
+ *
4917
+ * Not PII: the stored value is a hash, and it is written through the same
4918
+ * `storage` wrapper as every other key (so it inherits the `dl_` prefix).
4919
+ */
4920
+ const IDENTIFY_FINGERPRINT_KEY = 'dl_identify_fingerprint';
4422
4921
  class Datalyr {
4423
4922
  constructor() {
4424
4923
  // Keys the caller passed to init() (before built-in defaults were merged).
@@ -4434,10 +4933,26 @@ class Datalyr {
4434
4933
  this.errors = [];
4435
4934
  this.MAX_ERRORS = 50;
4436
4935
  this.lastSpaPath = null; // dedups SPA pageviews (replaceState-on-mount double-fire)
4936
+ // Shopify loads Customer Privacy asynchronously. Keep the initial pageview
4937
+ // pending until initialization is complete and analytics consent is known,
4938
+ // then release it exactly once when consent allows tracking.
4939
+ this.initialPageViewReady = false;
4940
+ this.initialPageViewSent = false;
4437
4941
  // FIXED (ISSUE-01): Async initialization promise to prevent race conditions
4438
4942
  this.initializationPromise = null;
4439
4943
  // Opt-out check moved to init() after cookies configured (Issue #14)
4440
4944
  }
4945
+ /**
4946
+ * Return the workspace configured for this instance, or null before init().
4947
+ *
4948
+ * CDN bootstrap uses this public accessor instead of reaching into the
4949
+ * private runtime config when deciding whether an existing global belongs
4950
+ * to the requested workspace.
4951
+ */
4952
+ getWorkspaceId() {
4953
+ var _a, _b;
4954
+ return (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspaceId) !== null && _b !== void 0 ? _b : null;
4955
+ }
4441
4956
  /**
4442
4957
  * Initialize the SDK
4443
4958
  */
@@ -4581,6 +5096,11 @@ class Datalyr {
4581
5096
  const deviceId = this.identity.getAnonymousId();
4582
5097
  yield dataEncryption.initialize(this.config.workspaceId, deviceId);
4583
5098
  this.userProperties = yield storage.getEncrypted('dl_user_traits', {});
5099
+ // WEB-22: restore a PII user id that was persisted encrypted. Must run
5100
+ // here — it needs dataEncryption to be initialized, so it cannot happen
5101
+ // in the IdentityManager constructor. It never overwrites an id already
5102
+ // set by an explicit identify() earlier in this page load.
5103
+ yield this.identity.hydrateEncryptedUserId();
4584
5104
  this.log('Encryption initialized, user properties loaded');
4585
5105
  }
4586
5106
  catch (encErr) {
@@ -4670,14 +5190,20 @@ class Datalyr {
4670
5190
  // Setup auto-identify callback
4671
5191
  this.autoIdentify.initialize((email, source) => {
4672
5192
  this.log(`Auto-identified user: ${email} from ${source}`);
4673
- // Track auto-identify event
4674
- this.track('$auto_identify', {
4675
- email,
4676
- source,
4677
- timestamp: Date.now()
4678
- });
4679
- // Automatically call identify with email
4680
- this.identify(email, { email });
5193
+ // WEB-21: ONE event, not two.
5194
+ //
5195
+ // This used to emit `$auto_identify` and then call identify(),
5196
+ // which emits `$identify` — two events ~1ms apart carrying the same
5197
+ // email. Production over 7 days on workspace f6260736 showed a
5198
+ // perfect 379 / 379 / 379 split ($identify / $auto_identify /
5199
+ // visitors): every auto-identification was booked twice.
5200
+ //
5201
+ // Nothing consumed `$auto_identify`: grepped across the whole
5202
+ // platform (app/, lib/, all Cloudflare workers, all Tinybird pipes)
5203
+ // — zero readers, while prod carried 6,197 of them in 30 days.
5204
+ // The only information it added over `$identify` was WHICH detector
5205
+ // found the email, so that is preserved as a trait instead.
5206
+ this.identify(email, { email, auto_identify_source: source });
4681
5207
  });
4682
5208
  }
4683
5209
  // Stamp attribution signals into the Shopify cart (OPT-IN, default off).
@@ -4708,10 +5234,22 @@ class Datalyr {
4708
5234
  if (this.config.stripePaymentLinks !== false && this.shouldTrack()) {
4709
5235
  this.syncStripePaymentLinks((_b = this.config.stripeLinkDomains) !== null && _b !== void 0 ? _b : []);
4710
5236
  }
4711
- // Track initial page view if enabled (AFTER encryption ready)
4712
- if (this.config.trackPageViews) {
4713
- this.page();
5237
+ // Checkout Session capture (DEFAULT ON). The decorator above cannot help
5238
+ // when the merchant's BACKEND creates the session — checkout.stripe.com
5239
+ // ignores client_reference_id post-creation — which is how most SaaS
5240
+ // checkouts work, and why payers arrive at our webhook with no visitor
5241
+ // (measured 0.5% and 13.3% visitor coverage on the two Stripe tenants).
5242
+ // The session id still has to reach the browser, so we observe it and
5243
+ // let the server join on session.id. Same shouldTrack() gate as the
5244
+ // decorator: an opted-out visitor's id is never paired with a checkout.
5245
+ if (this.config.stripeCheckoutSessions !== false && this.shouldTrack()) {
5246
+ this.startStripeSessionCapture();
4714
5247
  }
5248
+ // Track the initial page view after encryption is ready. On Shopify the
5249
+ // Customer Privacy API can still be loading, so retain one pending
5250
+ // pageview and release it from onShopifyConsentChanged() once allowed.
5251
+ this.initialPageViewReady = true;
5252
+ this.trackInitialPageViewOnce();
4715
5253
  this.log('Async initialization complete');
4716
5254
  }
4717
5255
  catch (error) {
@@ -4844,6 +5382,50 @@ class Datalyr {
4844
5382
  /**
4845
5383
  * Identify a user
4846
5384
  */
5385
+ /**
5386
+ * Stable fingerprint of an identity for redundant-emit suppression (WEB-20).
5387
+ *
5388
+ * Keys are sorted and each value is JSON-serialized, so `{a,b}` and `{b,a}`
5389
+ * collapse to one identity while a genuinely changed nested trait does not.
5390
+ * (The mobile SDKs use `String(value)`, which flattens every object to
5391
+ * `[object Object]` and can swallow a real change; web traits are plain JSON,
5392
+ * so it can afford to be exact.)
5393
+ *
5394
+ * Hashed rather than stored raw so the key does not become another copy of the
5395
+ * user's traits at rest. Being honest about the strength: a 32-bit
5396
+ * non-cryptographic digest sitting beside a readable `dl_dl_anonymous_id` is
5397
+ * NOT protection against a determined reader — it defeats casual inspection
5398
+ * and bulk scraping, nothing more. The PII that matters is handled properly
5399
+ * (encrypted `dl_user_id_pii`, encrypted `dl_user_traits`). 32 bits also means
5400
+ * a ~1-in-4.3e9 chance per identity that a genuine change is suppressed;
5401
+ * acceptable for change detection, which is all this is.
5402
+ */
5403
+ identityFingerprint(userId, traits = {}) {
5404
+ const stableTraits = Object.keys(traits || {})
5405
+ .sort()
5406
+ .map((key) => {
5407
+ let value;
5408
+ try {
5409
+ value = JSON.stringify(traits[key]);
5410
+ }
5411
+ catch (_a) {
5412
+ // Circular/unserializable trait — fall back to a coarse marker rather
5413
+ // than throwing inside identify().
5414
+ value = '[unserializable]';
5415
+ }
5416
+ return `${key}=${value}`;
5417
+ })
5418
+ .join('&');
5419
+ const input = `${this.identity.getAnonymousId()}|${userId}|${stableTraits}`;
5420
+ // 32-bit FNV-1a. Not cryptographic — this only needs to detect change, and
5421
+ // it must be synchronous (crypto.subtle is async and identify() is not).
5422
+ let hash = 0x811c9dc5;
5423
+ for (let i = 0; i < input.length; i++) {
5424
+ hash ^= input.charCodeAt(i);
5425
+ hash = Math.imul(hash, 0x01000193);
5426
+ }
5427
+ return (hash >>> 0).toString(16);
5428
+ }
4847
5429
  identify(userId, traits = {}) {
4848
5430
  if (!this.initialized) {
4849
5431
  console.warn('[Datalyr] SDK not initialized. Call init() first.');
@@ -4883,8 +5465,31 @@ class Datalyr {
4883
5465
  // If encryption fails, user traits are only stored in memory (this.userProperties)
4884
5466
  // and will be lost on page reload - but PII is NOT exposed in localStorage
4885
5467
  });
4886
- // Track $identify event
4887
- this.track('$identify', Object.assign(Object.assign({}, identityLink), { traits }));
5468
+ // WEB-20: redundant-identify suppression, matching iOS 2.1.11 / RN 1.7.16.
5469
+ //
5470
+ // identify() is host-app-driven and SPA routers commonly call it in a
5471
+ // route effect, so an unchanged identity was re-emitted on every
5472
+ // navigation. The mobile SDKs got this in 2.1.10/1.7.15; web did not.
5473
+ //
5474
+ // Fingerprint = anonymousId | userId | sorted traits. The anonymous id is
5475
+ // included so a reset()/rotation always re-emits and identity links are
5476
+ // never lost — only exact repeats are skipped.
5477
+ //
5478
+ // Only the EVENT is suppressed. `this.identity.identify()` above has
5479
+ // already persisted `dl_user_id`, traits are still merged and encrypted,
5480
+ // and the plugin handlers below still run on every call — a plugin's
5481
+ // `identify` hook is a customer extension point whose semantics we cannot
5482
+ // assume, so its contract ("called when identify() is called") is
5483
+ // deliberately left intact.
5484
+ const identityFingerprint = this.identityFingerprint(userId, traits);
5485
+ const isRedundantIdentify = storage.getString(IDENTIFY_FINGERPRINT_KEY, null) === identityFingerprint;
5486
+ if (isRedundantIdentify) {
5487
+ this.log('Skipping redundant identify (unchanged identity):', userId);
5488
+ }
5489
+ else {
5490
+ storage.set(IDENTIFY_FINGERPRINT_KEY, identityFingerprint);
5491
+ this.track('$identify', Object.assign(Object.assign({}, identityLink), { traits }));
5492
+ }
4888
5493
  // Call plugin handlers
4889
5494
  if (this.config.plugins) {
4890
5495
  for (const plugin of this.config.plugins) {
@@ -4904,6 +5509,18 @@ class Datalyr {
4904
5509
  this.trackError(error, { userId });
4905
5510
  }
4906
5511
  }
5512
+ /**
5513
+ * WEB-27: queue health, including events the SDK gave up on.
5514
+ *
5515
+ * `getStats()` existed on EventQueue but was unreachable — `queue` is private
5516
+ * and nothing exposed it, so the observability fix could not actually be
5517
+ * observed. A non-zero `droppedEvents` means data was lost.
5518
+ */
5519
+ getQueueStats() {
5520
+ if (!this.queue)
5521
+ return null;
5522
+ return this.queue.getStats();
5523
+ }
4907
5524
  /**
4908
5525
  * Track a page view
4909
5526
  */
@@ -5021,6 +5638,9 @@ class Datalyr {
5021
5638
  // values to the next user's events (cross-user contamination on shared devices).
5022
5639
  this.superProperties = {};
5023
5640
  storage.remove('dl_user_traits');
5641
+ // WEB-20: drop the identify fingerprint, so a logout→login (or a different
5642
+ // user on this browser) always re-emits $identify and the link is rebuilt.
5643
+ storage.remove(IDENTIFY_FINGERPRINT_KEY);
5024
5644
  // Clear the auto-identify guard so a different user on the same browser is
5025
5645
  // re-captured (it short-circuits while dl_auto_identified_email is present), and so
5026
5646
  // the prior user's email isn't left at rest after logout.
@@ -5168,16 +5788,21 @@ class Datalyr {
5168
5788
  * (same convention as pixels/auto-identify).
5169
5789
  */
5170
5790
  disposeMarketingLinkDecorators() {
5171
- var _a, _b;
5791
+ var _a, _b, _c;
5172
5792
  try {
5173
5793
  (_a = this.stripeLinksDisposer) === null || _a === void 0 ? void 0 : _a.call(this);
5174
5794
  }
5175
- catch ( /* best-effort */_c) { /* best-effort */ }
5795
+ catch ( /* best-effort */_d) { /* best-effort */ }
5176
5796
  this.stripeLinksDisposer = undefined;
5177
5797
  try {
5178
- (_b = this.outboundDisposer) === null || _b === void 0 ? void 0 : _b.call(this);
5798
+ (_b = this.stripeSessionWatcher) === null || _b === void 0 ? void 0 : _b.stop();
5179
5799
  }
5180
- catch ( /* best-effort */_d) { /* best-effort */ }
5800
+ catch ( /* best-effort */_e) { /* best-effort */ }
5801
+ this.stripeSessionWatcher = undefined;
5802
+ try {
5803
+ (_c = this.outboundDisposer) === null || _c === void 0 ? void 0 : _c.call(this);
5804
+ }
5805
+ catch ( /* best-effort */_f) { /* best-effort */ }
5181
5806
  this.outboundDisposer = undefined;
5182
5807
  }
5183
5808
  optOut() {
@@ -5206,8 +5831,22 @@ class Datalyr {
5206
5831
  // Purge PII at rest.
5207
5832
  this.userProperties = {};
5208
5833
  storage.remove('dl_user_traits');
5834
+ // WEB-26: remove the PLAINTEXT id as well. optOut() purged only the
5835
+ // encrypted copy, so an opted-out visitor whose email was written by an
5836
+ // older build kept it at rest — the one state where that is least
5837
+ // defensible.
5838
+ storage.remove('dl_user_id');
5839
+ storage.remove('dl_user_id_pii');
5840
+ storage.remove(IDENTIFY_FINGERPRINT_KEY);
5209
5841
  storage.remove('dl_auto_identified_email');
5210
5842
  storage.remove('dl_journey');
5843
+ // WEB-25: first/last touch hold redacted-but-full landing URLs, referrers and
5844
+ // click ids for up to 90 days. reset() has always cleared them; optOut() did
5845
+ // not — so an opted-out visitor kept marketing attribution at rest, which is
5846
+ // the one state where it is least defensible. Same rationale as dl_journey
5847
+ // directly above.
5848
+ storage.remove('dl_first_touch');
5849
+ storage.remove('dl_last_touch');
5211
5850
  this.log('User opted out');
5212
5851
  }
5213
5852
  /**
@@ -5270,8 +5909,16 @@ class Datalyr {
5270
5909
  this.autoIdentify = undefined;
5271
5910
  this.userProperties = {};
5272
5911
  storage.remove('dl_user_traits');
5912
+ // WEB-26: see optOut() — the plaintext id must go too.
5913
+ storage.remove('dl_user_id');
5914
+ storage.remove('dl_user_id_pii');
5915
+ storage.remove(IDENTIFY_FINGERPRINT_KEY);
5273
5916
  storage.remove('dl_auto_identified_email');
5274
5917
  storage.remove('dl_journey');
5918
+ // WEB-25: see optOut() — withdrawn analytics consent must not leave 90-day
5919
+ // marketing attribution at rest either.
5920
+ storage.remove('dl_first_touch');
5921
+ storage.remove('dl_last_touch');
5275
5922
  }
5276
5923
  else {
5277
5924
  // TR-15 (P3): grant → persist the in-memory anon id now (see onShopifyConsentChanged).
@@ -5525,6 +6172,39 @@ class Datalyr {
5525
6172
  * changes. window.open(paymentLink) is not covered (use getVisitorId()
5526
6173
  * manually); iframe/shadow-DOM links are unreachable from document.
5527
6174
  */
6175
+ /**
6176
+ * Observe Stripe Checkout Session ids and report each one once.
6177
+ *
6178
+ * The event is what carries the pairing: the server stores
6179
+ * (stripe_session_id -> visitor_id) and, when checkout.session.completed
6180
+ * arrives without a client_reference_id, joins on session.id and feeds the
6181
+ * SAME cacheCustomerVisitor path the Payment Link flow already uses — so
6182
+ * every later invoice for that customer inherits the visitor too.
6183
+ *
6184
+ * Consent is re-checked at emit time, not just at init: a visitor can
6185
+ * withdraw between page load and checkout, and this pairing is exactly the
6186
+ * kind of identity link that must stop when they do.
6187
+ */
6188
+ startStripeSessionCapture() {
6189
+ if (this.stripeSessionWatcher)
6190
+ return;
6191
+ const watcher = new StripeSessionWatcher();
6192
+ this.stripeSessionWatcher = watcher;
6193
+ watcher.start((stripeSessionId) => {
6194
+ var _a;
6195
+ if (!this.shouldTrack())
6196
+ return;
6197
+ this.track('$stripe_checkout_session', { stripe_session_id: stripeSessionId });
6198
+ // The very next thing this page does is navigate to Stripe, so flush now
6199
+ // rather than let the batch timer lose the pairing to the unload.
6200
+ try {
6201
+ (_a = this.queue) === null || _a === void 0 ? void 0 : _a.flush();
6202
+ }
6203
+ catch (_b) {
6204
+ /* best-effort — never block the checkout */
6205
+ }
6206
+ });
6207
+ }
5528
6208
  syncStripePaymentLinks(extraDomains) {
5529
6209
  if (typeof window === "undefined" || typeof document === "undefined")
5530
6210
  return;
@@ -5751,7 +6431,7 @@ class Datalyr {
5751
6431
  // drift from the package again (it sat at 1.7.4 across the 1.7.5 release). The
5752
6432
  // build guard (scripts/check-bundle.js, run by build:check) still verifies the
5753
6433
  // deployable bundles carry the package.json version. (FSR-103)
5754
- sdk_version: '1.7.6',
6434
+ sdk_version: '1.7.8',
5755
6435
  sdk_name: 'datalyr-web-sdk',
5756
6436
  // A3-25: versioned-envelope stamp. Every SDK emits schema_version so the ingest/contract
5757
6437
  // layer can key on ONE canonical envelope version (snake_case fields, event_name/event_data
@@ -5944,6 +6624,8 @@ class Datalyr {
5944
6624
  // visitor_id that vanishes on the next page load. Idempotent.
5945
6625
  if (allowed)
5946
6626
  this.identity.enablePersistence();
6627
+ if (allowed)
6628
+ this.trackInitialPageViewOnce();
5947
6629
  if (!allowed) {
5948
6630
  // Mirror setConsent() withdrawal: purge buffered events so events captured
5949
6631
  // before the decline can't drain if consent is later re-granted.
@@ -5975,6 +6657,15 @@ class Datalyr {
5975
6657
  }
5976
6658
  this.log('Shopify consent collected — analytics allowed:', allowed, '— marketing blocked:', marketingBlocked);
5977
6659
  }
6660
+ /** Release the automatic landing pageview once, after init and consent. */
6661
+ trackInitialPageViewOnce() {
6662
+ if (!this.initialPageViewReady || this.initialPageViewSent)
6663
+ return;
6664
+ if (!this.config.trackPageViews || !this.initialized || !this.shouldTrack())
6665
+ return;
6666
+ this.initialPageViewSent = true;
6667
+ this.page();
6668
+ }
5978
6669
  /**
5979
6670
  * Setup SPA tracking
5980
6671
  * Fixed Issue #15: Store original methods for cleanup
@@ -6169,6 +6860,10 @@ class Datalyr {
6169
6860
  this.stripeLinksDisposer();
6170
6861
  this.stripeLinksDisposer = undefined;
6171
6862
  }
6863
+ if (this.stripeSessionWatcher) {
6864
+ this.stripeSessionWatcher.stop();
6865
+ this.stripeSessionWatcher = undefined;
6866
+ }
6172
6867
  // Clean up queue
6173
6868
  if (this.queue) {
6174
6869
  this.queue.destroy();
@@ -6194,6 +6889,8 @@ class Datalyr {
6194
6889
  this.container = undefined;
6195
6890
  this.autoIdentify = undefined;
6196
6891
  this.lastSpaPath = null;
6892
+ this.initialPageViewReady = false;
6893
+ this.initialPageViewSent = false;
6197
6894
  // Clear any remaining data
6198
6895
  this.superProperties = {};
6199
6896
  this.userProperties = {};
@@ -6202,19 +6899,27 @@ class Datalyr {
6202
6899
  this.log('SDK destroyed');
6203
6900
  }
6204
6901
  }
6205
- // Create singleton instance. TR-23: reuse an existing window.datalyr (a prior tag's instance —
6206
- // Shopify App Embed + a manual snippet coexisting, or a double-included bundle) instead of
6207
- // constructing a SECOND one. Two instances each patch history.pushState and fire their own
6208
- // pageviews (distinct event_ids no server-side dedup). A plain truthy check (NOT instanceof):
6209
- // two <script> tags run two separate IIFEs whose Datalyr classes are structurally identical but
6210
- // distinct objects, so instanceof would fail across them. With one shared instance, the second
6211
- // tag's bootstrap init() hits the instance-level `initialized` guard and no-ops.
6212
- const datalyr = (typeof window !== 'undefined' && window.datalyr) || new Datalyr();
6902
+ /**
6903
+ * Create an independent SDK instance without reading or mutating window.
6904
+ *
6905
+ * The CDN bootstrap uses this when an existing global is configured for a
6906
+ * different workspace. Package consumers can also opt into multiple explicit
6907
+ * instances without changing the default singleton contract below.
6908
+ */
6909
+ function createDatalyrInstance() {
6910
+ return new Datalyr();
6911
+ }
6912
+ // Create the default singleton. TR-23: reuse an existing window.datalyr (a
6913
+ // prior tag's instance or a package singleton) so npm/ESM/CJS consumers retain
6914
+ // the established one-global behavior. Workspace conflict resolution belongs
6915
+ // to the CDN bootstrap, which has the authoritative script-tag configuration.
6916
+ const datalyr = (typeof window !== 'undefined' && window.datalyr) || createDatalyrInstance();
6213
6917
  // Expose global API
6214
6918
  if (typeof window !== 'undefined') {
6215
6919
  window.datalyr = datalyr;
6216
6920
  }
6217
6921
 
6922
+ exports.createDatalyrInstance = createDatalyrInstance;
6218
6923
  exports.datalyr = datalyr;
6219
6924
  exports.default = datalyr;
6220
6925
  //# sourceMappingURL=datalyr.cjs.js.map