@usesophi/sophi-web-object 1.3.1 → 1.3.2

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.
package/dist/sophi.js CHANGED
@@ -1,10 +1,44 @@
1
1
  /*!
2
- * sophi-web-object v1.3.1
2
+ * sophi-web-object v1.3.2
3
3
  * Framework-agnostic e-commerce tracking script
4
4
  */
5
- var SophiTracker = (function (exports) {
5
+ (function () {
6
6
  'use strict';
7
7
 
8
+ /******************************************************************************
9
+ Copyright (c) Microsoft Corporation.
10
+
11
+ Permission to use, copy, modify, and/or distribute this software for any
12
+ purpose with or without fee is hereby granted.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
15
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
16
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
17
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
18
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
19
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
20
+ PERFORMANCE OF THIS SOFTWARE.
21
+ ***************************************************************************** */
22
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
23
+
24
+
25
+ function __rest(s, e) {
26
+ var t = {};
27
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
28
+ t[p] = s[p];
29
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
30
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
31
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
32
+ t[p[i]] = s[p[i]];
33
+ }
34
+ return t;
35
+ }
36
+
37
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
38
+ var e = new Error(message);
39
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
40
+ };
41
+
8
42
  /** Sophi API origin — set via SOPHI_API_URL in .env at build time. */
9
43
  const SOPHI_API_ORIGIN = "https://api.usesophi.com";
10
44
  const DEFAULTS = {
@@ -302,6 +336,26 @@ var SophiTracker = (function (exports) {
302
336
  log(`Queued event: ${envelope.event_type} (queue size: ${queue.length})`);
303
337
  scheduleFlush();
304
338
  }
339
+ /**
340
+ * Send one event right away, bypassing the debounce window. Used for Sophi
341
+ * button clicks, which are usually followed by a same-tab navigation.
342
+ *
343
+ * With an established session the event goes out through fetch keepalive
344
+ * (with auth headers), which survives the page being torn down. Without a
345
+ * session yet it falls back to the normal queue.
346
+ */
347
+ function sendImmediate(envelope) {
348
+ if (!hasStorageConsent()) {
349
+ log(`Dropped event (no storage consent): ${envelope.event_type}`);
350
+ return;
351
+ }
352
+ const session = getResolvedSession();
353
+ if (session && sendOnUnload(envelope, session)) {
354
+ log(`Sent event immediately: ${envelope.event_type}`);
355
+ return;
356
+ }
357
+ enqueue(envelope);
358
+ }
305
359
  function scheduleFlush() {
306
360
  if (debounceTimer !== null)
307
361
  return;
@@ -355,6 +409,213 @@ var SophiTracker = (function (exports) {
355
409
  queue.length = 0;
356
410
  }
357
411
 
412
+ /**
413
+ * Campaign attribution (opt-in via `config.attribution: true`).
414
+ *
415
+ * On boot the SDK reads UTM parameters, ad click IDs and the external referrer
416
+ * hostname of the current page view. A page view that has any of them is a
417
+ * "touch". The first touch is kept for 30 days; the last touch is replaced by
418
+ * every new touch; direct visits and internal navigation change nothing.
419
+ *
420
+ * The value is held in memory and written to localStorage only while storage
421
+ * consent is granted. It is attached to every event under
422
+ * `page.custom._sophi.attribution` by the collector.
423
+ */
424
+ const UTM_FIELDS = {
425
+ utm_source: 'source',
426
+ utm_medium: 'medium',
427
+ utm_campaign: 'campaign',
428
+ utm_term: 'term',
429
+ utm_content: 'content',
430
+ };
431
+ const CLICK_ID_SOURCES = {
432
+ gclid: 'google',
433
+ gbraid: 'google',
434
+ wbraid: 'google',
435
+ fbclid: 'facebook',
436
+ msclkid: 'bing',
437
+ ttclid: 'tiktok',
438
+ li_fat_id: 'linkedin',
439
+ };
440
+ const TOUCH_TTL_SECONDS = 30 * 86400;
441
+ const MAX_VALUE_LENGTH = 256;
442
+ /** Touch detected on this page view (null = direct / internal). */
443
+ let pageTouch = null;
444
+ /** Resolved attribution for this page view, attached to events. */
445
+ let current = null;
446
+ // ─── Helpers ──────────────────────────────────────────────────────────────────
447
+ function isEnabled() {
448
+ return getConfig().attribution === true;
449
+ }
450
+ function storageKey() {
451
+ return `sophi-${hashKey(getConfig().apiKey)}-attribution`;
452
+ }
453
+ function clip(value) {
454
+ const trimmed = value === null || value === void 0 ? void 0 : value.trim();
455
+ return trimmed ? trimmed.slice(0, MAX_VALUE_LENGTH) : undefined;
456
+ }
457
+ function bareHost(host) {
458
+ return host.toLowerCase().replace(/^www\./, '');
459
+ }
460
+ function isTouch(value) {
461
+ return (typeof value === 'object' &&
462
+ value !== null &&
463
+ typeof value.timestamp === 'number');
464
+ }
465
+ function readStored() {
466
+ try {
467
+ const raw = localStorage.getItem(storageKey());
468
+ if (!raw)
469
+ return null;
470
+ const parsed = JSON.parse(raw);
471
+ return {
472
+ first: isTouch(parsed === null || parsed === void 0 ? void 0 : parsed.first) ? parsed.first : undefined,
473
+ last: isTouch(parsed === null || parsed === void 0 ? void 0 : parsed.last) ? parsed.last : undefined,
474
+ };
475
+ }
476
+ catch (_a) {
477
+ return null;
478
+ }
479
+ }
480
+ function writeStored(value) {
481
+ try {
482
+ if (value) {
483
+ localStorage.setItem(storageKey(), JSON.stringify(value));
484
+ }
485
+ else {
486
+ localStorage.removeItem(storageKey());
487
+ }
488
+ }
489
+ catch (_a) {
490
+ // Storage unavailable (private mode, blocked) — keep the in-memory value.
491
+ }
492
+ }
493
+ function fresh(touch, now) {
494
+ return touch && now - touch.timestamp < TOUCH_TTL_SECONDS ? touch : undefined;
495
+ }
496
+ /** Combines stored state with this page view's touch. */
497
+ function mergeAttribution(stored, touch, now) {
498
+ let first = fresh(stored === null || stored === void 0 ? void 0 : stored.first, now);
499
+ let last = fresh(stored === null || stored === void 0 ? void 0 : stored.last, now);
500
+ if (touch) {
501
+ last = touch;
502
+ first = first !== null && first !== void 0 ? first : touch;
503
+ }
504
+ if (!first && !last)
505
+ return null;
506
+ const result = {};
507
+ if (first)
508
+ result.first = first;
509
+ if (last)
510
+ result.last = last;
511
+ return result;
512
+ }
513
+ /**
514
+ * Reads the touch from a page URL and referrer. Returns null for a direct
515
+ * visit or internal navigation. Only the referrer hostname is kept, and the
516
+ * landing URL keeps only its origin, path, UTM and click-ID parameters.
517
+ */
518
+ function detectTouch(href, referrer, now) {
519
+ var _a, _b;
520
+ let url;
521
+ try {
522
+ url = new URL(href);
523
+ }
524
+ catch (_c) {
525
+ return null;
526
+ }
527
+ const params = url.searchParams;
528
+ const touch = { timestamp: now };
529
+ const kept = new URLSearchParams();
530
+ for (const [param, field] of Object.entries(UTM_FIELDS)) {
531
+ const value = clip(params.get(param));
532
+ if (value) {
533
+ touch[field] = value;
534
+ kept.set(param, value);
535
+ }
536
+ }
537
+ for (const param of Object.keys(CLICK_ID_SOURCES)) {
538
+ const value = clip(params.get(param));
539
+ if (value) {
540
+ kept.set(param, value);
541
+ if (!touch.click_id) {
542
+ touch.click_id = value;
543
+ touch.click_id_type = param;
544
+ }
545
+ }
546
+ }
547
+ let referrerHost;
548
+ if (referrer) {
549
+ try {
550
+ const host = new URL(referrer).hostname;
551
+ if (host && bareHost(host) !== bareHost(url.hostname)) {
552
+ referrerHost = host.toLowerCase();
553
+ }
554
+ }
555
+ catch (_d) {
556
+ // Malformed referrer — ignore.
557
+ }
558
+ }
559
+ const hasCampaign = kept.toString() !== '';
560
+ if (!hasCampaign && !referrerHost)
561
+ return null;
562
+ if (referrerHost)
563
+ touch.referrer = referrerHost;
564
+ if (!touch.source) {
565
+ if (touch.click_id_type) {
566
+ touch.source = CLICK_ID_SOURCES[touch.click_id_type];
567
+ }
568
+ else if (referrerHost) {
569
+ touch.source = referrerHost;
570
+ touch.medium = (_a = touch.medium) !== null && _a !== void 0 ? _a : 'referral';
571
+ }
572
+ }
573
+ const query = kept.toString();
574
+ touch.landing_url = (_b = clip(`${url.origin}${url.pathname}${query ? `?${query}` : ''}`)) !== null && _b !== void 0 ? _b : url.origin;
575
+ return touch;
576
+ }
577
+ // ─── Public API ───────────────────────────────────────────────────────────────
578
+ /** Called once at bootstrap. Does nothing unless `config.attribution` is true. */
579
+ function captureAttribution() {
580
+ pageTouch = null;
581
+ current = null;
582
+ if (!isEnabled())
583
+ return;
584
+ const now = Math.floor(Date.now() / 1000);
585
+ pageTouch = detectTouch(window.location.href, document.referrer, now);
586
+ if (hasStorageConsent()) {
587
+ current = mergeAttribution(readStored(), pageTouch, now);
588
+ writeStored(current);
589
+ }
590
+ else {
591
+ // No consent: keep this page view's touch in memory only.
592
+ current = mergeAttribution(null, pageTouch, now);
593
+ }
594
+ if (current)
595
+ log('Attribution captured', current);
596
+ }
597
+ /** Called once storage consent is granted: merges with stored state and persists. */
598
+ function persistAttribution() {
599
+ if (!isEnabled() || !hasStorageConsent())
600
+ return;
601
+ const now = Math.floor(Date.now() / 1000);
602
+ current = mergeAttribution(readStored(), pageTouch, now);
603
+ writeStored(current);
604
+ }
605
+ /** Called when storage consent is withdrawn: removes the stored value. */
606
+ function clearAttribution() {
607
+ if (!isEnabled())
608
+ return;
609
+ writeStored(null);
610
+ current = mergeAttribution(null, pageTouch, Math.floor(Date.now() / 1000));
611
+ }
612
+ /** Attribution to attach to events, or undefined when there is none. */
613
+ function getAttribution() {
614
+ if (!current || !isEnabled())
615
+ return undefined;
616
+ return Object.assign({}, current);
617
+ }
618
+
358
619
  function mapPageEvent(page, sdkVersion, context) {
359
620
  if (!page.type) {
360
621
  warn('page.type is required — skipping page_view event');
@@ -367,6 +628,90 @@ var SophiTracker = (function (exports) {
367
628
  return Object.assign({ event_type: 'page_view', client_timestamp: Math.floor(Date.now() / 1000), sdk_version: sdkVersion, page }, context);
368
629
  }
369
630
 
631
+ const MAX_LENGTH = 64;
632
+ const ENTRY_TYPES = [
633
+ 'search_bar',
634
+ 'post_search',
635
+ 'floating_trigger',
636
+ 'homepage_widget',
637
+ 'pdp',
638
+ 'product_grid',
639
+ 'menu',
640
+ 'checkout',
641
+ ];
642
+ /**
643
+ * Returns a copy of `page` with `patch` merged into `page.custom._sophi`.
644
+ * The integrator's own `page.custom` keys are kept, and the original object
645
+ * is never mutated (writing back into sophi_object.page would make the Proxy
646
+ * emit an extra page_view).
647
+ */
648
+ function withSophi(page, patch) {
649
+ var _a;
650
+ const custom = (_a = page.custom) !== null && _a !== void 0 ? _a : {};
651
+ const existing = custom._sophi;
652
+ const previous = typeof existing === 'object' && existing !== null && !Array.isArray(existing)
653
+ ? existing
654
+ : {};
655
+ return Object.assign(Object.assign({}, page), { custom: Object.assign(Object.assign({}, custom), { _sophi: Object.assign(Object.assign({}, previous), patch) }) });
656
+ }
657
+ /** Validates and normalises an entry. Returns null (after a warning) when invalid. */
658
+ function normalizeEntry(input) {
659
+ const placement = typeof (input === null || input === void 0 ? void 0 : input.placement) === 'string' ? input.placement.trim() : '';
660
+ if (!placement) {
661
+ warn('entry.placement is required — skipping entry event');
662
+ return null;
663
+ }
664
+ if (placement.length > MAX_LENGTH) {
665
+ warn(`entry.placement must be at most ${MAX_LENGTH} characters — skipping entry event`);
666
+ return null;
667
+ }
668
+ const entry = { placement };
669
+ if ((input === null || input === void 0 ? void 0 : input.group) !== undefined) {
670
+ const group = typeof input.group === 'string' ? input.group.trim() : '';
671
+ if (!group) {
672
+ warn('entry.group must be a non-empty string — sending without group');
673
+ }
674
+ else if (group.length > MAX_LENGTH) {
675
+ warn(`entry.group must be at most ${MAX_LENGTH} characters — sending without group`);
676
+ }
677
+ else {
678
+ entry.group = group;
679
+ }
680
+ }
681
+ if ((input === null || input === void 0 ? void 0 : input.type) !== undefined) {
682
+ if (ENTRY_TYPES.includes(input.type)) {
683
+ entry.type = input.type;
684
+ }
685
+ else {
686
+ warn(`entry.type "${String(input.type)}" is not a standard type — sending without type`);
687
+ }
688
+ }
689
+ return entry;
690
+ }
691
+ /**
692
+ * Maps a Sophi button click to a `custom` event. The entry travels under
693
+ * `page.custom._sophi.entry`, so no change to the ingest contract is needed.
694
+ */
695
+ function mapEntryEvent(input, page, sdkVersion) {
696
+ if (!page.type) {
697
+ warn('page.type is required — skipping entry event');
698
+ return null;
699
+ }
700
+ if (!page.url) {
701
+ warn('page.url is required — skipping entry event');
702
+ return null;
703
+ }
704
+ const entry = normalizeEntry(input);
705
+ if (!entry)
706
+ return null;
707
+ return {
708
+ event_type: 'custom',
709
+ client_timestamp: Math.floor(Date.now() / 1000),
710
+ sdk_version: sdkVersion,
711
+ page: withSophi(page, { entry }),
712
+ };
713
+ }
714
+
370
715
  function mapUserEvent(user, page, sdkVersion, context) {
371
716
  if (!user.consent) {
372
717
  warn('user.consent is required — skipping identify event');
@@ -502,7 +847,7 @@ var SophiTracker = (function (exports) {
502
847
  }
503
848
 
504
849
  // Injected at build time via rollup-plugin-replace; falls back to package version.
505
- const SDK_VERSION = '"1.3.1"';
850
+ const SDK_VERSION = '"1.3.2"';
506
851
  // ─── Default event types per object key ──────────────────────────────────────
507
852
  const DEFAULT_EVENT_TYPE = {
508
853
  page: 'page_view',
@@ -598,7 +943,36 @@ var SophiTracker = (function (exports) {
598
943
  if (shouldLogCollection) {
599
944
  log(`Collected: ${envelope.event_type} (triggered by: ${triggeredBy})`);
600
945
  }
601
- enqueue(envelope);
946
+ enqueue(withAttribution(envelope));
947
+ }
948
+ }
949
+ /**
950
+ * Attach campaign attribution under `page.custom._sophi.attribution` when it
951
+ * is enabled and known. Returns the envelope unchanged otherwise, so events
952
+ * stay byte-identical for integrations that have not opted in.
953
+ */
954
+ function withAttribution(envelope) {
955
+ const attribution = getAttribution();
956
+ if (!attribution)
957
+ return envelope;
958
+ return Object.assign(Object.assign({}, envelope), { page: withSophi(envelope.page, { attribution }) });
959
+ }
960
+ /**
961
+ * Collect a Sophi button click (`SophiTracker.trackEntry` or a tagged element)
962
+ * and send it immediately. The click usually triggers a same-tab navigation,
963
+ * so it bypasses the debounced queue when a session is available.
964
+ */
965
+ function collectEntry(entry, obj) {
966
+ var _a;
967
+ const page = obj === null || obj === void 0 ? void 0 : obj.page;
968
+ if (!page) {
969
+ warn(`sophi_object.page is required to send any event — skipping`);
970
+ return;
971
+ }
972
+ const envelope = mapEntryEvent(entry, page, SDK_VERSION);
973
+ if (envelope) {
974
+ log(`Collected: custom (entry: ${((_a = envelope.page.custom) === null || _a === void 0 ? void 0 : _a._sophi).entry.placement})`);
975
+ sendImmediate(withAttribution(envelope));
602
976
  }
603
977
  }
604
978
  /**
@@ -690,14 +1064,6 @@ var SophiTracker = (function (exports) {
690
1064
  function setState(s) {
691
1065
  state = s;
692
1066
  }
693
- /**
694
- * Reset all module-level state to initial values.
695
- * For test isolation only — do not call in production code.
696
- */
697
- function resetTrackerState() {
698
- state = TrackerState.BUFFERING;
699
- pendingQueue.length = 0;
700
- }
701
1067
 
702
1068
  // ─── Bootstrap guard ──────────────────────────────────────────────────────────
703
1069
  /**
@@ -706,6 +1072,7 @@ var SophiTracker = (function (exports) {
706
1072
  */
707
1073
  let bootstrapGuard = false;
708
1074
  let unloadFlushRegistered = false;
1075
+ let entryClickListenerRegistered = false;
709
1076
  // ─── Private push implementation ──────────────────────────────────────────────
710
1077
  /**
711
1078
  * Execute a push() call immediately against the current sophi_object state.
@@ -731,9 +1098,10 @@ var SophiTracker = (function (exports) {
731
1098
  finally {
732
1099
  endInternalPushSuppression();
733
1100
  }
734
- const explicitTrigger = resolveExplicitTriggeredKey(partial);
1101
+ const eventPartial = omitEmptyBasketOnRemove(partial);
1102
+ const explicitTrigger = resolveExplicitTriggeredKey(eventPartial);
735
1103
  if (explicitTrigger) {
736
- const scopedObj = buildExplicitScopedObject(partial, window.sophi_object);
1104
+ const scopedObj = buildExplicitScopedObject(eventPartial, window.sophi_object);
737
1105
  collectExplicit(explicitTrigger, scopedObj);
738
1106
  }
739
1107
  log(`Explicit push ${String((_a = partial.event_type) !== null && _a !== void 0 ? _a : 'custom')} queued once`);
@@ -821,6 +1189,13 @@ var SophiTracker = (function (exports) {
821
1189
  initConfig(Object.assign(Object.assign({}, getConfig()), { userId }));
822
1190
  resetSession();
823
1191
  window.sophi_object.config.userId = userId !== null && userId !== void 0 ? userId : '';
1192
+ // Without storage consent the SDK stays passive: no session request and no
1193
+ // cookies. The new userId is kept in config, so setConsent(true) creates
1194
+ // the session for this user (and merges a guest session if one exists).
1195
+ if (!hasStorageConsent()) {
1196
+ log('updateUser: no storage consent — session will be created when consent is granted.');
1197
+ return;
1198
+ }
824
1199
  void getSession();
825
1200
  },
826
1201
  /**
@@ -852,6 +1227,7 @@ var SophiTracker = (function (exports) {
852
1227
  void (async () => {
853
1228
  try {
854
1229
  await getSession();
1230
+ persistAttribution();
855
1231
  if (window.sophi_object) {
856
1232
  collectAll(window.sophi_object);
857
1233
  }
@@ -870,13 +1246,62 @@ var SophiTracker = (function (exports) {
870
1246
  return;
871
1247
  setStorageConsentState(false);
872
1248
  clearSession();
1249
+ clearAttribution();
873
1250
  log('Storage consent withdrawn — Web Object is now passive.');
874
1251
  }
875
1252
  },
1253
+ /**
1254
+ * Record a click on a Sophi entry point (a button or link that opens Sophi).
1255
+ * Sent as a `custom` event with the entry under `page.custom._sophi.entry`.
1256
+ *
1257
+ * Use this for flows where no element tagged with `data-sophi-placement` is
1258
+ * clicked (e.g. a search submitted with Enter). Do not combine it with the
1259
+ * data attributes on the same button, or the click is counted twice.
1260
+ *
1261
+ * @example
1262
+ * SophiTracker.trackEntry({ placement: 'header_search', group: 'search', type: 'search_bar' })
1263
+ */
1264
+ trackEntry(entry) {
1265
+ if (getState() === TrackerState.FAILED) {
1266
+ warn('SophiTracker.trackEntry() called after bootstrap failure — ignoring.');
1267
+ return;
1268
+ }
1269
+ try {
1270
+ getConfig();
1271
+ }
1272
+ catch (_a) {
1273
+ warn('SophiTracker.trackEntry() called before initialisation — ignoring.');
1274
+ return;
1275
+ }
1276
+ if (!hasStorageConsent()) {
1277
+ log('trackEntry ignored — no storage consent.');
1278
+ return;
1279
+ }
1280
+ collectEntry(entry, window.sophi_object);
1281
+ },
876
1282
  /** Expose session info for debugging */
877
1283
  getSession,
878
1284
  };
879
1285
  // ─── Private helpers ──────────────────────────────────────────────────────────
1286
+ /**
1287
+ * Removing the last item leaves an empty basket. The external-events contract
1288
+ * rejects an empty `basket.line_items` and represents an empty basket by
1289
+ * omitting `basket`, so `remove_from_cart` is sent by its product without the
1290
+ * basket. Applies only to `remove_from_cart` with a product: anywhere else an
1291
+ * empty basket is an integration error and still skips with a warning.
1292
+ * Only the event changes — `sophi_object` keeps what the integrator pushed.
1293
+ */
1294
+ function omitEmptyBasketOnRemove(partial) {
1295
+ var _a;
1296
+ if (partial.event_type !== 'remove_from_cart' || !partial.product)
1297
+ return partial;
1298
+ const lineItems = (_a = partial.basket) === null || _a === void 0 ? void 0 : _a.line_items;
1299
+ if (!Array.isArray(lineItems) || lineItems.length > 0)
1300
+ return partial;
1301
+ log('remove_from_cart: basket is empty — sending the event without basket.');
1302
+ const { basket: _emptyBasket } = partial, rest = __rest(partial, ["basket"]);
1303
+ return rest;
1304
+ }
880
1305
  function resolveExplicitTriggeredKey(partial) {
881
1306
  var _a;
882
1307
  // Prefer specific commerce objects over page when multiple keys are present.
@@ -925,6 +1350,12 @@ var SophiTracker = (function (exports) {
925
1350
  // no session, no cookies, no events — until SophiTracker.setConsent(true).
926
1351
  const consentGranted = getConfig().storageConsent !== false;
927
1352
  setStorageConsentState(consentGranted);
1353
+ // Opt-in campaign attribution (no-op unless config.attribution is true).
1354
+ // Held in memory without consent; persisted only with consent.
1355
+ captureAttribution();
1356
+ // Sophi button clicks on elements tagged with data-sophi-placement. Installed
1357
+ // in passive mode too; trackEntry() ignores clicks until consent is granted.
1358
+ registerEntryClickListener();
928
1359
  if (!consentGranted) {
929
1360
  log('Initialised in anonymous mode — no session, cookies, or events until consent is granted.');
930
1361
  // Keep the object reactive so its state is current when consent arrives.
@@ -971,6 +1402,64 @@ var SophiTracker = (function (exports) {
971
1402
  }
972
1403
  });
973
1404
  }
1405
+ /**
1406
+ * One capture-phase click listener on window. Capture runs before the page's
1407
+ * own handlers, so a `stopPropagation()` in an integrator's onclick cannot
1408
+ * hide the click. The innermost tagged element wins, so a chip nested inside a
1409
+ * tagged banner is counted once, as the chip. Never stops or cancels the click.
1410
+ */
1411
+ function registerEntryClickListener() {
1412
+ if (entryClickListenerRegistered)
1413
+ return;
1414
+ entryClickListenerRegistered = true;
1415
+ window.addEventListener('click', handleEntryClick, true);
1416
+ }
1417
+ function handleEntryClick(event) {
1418
+ try {
1419
+ const entry = readEntryFromEvent(event);
1420
+ if (entry)
1421
+ SophiTracker.trackEntry(entry);
1422
+ }
1423
+ catch (err) {
1424
+ warn('Entry click tracking failed', err);
1425
+ }
1426
+ }
1427
+ /**
1428
+ * Finds the innermost element with `data-sophi-placement` on the event path
1429
+ * (composedPath also crosses open shadow roots) and reads `data-sophi-group`
1430
+ * and `data-sophi-type` from it or its nearest ancestor on the path.
1431
+ */
1432
+ function readEntryFromEvent(event) {
1433
+ var _a;
1434
+ const path = [];
1435
+ if (typeof event.composedPath === 'function') {
1436
+ for (const node of event.composedPath()) {
1437
+ if (node instanceof Element)
1438
+ path.push(node);
1439
+ }
1440
+ }
1441
+ else {
1442
+ let node = event.target instanceof Element ? event.target : null;
1443
+ while (node) {
1444
+ path.push(node);
1445
+ node = node.parentElement;
1446
+ }
1447
+ }
1448
+ const index = path.findIndex((el) => el.hasAttribute('data-sophi-placement'));
1449
+ if (index === -1)
1450
+ return null;
1451
+ const inherited = (name) => { var _a, _b; return (_b = (_a = path.slice(index).find((el) => el.hasAttribute(name))) === null || _a === void 0 ? void 0 : _a.getAttribute(name)) !== null && _b !== void 0 ? _b : undefined; };
1452
+ const entry = {
1453
+ placement: (_a = path[index].getAttribute('data-sophi-placement')) !== null && _a !== void 0 ? _a : '',
1454
+ };
1455
+ const group = inherited('data-sophi-group');
1456
+ const type = inherited('data-sophi-type');
1457
+ if (group !== undefined)
1458
+ entry.group = group;
1459
+ if (type !== undefined)
1460
+ entry.type = type;
1461
+ return entry;
1462
+ }
974
1463
  // ─── Stub adoption ────────────────────────────────────────────────────────────
975
1464
  /**
976
1465
  * Inspect the existing window.SophiTracker value before replacing it.
@@ -1020,20 +1509,6 @@ var SophiTracker = (function (exports) {
1020
1509
  else {
1021
1510
  void bootstrap();
1022
1511
  }
1023
- /** Reset the bootstrap guard between tests. */
1024
- function _resetBootstrapGuard() {
1025
- bootstrapGuard = false;
1026
- unloadFlushRegistered = false;
1027
- }
1028
-
1029
- exports._bootstrap = bootstrap;
1030
- exports._resetBootstrapGuard = _resetBootstrapGuard;
1031
- exports.default = SophiTracker;
1032
- exports.resetTrackerState = resetTrackerState;
1033
-
1034
- Object.defineProperty(exports, '__esModule', { value: true });
1035
-
1036
- return exports;
1037
1512
 
1038
- })({});
1513
+ })();
1039
1514
  //# sourceMappingURL=sophi.js.map