@bidspark/analytics 0.44.0 → 0.45.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/index.mjs CHANGED
@@ -1035,6 +1035,33 @@ function isVisitorSampled(visitorKey, sampleRate) {
1035
1035
  }
1036
1036
  return (hash >>> 0) / 4294967296 < rate;
1037
1037
  }
1038
+ var AUTOMATED_UA_RE = /headless|phantomjs|slimerjs|puppeteer|playwright/i;
1039
+ var DESKTOP_CHROME_UA_RE = /Chrome\/\d+/i;
1040
+ var NON_DESKTOP_CHROME_UA_RE = /Mobile|Android|iPhone|iPad|iPod|CriOS|FxiOS|Edg\/|OPR\/|SamsungBrowser/i;
1041
+ function isAutomatedClient() {
1042
+ const g = typeof globalThis !== "undefined" ? globalThis : void 0;
1043
+ const nav = g && "navigator" in g ? g.navigator : void 0;
1044
+ if (!nav) return false;
1045
+ if (nav.webdriver === true) return true;
1046
+ const ua = typeof nav.userAgent === "string" ? nav.userAgent : "";
1047
+ if (AUTOMATED_UA_RE.test(ua)) return true;
1048
+ const win = g && "window" in g ? g.window : g;
1049
+ let weakSignals = 0;
1050
+ if (win && typeof win.outerWidth === "number" && typeof win.outerHeight === "number" && win.outerWidth === 0 && win.outerHeight === 0) {
1051
+ weakSignals++;
1052
+ }
1053
+ if (Array.isArray(nav.languages) && nav.languages.length === 0) {
1054
+ weakSignals++;
1055
+ }
1056
+ if (DESKTOP_CHROME_UA_RE.test(ua) && !NON_DESKTOP_CHROME_UA_RE.test(ua)) {
1057
+ if (win && !win.chrome) weakSignals++;
1058
+ const plugins = nav.plugins;
1059
+ if (plugins !== void 0 && plugins !== null && plugins.length === 0) {
1060
+ weakSignals++;
1061
+ }
1062
+ }
1063
+ return weakSignals >= 2;
1064
+ }
1038
1065
 
1039
1066
  // ../../protogen/usage_event.ts
1040
1067
  var usage_event_exports = {};
@@ -1201,7 +1228,7 @@ function sendEvents(opts) {
1201
1228
  bidderOutcomes: []
1202
1229
  }));
1203
1230
  const nav = g && "navigator" in g ? g.navigator : void 0;
1204
- const automated = Boolean(nav && nav.webdriver === true);
1231
+ const automated = isAutomatedClient();
1205
1232
  const batch = {
1206
1233
  propertyId: idToBytes(opts.propertyId),
1207
1234
  pageviewId: idToBytes(pageviewId),
@@ -1505,6 +1532,15 @@ function sameEndpointOrigin(a, b) {
1505
1532
  return false;
1506
1533
  }
1507
1534
  }
1535
+ function normalizePageUrl(raw) {
1536
+ if (!raw) return "";
1537
+ try {
1538
+ const u = new URL(raw);
1539
+ return u.origin + u.pathname;
1540
+ } catch {
1541
+ return raw;
1542
+ }
1543
+ }
1508
1544
  var SESSION_PERSIST_INTERVAL_MS = 60 * 1e3;
1509
1545
  var persistedSessionTs = 0;
1510
1546
  var ACTIVITY_EVENTS = ["pointerdown", "pointermove", "keydown", "scroll", "wheel", "touchstart"];
@@ -1614,7 +1650,7 @@ function getOrCreateUserId() {
1614
1650
  if (storageAllowed && typeof localStorage !== "undefined") {
1615
1651
  const stored = localStorage.getItem(USER_ID_KEY);
1616
1652
  if (stored) return stored;
1617
- const newId = generateUUID2();
1653
+ const newId = inMemorySessionId || generateUUID2();
1618
1654
  localStorage.setItem(USER_ID_KEY, newId);
1619
1655
  return newId;
1620
1656
  }
@@ -1648,6 +1684,16 @@ function tcDataToConsentRecord(tcData) {
1648
1684
  purposesConsented: purposes
1649
1685
  };
1650
1686
  }
1687
+ function resolveTcfStorageAllowed(tcData, success) {
1688
+ if (!success || !tcData) return void 0;
1689
+ if (tcData.eventStatus === "cmpuishown" && !tcData.tcString) return false;
1690
+ const allowed = storageAllowedBy(tcDataToConsentRecord(tcData));
1691
+ if (!allowed) {
1692
+ clearStoredSession();
1693
+ clearStoredUserId();
1694
+ }
1695
+ return allowed;
1696
+ }
1651
1697
  function probeTcfStorageAllowed() {
1652
1698
  if (typeof window === "undefined") return void 0;
1653
1699
  const win = window;
@@ -1655,27 +1701,22 @@ function probeTcfStorageAllowed() {
1655
1701
  let allowed = void 0;
1656
1702
  try {
1657
1703
  win.__tcfapi("getTCData", 2, (tcData, success) => {
1658
- if (success && tcData) {
1659
- allowed = storageAllowedBy(tcDataToConsentRecord(tcData));
1660
- }
1704
+ allowed = resolveTcfStorageAllowed(tcData, success);
1661
1705
  });
1662
1706
  } catch {
1663
1707
  }
1664
1708
  return allowed !== void 0 ? allowed : false;
1665
1709
  }
1666
- var tcfListenerAttached = false;
1667
- function resetTcfListener() {
1668
- tcfListenerAttached = false;
1669
- }
1710
+ var attachedTcfApi = null;
1670
1711
  function attachTcfListener() {
1671
- if (tcfListenerAttached || typeof window === "undefined") return;
1712
+ if (typeof window === "undefined") return;
1672
1713
  const win = window;
1673
- if (typeof win.__tcfapi !== "function") return;
1674
- tcfListenerAttached = true;
1714
+ if (typeof win.__tcfapi !== "function" || attachedTcfApi === win.__tcfapi) return;
1715
+ attachedTcfApi = win.__tcfapi;
1675
1716
  try {
1676
1717
  win.__tcfapi("addEventListener", 2, (tcData, success) => {
1677
- if (!success || !tcData) return;
1678
- BidsparkPrebidAnalytics.setStorageAllowed(storageAllowedBy(tcDataToConsentRecord(tcData)));
1718
+ const allowed = resolveTcfStorageAllowed(tcData, success);
1719
+ if (allowed !== void 0) BidsparkPrebidAnalytics.setStorageAllowed(allowed);
1679
1720
  });
1680
1721
  } catch {
1681
1722
  }
@@ -1766,19 +1807,31 @@ var PrebidEventDeduper = class {
1766
1807
  }
1767
1808
  };
1768
1809
  function parseBidDimensions(bid) {
1769
- if (Number.isFinite(bid?.width) && Number.isFinite(bid?.height)) {
1810
+ if (Number.isFinite(bid?.width) && bid.width > 0 && Number.isFinite(bid?.height) && bid.height > 0) {
1770
1811
  return { width: bid.width, height: bid.height };
1771
1812
  }
1813
+ if (Number.isFinite(bid?.w) && bid.w > 0 && Number.isFinite(bid?.h) && bid.h > 0) {
1814
+ return { width: bid.w, height: bid.h };
1815
+ }
1816
+ if (Number.isFinite(bid?.playerWidth) && bid.playerWidth > 0 && Number.isFinite(bid?.playerHeight) && bid.playerHeight > 0) {
1817
+ return { width: bid.playerWidth, height: bid.playerHeight };
1818
+ }
1819
+ const ps = bid?.mediaTypes?.video?.playerSize;
1820
+ if (Array.isArray(ps) && ps.length > 0) {
1821
+ const tuple = Array.isArray(ps[0]) ? ps[0] : ps;
1822
+ if (Number.isFinite(tuple[0]) && tuple[0] > 0 && Number.isFinite(tuple[1]) && tuple[1] > 0) {
1823
+ return { width: tuple[0], height: tuple[1] };
1824
+ }
1825
+ }
1772
1826
  if (typeof bid?.size === "string") {
1773
1827
  const match = bid.size.match(/^(\d+)x(\d+)$/);
1774
1828
  if (match) {
1775
1829
  return { width: Number(match[1]), height: Number(match[2]) };
1776
1830
  }
1777
1831
  }
1778
- return {
1779
- width: Number.isFinite(bid?.width) ? bid.width : 0,
1780
- height: Number.isFinite(bid?.height) ? bid.height : 0
1781
- };
1832
+ const w = Number.isFinite(bid?.width) ? bid.width : Number.isFinite(bid?.w) ? bid.w : Number.isFinite(bid?.playerWidth) ? bid.playerWidth : 0;
1833
+ const h = Number.isFinite(bid?.height) ? bid.height : Number.isFinite(bid?.h) ? bid.h : Number.isFinite(bid?.playerHeight) ? bid.playerHeight : 0;
1834
+ return { width: w, height: h };
1782
1835
  }
1783
1836
  function resolveBidPricing(bid, fallback) {
1784
1837
  if (Number.isFinite(bid?.cpm)) {
@@ -1823,14 +1876,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1823
1876
  storageAllowed = allowed;
1824
1877
  persistedSessionTs = 0;
1825
1878
  for (const inst of _BidsparkPrebidAnalytics.allInstances) {
1826
- inst.config.storageAllowed = allowed;
1827
- if (!allowed) {
1828
- inst.config.userId = "";
1829
- inst.config.visitorId = inst.config.visitorId || inst.config.pageviewId;
1830
- } else if (!inst.config.userId) {
1831
- inst.config.userId = getOrCreateUserId();
1832
- inst.config.visitorId = inst.config.visitorId || inst.config.userId || inst.config.pageviewId;
1833
- }
1879
+ inst.applyStorageAllowed(allowed);
1834
1880
  }
1835
1881
  }
1836
1882
  static isStorageAllowed() {
@@ -1881,6 +1927,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1881
1927
  logger;
1882
1928
  // True when managing session lifecycle internally; false if caller supplied fixed sessionId.
1883
1929
  managesSessionId;
1930
+ configuredUserId;
1931
+ // True when visitor sampling key is derived internally from storage/session rather than caller config.
1932
+ managesVisitorId;
1933
+ // True once visitorId is settled (storage read, caller-supplied, or first batch drained).
1934
+ visitorKeyLocked;
1884
1935
  constructor(config) {
1885
1936
  const tcfStorage = probeTcfStorageAllowed();
1886
1937
  if (typeof window !== "undefined" && typeof window.__tcfapi === "function") {
@@ -1894,32 +1945,33 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1894
1945
  const requestedEndpoint = config.endpoint || "";
1895
1946
  const endpoint = !requestedEndpoint || isTrustedEndpoint(requestedEndpoint) ? requestedEndpoint : "";
1896
1947
  const pageviewId = config.pageviewId || generateUUID2();
1948
+ recordActivity();
1949
+ this.managesSessionId = !config.sessionId;
1950
+ const sessionId = config.sessionId || getOrCreateSessionId();
1951
+ this.configuredUserId = config.userId || "";
1897
1952
  let initialUserId = "";
1898
- let initialVisitorId = "";
1899
1953
  if (isStorageOn) {
1900
- initialUserId = config.userId || getOrCreateUserId();
1901
- if (config.userId) {
1954
+ initialUserId = this.configuredUserId || getOrCreateUserId();
1955
+ if (this.configuredUserId) {
1902
1956
  try {
1903
1957
  if (typeof localStorage !== "undefined") {
1904
- localStorage.setItem(USER_ID_KEY, config.userId);
1958
+ localStorage.setItem(USER_ID_KEY, this.configuredUserId);
1905
1959
  }
1906
1960
  } catch {
1907
1961
  }
1908
1962
  }
1909
- initialVisitorId = config.visitorId || initialUserId || pageviewId;
1910
- } else {
1911
- initialUserId = "";
1912
- initialVisitorId = config.visitorId || pageviewId;
1913
1963
  }
1964
+ this.managesVisitorId = !config.visitorId && !config.userId && !config.sessionId;
1965
+ this.visitorKeyLocked = isStorageOn || !this.managesVisitorId;
1914
1966
  const usageEndpoint = config.usageEndpoint || "";
1915
1967
  this.config = {
1916
1968
  endpoint,
1917
1969
  usageEndpoint,
1918
1970
  propertyId: config.propertyId || "",
1919
1971
  pageviewId,
1920
- sessionId: config.sessionId || "",
1972
+ sessionId,
1921
1973
  userId: initialUserId,
1922
- visitorId: initialVisitorId,
1974
+ visitorId: config.visitorId || this.configuredUserId || initialUserId || sessionId,
1923
1975
  deviceType: config.deviceType || "desktop",
1924
1976
  country: config.country || "",
1925
1977
  region: config.region || "",
@@ -1939,9 +1991,6 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1939
1991
  prefix: "[analytics]",
1940
1992
  logLevel: this.config.logLevel
1941
1993
  });
1942
- recordActivity();
1943
- this.managesSessionId = !config.sessionId;
1944
- if (this.managesSessionId) this.config.sessionId = getOrCreateSessionId();
1945
1994
  if (requestedEndpoint && !endpoint) {
1946
1995
  this.log(
1947
1996
  "ERROR",
@@ -1954,6 +2003,31 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1954
2003
  };
1955
2004
  this.boundVisibilityChange = () => this.handleVisibilityChange();
1956
2005
  }
2006
+ applyStorageAllowed(allowed) {
2007
+ this.config.storageAllowed = allowed;
2008
+ if (!allowed) {
2009
+ this.config.userId = "";
2010
+ return;
2011
+ }
2012
+ this.syncSessionId();
2013
+ if (!this.config.userId) {
2014
+ this.config.userId = this.configuredUserId || getOrCreateUserId();
2015
+ }
2016
+ if (this.managesVisitorId && !this.visitorKeyLocked) {
2017
+ this.config.visitorId = this.config.userId || this.config.sessionId;
2018
+ this.visitorKeyLocked = true;
2019
+ if (!this.isSampledVisitor()) {
2020
+ this.queue = [];
2021
+ if (this.revenueFlushTimer) {
2022
+ clearTimeout(this.revenueFlushTimer);
2023
+ this.revenueFlushTimer = null;
2024
+ }
2025
+ }
2026
+ }
2027
+ if (this.isEnabled) {
2028
+ this.resendPersistedBatches();
2029
+ }
2030
+ }
1957
2031
  setLogLevel(level) {
1958
2032
  const norm = normalizeLogLevel(level);
1959
2033
  this.config.logLevel = norm;
@@ -1967,6 +2041,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1967
2041
  if (this.isEnabled) return;
1968
2042
  this.isEnabled = true;
1969
2043
  _BidsparkPrebidAnalytics.activeInstances.add(this);
2044
+ _BidsparkPrebidAnalytics.allInstances.add(this);
1970
2045
  this.logger.setLevel(this.config.logLevel);
1971
2046
  if (this.config.attachPbjsListeners && this.config.usageEndpoint && !this.usageRecorder) {
1972
2047
  this.usageRecorder = new UsageRecorder({
@@ -1996,12 +2071,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1996
2071
  this.cmpDetach = this.attachCmp();
1997
2072
  if (typeof window !== "undefined") {
1998
2073
  if (!this.pageUrl) {
1999
- try {
2000
- const u = new URL(window.location.href);
2001
- this.pageUrl = u.origin + u.pathname;
2002
- } catch {
2003
- this.pageUrl = window.location.href;
2004
- }
2074
+ this.pageUrl = normalizePageUrl(window.location.href);
2005
2075
  }
2006
2076
  window.addEventListener("pagehide", this.boundFlushBeacon);
2007
2077
  if (typeof document !== "undefined") {
@@ -2619,7 +2689,15 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2619
2689
  hasImpressionEmitted(slotId, refreshIndex, auctionId, creativeId, adId) {
2620
2690
  const rIndex = refreshIndex ?? this.slotRefreshIndices.get(slotId) ?? 0;
2621
2691
  const baseSlotKey = `${escapeKeyPart(slotId)}:${rIndex}`;
2692
+ if (auctionId ? this.slotEmittedImpressionKeys.has(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`) : this.slotEmittedImpressionKeys.has(baseSlotKey)) {
2693
+ return true;
2694
+ }
2622
2695
  if (adId) {
2696
+ if (auctionId && this.slotEmittedImpressionKeys.has(
2697
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:render`
2698
+ ) || this.slotEmittedImpressionKeys.has(`${baseSlotKey}:render`)) {
2699
+ return true;
2700
+ }
2623
2701
  if (auctionId) {
2624
2702
  if (this.slotEmittedImpressionKeys.has(
2625
2703
  `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad:${escapeKeyPart(adId)}`
@@ -2642,6 +2720,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2642
2720
  }
2643
2721
  return false;
2644
2722
  }
2723
+ if (auctionId && this.slotEmittedImpressionKeys.has(
2724
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad-emitted`
2725
+ ) || this.slotEmittedImpressionKeys.has(`${baseSlotKey}:ad-emitted`)) {
2726
+ return true;
2727
+ }
2645
2728
  if (creativeId) {
2646
2729
  if (auctionId) {
2647
2730
  return this.slotEmittedImpressionKeys.has(
@@ -2650,10 +2733,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2650
2733
  }
2651
2734
  return this.slotEmittedImpressionKeys.has(`${baseSlotKey}:${escapeKeyPart(creativeId)}`);
2652
2735
  }
2653
- if (auctionId) {
2654
- return this.slotEmittedImpressionKeys.has(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2736
+ if (auctionId && this.slotEmittedImpressionKeys.has(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:any`)) {
2737
+ return true;
2655
2738
  }
2656
- return this.slotEmittedImpressionKeys.has(baseSlotKey);
2739
+ return false;
2657
2740
  }
2658
2741
  markImpressionEmitted(slotId, refreshIndex, auctionId, creativeId, adId) {
2659
2742
  const baseSlotKey = `${escapeKeyPart(slotId)}:${refreshIndex}`;
@@ -2661,10 +2744,13 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2661
2744
  if (hasIdentity) {
2662
2745
  if (adId) {
2663
2746
  this.addImpressionKey(`${baseSlotKey}:ad:${escapeKeyPart(adId)}`);
2747
+ this.addImpressionKey(`${baseSlotKey}:ad-emitted`);
2664
2748
  if (auctionId) {
2665
2749
  this.addImpressionKey(
2666
2750
  `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad:${escapeKeyPart(adId)}`
2667
2751
  );
2752
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:any`);
2753
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad-emitted`);
2668
2754
  }
2669
2755
  }
2670
2756
  if (creativeId && creativeId !== adId) {
@@ -2673,15 +2759,21 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2673
2759
  this.addImpressionKey(
2674
2760
  `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:${escapeKeyPart(creativeId)}`
2675
2761
  );
2762
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:any`);
2676
2763
  }
2677
2764
  }
2678
- if (auctionId) {
2679
- this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2765
+ if (!adId) {
2766
+ this.addImpressionKey(`${baseSlotKey}:render`);
2767
+ if (auctionId) {
2768
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:render`);
2769
+ }
2680
2770
  }
2681
2771
  } else {
2682
2772
  this.addImpressionKey(baseSlotKey);
2773
+ this.addImpressionKey(`${baseSlotKey}:render`);
2683
2774
  if (auctionId) {
2684
2775
  this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2776
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:render`);
2685
2777
  }
2686
2778
  }
2687
2779
  }
@@ -2708,8 +2800,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2708
2800
  ...parseBidDimensions(rawBid).width ? parseBidDimensions(rawBid) : cached?.bidTrace ? { width: cached.bidTrace.width, height: cached.bidTrace.height } : parseBidDimensions(rawBid),
2709
2801
  dealId: rawBid.dealId || cached?.bidTrace?.dealId || "",
2710
2802
  mediaType,
2711
- latencyMs: Number.isFinite(rawBid.timeToRespond) ? rawBid.timeToRespond : cached?.bidTrace?.latencyMs ?? 0,
2712
- advertiserDomain: rawBid.meta?.advertiserDomains?.[0] || cached?.bidTrace?.advertiserDomain || "",
2803
+ latencyMs: Number.isFinite(rawBid.timeToRespond) ? rawBid.timeToRespond : Number.isFinite(rawBid.latencyMs) ? rawBid.latencyMs : cached?.bidTrace?.latencyMs ?? 0,
2804
+ advertiserDomain: rawBid.advertiserDomain || rawBid.meta?.advertiserDomains?.[0] || (Array.isArray(rawBid.adomain) ? rawBid.adomain[0] : "") || cached?.bidTrace?.advertiserDomain || "",
2713
2805
  creativeId: rawBid.creativeId || cached?.bidTrace?.creativeId || ""
2714
2806
  };
2715
2807
  if (isDifferentAuction && targetSlot) {
@@ -2880,16 +2972,16 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2880
2972
  const handler = (evt) => {
2881
2973
  const detail = evt.detail;
2882
2974
  if (detail) {
2883
- this.recordConsent(detail);
2884
2975
  this.followConsent(detail);
2976
+ this.recordConsent(detail);
2885
2977
  }
2886
2978
  };
2887
2979
  document.addEventListener("ads:consent", handler);
2888
2980
  const win = typeof window !== "undefined" ? window : {};
2889
2981
  const existingRecord = win[this.config.alias]?.consent?.getRecord?.() || null;
2890
2982
  if (existingRecord) {
2891
- this.recordConsent(existingRecord);
2892
2983
  this.followConsent(existingRecord);
2984
+ this.recordConsent(existingRecord);
2893
2985
  }
2894
2986
  let detached = false;
2895
2987
  return () => {
@@ -2898,15 +2990,23 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2898
2990
  document.removeEventListener("ads:consent", handler);
2899
2991
  };
2900
2992
  }
2901
- /** Device storage follows the decision; a refusal also drops the stored session. */
2993
+ /** Device storage follows the decision; a refusal also drops stored session and user IDs. */
2902
2994
  followConsent(record) {
2903
2995
  const allowed = storageAllowedBy(record);
2904
- if (!allowed) clearStoredSession();
2996
+ if (!allowed) {
2997
+ clearStoredSession();
2998
+ clearStoredUserId();
2999
+ }
2905
3000
  _BidsparkPrebidAnalytics.setStorageAllowed(allowed);
2906
3001
  }
2907
3002
  setUserId(userId) {
3003
+ this.configuredUserId = userId;
2908
3004
  this.config.userId = userId;
2909
- if (userId) this.config.visitorId = userId;
3005
+ if (userId) {
3006
+ this.config.visitorId = userId;
3007
+ this.managesVisitorId = false;
3008
+ this.visitorKeyLocked = true;
3009
+ }
2910
3010
  if (this.config.storageAllowed && typeof localStorage !== "undefined") {
2911
3011
  try {
2912
3012
  if (userId) {
@@ -2920,6 +3020,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2920
3020
  }
2921
3021
  setVisitorId(visitorId) {
2922
3022
  this.config.visitorId = visitorId;
3023
+ this.managesVisitorId = !visitorId;
3024
+ if (visitorId) this.visitorKeyLocked = true;
2923
3025
  }
2924
3026
  setSampleRate(sampleRate) {
2925
3027
  this.config.sampleRate = normalizeSampleRate(sampleRate);
@@ -2929,7 +3031,32 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2929
3031
  this.managesSessionId = !sessionId;
2930
3032
  if (this.managesSessionId) this.config.sessionId = getOrCreateSessionId();
2931
3033
  }
2932
- navigate(pageviewId, pageUrl) {
3034
+ getSessionId() {
3035
+ this.syncSessionId();
3036
+ return this.config.sessionId;
3037
+ }
3038
+ getPageviewId() {
3039
+ return this.config.pageviewId;
3040
+ }
3041
+ getContext() {
3042
+ return { pageviewId: this.getPageviewId(), sessionId: this.getSessionId() };
3043
+ }
3044
+ /**
3045
+ * Continues the pageview of the instance this one replaces: re-registering on
3046
+ * the same page must not count a second pageview or replay Prebid's history.
3047
+ */
3048
+ continuePageview(previous) {
3049
+ this.config.pageviewId = previous.config.pageviewId;
3050
+ this.pageviewEmitted = previous.pageviewEmitted;
3051
+ this.deduper = previous.deduper;
3052
+ this.replayedEventCount = previous.replayedEventCount;
3053
+ }
3054
+ navigate(pageviewId, pageUrl = "") {
3055
+ const nextPageUrl = normalizePageUrl(pageUrl);
3056
+ if (this.isEnabled && this.pageviewEmitted && pageviewId !== "" && pageviewId === this.config.pageviewId && (!nextPageUrl || nextPageUrl === this.pageUrl)) {
3057
+ recordActivity();
3058
+ return;
3059
+ }
2933
3060
  this.disable();
2934
3061
  this.slotRefreshIndices.clear();
2935
3062
  this.slotNames.clear();
@@ -2939,26 +3066,22 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2939
3066
  this.consentCount = 0;
2940
3067
  this.pageviewEmitted = false;
2941
3068
  this.config.pageviewId = pageviewId || generateUUID2();
2942
- this.config.visitorId = this.config.userId || this.config.pageviewId;
2943
- if (pageUrl) {
2944
- try {
2945
- const u = new URL(pageUrl);
2946
- this.pageUrl = u.origin + u.pathname;
2947
- } catch {
2948
- this.pageUrl = pageUrl;
2949
- }
2950
- } else {
2951
- this.pageUrl = "";
2952
- }
3069
+ this.pageUrl = nextPageUrl;
2953
3070
  this.logger.resetTiming();
3071
+ const prevSessionId = this.config.sessionId;
2954
3072
  recordActivity();
3073
+ this.syncSessionId();
3074
+ if (!this.config.visitorId || this.config.sessionId !== prevSessionId && this.config.visitorId === prevSessionId) {
3075
+ this.config.visitorId = this.config.userId || this.config.sessionId;
3076
+ }
2955
3077
  this.enable();
2956
3078
  }
2957
- recordAuctionStart(auctionId, adUnitCode = "", bidderCount) {
3079
+ recordAuctionStart(auctionId, adUnitCode = "", bidderCount, mediaType) {
2958
3080
  if (!this.isEnabled || !this.config.auctionEnabled) return;
2959
3081
  this.enqueue(TraceEventType.AUCTION_START, "auctionStart", {
2960
3082
  auctionId,
2961
3083
  adUnitCode,
3084
+ ...mediaType ? { bid: { mediaType } } : {},
2962
3085
  ...typeof bidderCount === "number" ? { metadata: { bidderCount: String(bidderCount) } } : {}
2963
3086
  });
2964
3087
  }
@@ -3018,7 +3141,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3018
3141
  data.bids.forEach((bid) => {
3019
3142
  const adUnitCode = bid.adUnitCode || "";
3020
3143
  const mediaTypes = Object.keys(bid.mediaTypes || {});
3021
- const mediaType = mediaTypes.length > 0 ? mediaTypes[0] : bid.mediaType || "banner";
3144
+ const mediaType = bid.mediaType || (bid.mediaTypes?.video ? "video" : mediaTypes.length > 0 ? mediaTypes[0] : "banner");
3022
3145
  const key = `${bidder}:${adUnitCode}`;
3023
3146
  if (!auctionMap.has(key)) {
3024
3147
  auctionMap.set(key, {
@@ -3220,35 +3343,28 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3220
3343
  }
3221
3344
  }
3222
3345
  const currentRefreshIndex = adUnitCode ? this.slotRefreshIndices.get(adUnitCode) ?? (record ? record.refreshIndex : 0) : 0;
3223
- if (!isVideo) {
3224
- const alreadyEmitted = adUnitCode ? this.hasImpressionEmitted(
3225
- adUnitCode,
3226
- currentRefreshIndex,
3227
- resolvedAuctionId,
3228
- bidTrace.creativeId
3229
- ) : false;
3230
- if (!alreadyEmitted) {
3231
- if (adUnitCode) {
3232
- this.markImpressionEmitted(
3233
- adUnitCode,
3234
- currentRefreshIndex,
3235
- resolvedAuctionId,
3236
- bidTrace.creativeId
3237
- );
3238
- }
3239
- this.enqueue(TraceEventType.IMPRESSION, "impression", {
3240
- auctionId: resolvedAuctionId,
3241
- transactionId: resolvedTransactionId,
3346
+ const alreadyEmitted = adUnitCode ? this.hasImpressionEmitted(
3347
+ adUnitCode,
3348
+ currentRefreshIndex,
3349
+ resolvedAuctionId,
3350
+ bidTrace.creativeId
3351
+ ) : false;
3352
+ if (!alreadyEmitted) {
3353
+ if (adUnitCode) {
3354
+ this.markImpressionEmitted(
3242
3355
  adUnitCode,
3243
- bid: bidTrace,
3244
- metadata: { refresh_index: String(currentRefreshIndex) }
3245
- });
3356
+ currentRefreshIndex,
3357
+ resolvedAuctionId,
3358
+ bidTrace.creativeId
3359
+ );
3246
3360
  }
3247
- } else {
3248
- this.log(
3249
- "DEBUG",
3250
- `adRenderSucceeded received for video ad unit ${adUnitCode || "unknown"}: suppressing IMPRESSION until verified video lifecycle event`
3251
- );
3361
+ this.enqueue(TraceEventType.IMPRESSION, "impression", {
3362
+ auctionId: resolvedAuctionId,
3363
+ transactionId: resolvedTransactionId,
3364
+ adUnitCode,
3365
+ bid: bidTrace,
3366
+ metadata: { refresh_index: String(currentRefreshIndex) }
3367
+ });
3252
3368
  }
3253
3369
  if (this.config.viewabilityEnabled && typeof document !== "undefined") {
3254
3370
  let el = adUnitCode && this.slotElements.get(adUnitCode) || null;
@@ -3302,9 +3418,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3302
3418
  enqueue(type, eventName, data) {
3303
3419
  if (!this.isEnabled) return;
3304
3420
  if (!this.shouldSample(type)) return;
3305
- if (this.managesSessionId && sessionNeedsSync()) {
3306
- this.config.sessionId = getOrCreateSessionId();
3307
- }
3421
+ this.syncSessionId();
3308
3422
  const protoEvent = {
3309
3423
  eventId: idToBytes(generateUUID2()),
3310
3424
  timestampMs: Date.now(),
@@ -3318,19 +3432,20 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3318
3432
  namespace: data.ns || data.namespace || ""
3319
3433
  };
3320
3434
  if (data.bid) {
3435
+ const dims = parseBidDimensions(data.bid);
3321
3436
  protoEvent.bid = {
3322
- bidder: data.bid.bidder || "",
3437
+ bidder: data.bid.bidder || data.bid.bidderCode || "",
3323
3438
  cpm: Number.isFinite(data.bid.cpm) ? data.bid.cpm : 0,
3324
3439
  // No defaults here: handlers with a priced bid (bidWon, impression)
3325
3440
  // set currency/mediaType themselves. Defaulting for the rest would
3326
3441
  // stamp fake "USD"/"banner" on rows that carried no bid.
3327
3442
  currency: data.bid.currency || "",
3328
- width: Number.isFinite(data.bid.width) ? data.bid.width : 0,
3329
- height: Number.isFinite(data.bid.height) ? data.bid.height : 0,
3443
+ width: dims.width,
3444
+ height: dims.height,
3330
3445
  dealId: data.bid.dealId || "",
3331
3446
  mediaType: data.bid.mediaType || "",
3332
- latencyMs: Number.isFinite(data.bid.latencyMs) ? data.bid.latencyMs : 0,
3333
- advertiserDomain: data.bid.advertiserDomain || "",
3447
+ latencyMs: Number.isFinite(data.bid.latencyMs) ? data.bid.latencyMs : Number.isFinite(data.bid.timeToRespond) ? data.bid.timeToRespond : 0,
3448
+ advertiserDomain: data.bid.advertiserDomain || data.bid.meta?.advertiserDomains?.[0] || (Array.isArray(data.bid.adomain) ? data.bid.adomain[0] : "") || "",
3334
3449
  creativeId: data.bid.creativeId || ""
3335
3450
  };
3336
3451
  }
@@ -3395,12 +3510,19 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3395
3510
  }, this.config.revenueFlushDelayMs);
3396
3511
  }
3397
3512
  }
3513
+ // Follows the page's session, which consent or a lapse can move after this
3514
+ // instance took its ID. A settled session is read as is: only a pageview or
3515
+ // visitor input may start a new one, never a flush.
3516
+ syncSessionId() {
3517
+ if (!this.managesSessionId) return;
3518
+ this.config.sessionId = sessionNeedsSync() ? getOrCreateSessionId() : inMemorySessionId;
3519
+ }
3398
3520
  isSampledVisitor() {
3399
- const key = this.config.visitorId || this.config.userId || this.config.pageviewId;
3521
+ const key = this.config.visitorId || this.config.sessionId;
3400
3522
  return isVisitorSampled(key, this.config.sampleRate);
3401
3523
  }
3402
3524
  shouldSample(type) {
3403
- if (!this.isSampledVisitor()) {
3525
+ if (this.visitorKeyLocked && !this.isSampledVisitor()) {
3404
3526
  return false;
3405
3527
  }
3406
3528
  if (type === TraceEventType.ERROR) {
@@ -3427,9 +3549,15 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3427
3549
  // Shared by flush() and flushBeacon().
3428
3550
  drainBatch() {
3429
3551
  if (this.queue.length === 0 || !this.config.endpoint) return null;
3552
+ this.syncSessionId();
3553
+ this.visitorKeyLocked = true;
3554
+ if (!this.isSampledVisitor()) {
3555
+ this.queue = [];
3556
+ return null;
3557
+ }
3430
3558
  const domain = typeof window !== "undefined" ? window.location.hostname : "";
3431
3559
  const sampleRate = normalizeSampleRate(this.config.sampleRate);
3432
- const automated = typeof navigator !== "undefined" && navigator.webdriver === true;
3560
+ const automated = isAutomatedClient();
3433
3561
  const buildBatch = (evts) => ({
3434
3562
  propertyId: idToBytes(this.config.propertyId),
3435
3563
  pageviewId: idToBytes(this.config.pageviewId),
@@ -3632,7 +3760,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3632
3760
  // event timestamps, so late rows attribute correctly.
3633
3761
  resendPersistedBatches() {
3634
3762
  try {
3635
- if (typeof localStorage === "undefined" || !this.config.endpoint) return;
3763
+ if (!storageAllowed || typeof localStorage === "undefined" || !this.config.endpoint) return;
3636
3764
  if (!this.config.propertyId) return;
3637
3765
  const ownPrefix = this.pendingKeyPrefix();
3638
3766
  const keys = [];
@@ -3750,6 +3878,7 @@ function registerPrebidAnalytics(pbjsGlobalName = "pbjs", defaults) {
3750
3878
  }
3751
3879
  }
3752
3880
  const analytics = new BidsparkPrebidAnalytics(merged);
3881
+ if (previous && !merged.pageviewId) analytics.continuePageview(previous);
3753
3882
  analytics.enable();
3754
3883
  win._bidsparkPrebidAnalytics = analytics;
3755
3884
  return analytics;
@@ -4190,8 +4319,8 @@ function attachImaAdsManager(analytics, adsManager, options) {
4190
4319
  }
4191
4320
  const slotId = options?.slotId || options?.adUnitCode || "video";
4192
4321
  const adUnitCode = options?.adUnitCode || slotId;
4193
- const auctionId = options?.auctionId || "";
4194
- const transactionId = options?.transactionId || "";
4322
+ const auctionId = options?.auctionId || options?.bid?.auctionId || "";
4323
+ const transactionId = options?.transactionId || options?.bid?.transactionId || "";
4195
4324
  const getWinningBid = (adData) => {
4196
4325
  let cached = (auctionId ? self.getCachedBid(`${auctionId}:${adUnitCode}`) : void 0) || (auctionId && slotId !== adUnitCode ? self.getCachedBid(`${auctionId}:${slotId}`) : void 0) || (adUnitCode !== "video" ? self.getCachedBid(adUnitCode) : void 0) || (slotId !== adUnitCode && slotId !== "video" ? self.getCachedBid(slotId) : void 0);
4197
4326
  if (!cached) {
@@ -4254,11 +4383,7 @@ function attachImaAdsManager(analytics, adsManager, options) {
4254
4383
  const resolvedTransactionId = transactionId || cached?.transactionId || "";
4255
4384
  const creativeId = session.creativeId || adData.creativeId || cached?.bidTrace?.creativeId || options?.bid?.creativeId || "";
4256
4385
  const stableAdIdentity = session.adId || adData.adId || creativeId || session.sessionId;
4257
- const mergedBid = {
4258
- ...cached?.rawBid || options?.bid,
4259
- mediaType: "video",
4260
- creativeId
4261
- };
4386
+ const mergedBid = resolveMergedBid(cached, creativeId);
4262
4387
  const emitted = self.recordImpression(resolvedSlotId, {
4263
4388
  adUnitCode: resolvedAdUnitCode,
4264
4389
  auctionId: resolvedAuctionId,
@@ -4291,6 +4416,19 @@ function attachImaAdsManager(analytics, adsManager, options) {
4291
4416
  }
4292
4417
  }
4293
4418
  };
4419
+ const resolveMergedBid = (cached, extraCreativeId) => {
4420
+ const rawDims = parseBidDimensions(cached?.rawBid);
4421
+ const optDims = parseBidDimensions(options?.bid);
4422
+ const creativeId = extraCreativeId || options?.bid?.creativeId || cached?.bidTrace?.creativeId || "";
4423
+ return {
4424
+ ...cached?.rawBid,
4425
+ ...options?.bid,
4426
+ ...options?.bid?.bidder || options?.bid?.bidderCode ? { bidderCode: options.bid.bidderCode || options.bid.bidder } : {},
4427
+ ...optDims.width > 0 && optDims.height > 0 ? optDims : rawDims,
4428
+ mediaType: "video",
4429
+ ...creativeId ? { creativeId } : {}
4430
+ };
4431
+ };
4294
4432
  const onMilestone = (milestone) => {
4295
4433
  self.log("DEBUG", `IMA AdEvent milestone: ${milestone}`);
4296
4434
  if (options?.onMilestone) {
@@ -4309,7 +4447,7 @@ function attachImaAdsManager(analytics, adsManager, options) {
4309
4447
  auctionId: auctionId || cached?.auctionId,
4310
4448
  transactionId: transactionId || cached?.transactionId,
4311
4449
  adUnitCode: resolvedAdUnitCode,
4312
- bid: cached?.bidTrace || options?.bid,
4450
+ bid: cached || options?.bid ? resolveMergedBid(cached) : void 0,
4313
4451
  metadata: {
4314
4452
  ...options?.metadata,
4315
4453
  media_type: "video"
@@ -4325,7 +4463,7 @@ function attachImaAdsManager(analytics, adsManager, options) {
4325
4463
  adUnitCode: resolvedAdUnitCode,
4326
4464
  auctionId: auctionId || cached?.auctionId,
4327
4465
  transactionId: transactionId || cached?.transactionId,
4328
- bid: cached?.bidTrace || options?.bid,
4466
+ bid: cached || options?.bid ? resolveMergedBid(cached) : void 0,
4329
4467
  metadata: options?.metadata
4330
4468
  });
4331
4469
  if (options?.onError) {
@@ -4737,6 +4875,24 @@ function getAdsGlobal(alias = DEFAULT_ALIAS) {
4737
4875
  const win = window;
4738
4876
  win[alias] = win[alias] || { q: [] };
4739
4877
  const sdk = win[alias];
4878
+ if (!sdk.getContext) {
4879
+ sdk.getContext = () => {
4880
+ const inst = win._bidsparkPrebidAnalytics;
4881
+ return inst?.getContext ? inst.getContext() : { pageviewId: inst?.getPageviewId?.() || "", sessionId: getOrCreateSessionId() };
4882
+ };
4883
+ }
4884
+ if (!sdk.getSessionId) {
4885
+ sdk.getSessionId = () => {
4886
+ const inst = win._bidsparkPrebidAnalytics;
4887
+ return inst?.getSessionId ? inst.getSessionId() : getOrCreateSessionId();
4888
+ };
4889
+ }
4890
+ if (!sdk.getPageviewId) {
4891
+ sdk.getPageviewId = () => {
4892
+ const inst = win._bidsparkPrebidAnalytics;
4893
+ return inst?.getPageviewId ? inst.getPageviewId() : "";
4894
+ };
4895
+ }
4740
4896
  if (!sdk.attachVideoPlayer) {
4741
4897
  sdk.attachVideoPlayer = (target, options) => {
4742
4898
  const inst = win._bidsparkPrebidAnalytics;
@@ -4782,14 +4938,15 @@ export {
4782
4938
  getPrebidEventKey,
4783
4939
  idToBytes,
4784
4940
  idToString,
4941
+ isAutomatedClient,
4785
4942
  isSessionActive,
4786
4943
  isTrustedEndpoint,
4787
4944
  isVisitorSampled,
4788
4945
  normalizeLogLevel,
4789
4946
  normalizeSampleRate,
4790
4947
  onSessionResume,
4948
+ parseBidDimensions,
4791
4949
  registerPrebidAnalytics,
4792
- resetTcfListener,
4793
4950
  sendEvents,
4794
4951
  sessionStarted
4795
4952
  };