@bidspark/analytics 0.46.0 → 0.46.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
@@ -27,18 +27,6 @@ var COLORS = {
27
27
  eventError: "color: #ef4444; font-weight: bold",
28
28
  reset: "color: inherit"
29
29
  };
30
- var logCounter = 0;
31
- var localGlobalListeners = /* @__PURE__ */ new Set();
32
- function getGlobalListeners() {
33
- if (typeof window !== "undefined") {
34
- const win = window;
35
- if (!win.__bidsparkLogListeners) {
36
- win.__bidsparkLogListeners = /* @__PURE__ */ new Set();
37
- }
38
- return win.__bidsparkLogListeners;
39
- }
40
- return localGlobalListeners;
41
- }
42
30
  function formatTime(ms) {
43
31
  if (ms < 0 || !Number.isFinite(ms)) ms = 0;
44
32
  if (ms < 1e3) return `${ms.toFixed(2)}ms`;
@@ -64,15 +52,11 @@ var Logger = class {
64
52
  _loadedAt;
65
53
  _now;
66
54
  _console;
67
- _listeners = /* @__PURE__ */ new Set();
68
55
  constructor(options = {}) {
69
56
  this._prefix = options.prefix ?? "[ads]";
70
57
  this._level = normalizeLogLevel(options.logLevel ?? LogLevel.INFO);
71
58
  this._now = options.now;
72
59
  this._console = options.console;
73
- if (options.onLog) {
74
- this._listeners.add(options.onLog);
75
- }
76
60
  this._loadedAt = options.loadedAt ?? (this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now());
77
61
  }
78
62
  get prefix() {
@@ -105,15 +89,6 @@ var Logger = class {
105
89
  getLoadedAt() {
106
90
  return this._loadedAt;
107
91
  }
108
- addListener(listener) {
109
- this._listeners.add(listener);
110
- return () => {
111
- this._listeners.delete(listener);
112
- };
113
- }
114
- removeListener(listener) {
115
- this._listeners.delete(listener);
116
- }
117
92
  isEnabled(level) {
118
93
  const target = normalizeLogLevel(level);
119
94
  return (LOG_LEVEL_MAP[target] ?? 20) >= (LOG_LEVEL_MAP[this._level] ?? 20);
@@ -127,23 +102,6 @@ var Logger = class {
127
102
  const current = this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
128
103
  return Math.max(0, current - this._loadedAt);
129
104
  }
130
- _dispatchRecord(record) {
131
- for (const l of this._listeners) {
132
- try {
133
- l(record);
134
- } catch {
135
- }
136
- }
137
- const globalListeners = getGlobalListeners();
138
- for (const gl of globalListeners) {
139
- if (!this._listeners.has(gl)) {
140
- try {
141
- gl(record);
142
- } catch {
143
- }
144
- }
145
- }
146
- }
147
105
  log(level, nameOrMsg, ...args) {
148
106
  const normLevel = normalizeLogLevel(level);
149
107
  if (!this.isEnabled(normLevel)) {
@@ -151,19 +109,6 @@ var Logger = class {
151
109
  }
152
110
  const elapsed = this._getElapsed();
153
111
  const formattedTimeStr = formatTime(elapsed);
154
- const nowEpoch = Date.now();
155
- const recordId = `bk_log_${nowEpoch}_${++logCounter}`;
156
- const record = {
157
- id: recordId,
158
- timestamp: nowEpoch,
159
- elapsedMs: elapsed,
160
- level: normLevel,
161
- prefix: this._prefix,
162
- message: nameOrMsg,
163
- args,
164
- data: args.length === 1 ? args[0] : args.length > 1 ? args : void 0
165
- };
166
- this._dispatchRecord(record);
167
112
  const c = this._getConsole();
168
113
  if (!c) return;
169
114
  let badgeStyle = COLORS.badge;
@@ -986,14 +931,22 @@ var CANONICAL_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
986
931
  var UUID_BYTES = 16;
987
932
  var utf8Encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
988
933
  var utf8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder() : null;
989
- function idToBytes(id) {
990
- if (!id) return new Uint8Array(0);
934
+ function normalizeUuidString(id) {
935
+ if (!id) return null;
991
936
  let clean = id.trim();
992
937
  if (clean.startsWith("{") && clean.endsWith("}")) {
993
938
  clean = clean.slice(1, -1).trim();
994
939
  }
995
940
  const lower = clean.toLowerCase();
996
- if (CANONICAL_UUID.test(lower)) {
941
+ return CANONICAL_UUID.test(lower) ? lower : null;
942
+ }
943
+ function isCanonicalUuid(id) {
944
+ return normalizeUuidString(id) !== null;
945
+ }
946
+ function idToBytes(id) {
947
+ if (!id) return new Uint8Array(0);
948
+ const lower = normalizeUuidString(id);
949
+ if (lower) {
997
950
  const hex = lower.replace(/-/g, "");
998
951
  const out2 = new Uint8Array(UUID_BYTES);
999
952
  for (let i = 0; i < UUID_BYTES; i++) {
@@ -1457,6 +1410,8 @@ var MAX_CACHED_BID_KEYS = 200;
1457
1410
  var MAX_IMPRESSION_KEYS = 1e3;
1458
1411
  var MAX_TRACKED_AUCTIONS = 50;
1459
1412
  var MAX_FLOOR_DECISIONS = 200;
1413
+ var MAX_SYNTHETIC_AUCTION_MAPPINGS = 200;
1414
+ var MAX_SYNTHETIC_BID_MAPPINGS = 2e3;
1460
1415
  var FLOOR_SOURCE_PROTO = {
1461
1416
  static: FloorSource.FLOOR_SOURCE_STATIC,
1462
1417
  pool: FloorSource.FLOOR_SOURCE_POOL,
@@ -1733,19 +1688,41 @@ function cmpStorageAllowed(alias) {
1733
1688
  function escapeKeyPart(str) {
1734
1689
  return String(str ?? "").replace(/%/g, "%25").replace(/:/g, "%3A");
1735
1690
  }
1691
+ function setBoundedMap(map, key, value, maxSize) {
1692
+ if (map.has(key)) map.delete(key);
1693
+ map.set(key, value);
1694
+ while (map.size > maxSize) {
1695
+ const oldest = map.keys().next();
1696
+ if (oldest.done) break;
1697
+ map.delete(oldest.value);
1698
+ }
1699
+ }
1700
+ function auctionInstanceDiscriminator(data) {
1701
+ const parts = [];
1702
+ if (Number.isFinite(data?.timestamp)) {
1703
+ parts.push(escapeKeyPart(data.timestamp));
1704
+ }
1705
+ const req0 = Array.isArray(data?.bidderRequests) ? data.bidderRequests[0] : void 0;
1706
+ const reqId = req0?.bidderRequestId || req0?.bids?.[0]?.bidId || req0?.bids?.[0]?.transactionId;
1707
+ if (reqId) {
1708
+ parts.push(escapeKeyPart(reqId));
1709
+ }
1710
+ return parts.length > 0 ? `:${parts.join(":")}` : "";
1711
+ }
1736
1712
  function getPrebidEventKey(eventName, data) {
1737
1713
  switch (eventName) {
1738
1714
  case "auctionInit":
1739
- return `auctionInit:${escapeKeyPart(data?.auctionId)}`;
1715
+ return `auctionInit:${escapeKeyPart(data?.auctionId)}${auctionInstanceDiscriminator(data)}`;
1740
1716
  case "auctionEnd":
1741
- return `auctionEnd:${escapeKeyPart(data?.auctionId)}`;
1717
+ return `auctionEnd:${escapeKeyPart(data?.auctionId)}${auctionInstanceDiscriminator(data)}`;
1742
1718
  case "bidRequested": {
1743
1719
  const bids = Array.isArray(data?.bids) ? data.bids.map((b) => escapeKeyPart(b?.bidId || b?.transactionId || b?.adUnitCode)).join(",") : "";
1744
- return `bidRequested:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${bids}`;
1720
+ const start = Number.isFinite(data?.auctionStart) ? `:${escapeKeyPart(data.auctionStart)}` : "";
1721
+ return `bidRequested:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${bids}${start}`;
1745
1722
  }
1746
1723
  case "bidResponse": {
1747
1724
  const bid = data || {};
1748
- const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1725
+ const uniqueBidId = bid.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1749
1726
  const price = bid.originalCpm ?? bid.cpm ?? "";
1750
1727
  return `bidResponse:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1751
1728
  }
@@ -1757,7 +1734,7 @@ function getPrebidEventKey(eventName, data) {
1757
1734
  }
1758
1735
  case "bidWon": {
1759
1736
  const bid = data || {};
1760
- const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1737
+ const uniqueBidId = bid.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1761
1738
  const price = bid.originalCpm ?? bid.cpm ?? "";
1762
1739
  return `bidWon:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1763
1740
  }
@@ -1765,11 +1742,13 @@ function getPrebidEventKey(eventName, data) {
1765
1742
  return `noBid:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.adUnitCode)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${escapeKeyPart(data?.bidId || data?.transactionId)}`;
1766
1743
  case "adRenderFailed": {
1767
1744
  const bid = data?.bid || {};
1768
- return `adRenderFailed:${escapeKeyPart(bid.auctionId || data?.auctionId)}:${escapeKeyPart(bid.adUnitCode || data?.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder || data?.bidderCode || data?.bidder)}:${escapeKeyPart(data?.reason)}:${escapeKeyPart(data?.message)}`;
1745
+ const adId = bid.adId || data?.adId || "";
1746
+ const adPart = adId ? `:${escapeKeyPart(adId)}` : "";
1747
+ return `adRenderFailed:${escapeKeyPart(bid.auctionId || data?.auctionId)}:${escapeKeyPart(bid.adUnitCode || data?.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder || data?.bidderCode || data?.bidder)}:${escapeKeyPart(data?.reason)}:${escapeKeyPart(data?.message)}${adPart}`;
1769
1748
  }
1770
1749
  case "adRenderSucceeded": {
1771
1750
  const bid = data?.bid || data || {};
1772
- const uniqueId = bid.creativeId || bid.adId || data?.adId || "";
1751
+ const uniqueId = bid.adId || data?.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1773
1752
  const price = bid.originalCpm ?? bid.cpm ?? "";
1774
1753
  return `adRenderSucceeded:${escapeKeyPart(bid.auctionId || data?.auctionId)}:${escapeKeyPart(bid.adUnitCode || data?.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueId)}:${escapeKeyPart(price)}`;
1775
1754
  }
@@ -1922,6 +1901,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1922
1901
  videoDetachCleanups = /* @__PURE__ */ new Set();
1923
1902
  auctionBidderOutcomes = /* @__PURE__ */ new Map();
1924
1903
  floorDecisions = /* @__PURE__ */ new Map();
1904
+ syntheticAuctionByRawTs = /* @__PURE__ */ new Map();
1905
+ syntheticAuctionByRawLatest = /* @__PURE__ */ new Map();
1906
+ syntheticAuctionByBidId = /* @__PURE__ */ new Map();
1907
+ syntheticAuctionByTxId = /* @__PURE__ */ new Map();
1908
+ syntheticAuctionByAdId = /* @__PURE__ */ new Map();
1909
+ syntheticToRawAuctionId = /* @__PURE__ */ new Map();
1925
1910
  recordedConsentKeys = /* @__PURE__ */ new Set();
1926
1911
  consentCount = 0;
1927
1912
  cmpDetach = null;
@@ -1935,6 +1920,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1935
1920
  managesVisitorId;
1936
1921
  // True once visitorId is settled (storage read, caller-supplied, or first batch drained).
1937
1922
  visitorKeyLocked;
1923
+ hasExplicitPbjsGlobalName;
1938
1924
  constructor(config) {
1939
1925
  const tcfStorage = probeTcfStorageAllowed();
1940
1926
  if (typeof window !== "undefined" && typeof window.__tcfapi === "function") {
@@ -1966,6 +1952,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1966
1952
  }
1967
1953
  this.managesVisitorId = !config.visitorId && !config.userId && !config.sessionId;
1968
1954
  this.visitorKeyLocked = isStorageOn || !this.managesVisitorId;
1955
+ const explicitPbjsGlobal = validPrebidGlobalName(config.pbjsGlobalName);
1956
+ this.hasExplicitPbjsGlobalName = Boolean(explicitPbjsGlobal);
1969
1957
  const usageEndpoint = config.usageEndpoint || "";
1970
1958
  this.config = {
1971
1959
  endpoint,
@@ -1984,7 +1972,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1984
1972
  viewabilityEnabled: config.viewabilityEnabled ?? true,
1985
1973
  storageAllowed: isStorageOn,
1986
1974
  logLevel: config.logLevel ? normalizeLogLevel(config.logLevel) : defaultLogger.getLevel(),
1987
- pbjsGlobalName: config.pbjsGlobalName || "pbjs",
1975
+ pbjsGlobalName: explicitPbjsGlobal || detectPrebidGlobalName(),
1988
1976
  attachPbjsListeners: config.attachPbjsListeners ?? true,
1989
1977
  revenueFlushDelayMs: Number.isFinite(config.revenueFlushDelayMs) && config.revenueFlushDelayMs >= 0 ? config.revenueFlushDelayMs : REVENUE_FLUSH_DELAY_MS,
1990
1978
  alias: config.alias || DEFAULT_ALIAS,
@@ -2101,6 +2089,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2101
2089
  if (!this.isEnabled) return false;
2102
2090
  if (this.boundPbjsHandlers.length > 0) return true;
2103
2091
  const win = typeof window !== "undefined" ? window : {};
2092
+ if (!this.hasExplicitPbjsGlobalName && typeof win[this.config.pbjsGlobalName]?.onEvent !== "function") {
2093
+ this.config.pbjsGlobalName = detectPrebidGlobalName(win);
2094
+ }
2104
2095
  const pbjs = win[this.config.pbjsGlobalName] || {};
2105
2096
  if (typeof pbjs.onEvent !== "function") {
2106
2097
  this.log("WARN", "pbjs.onEvent is not defined. Prebid analytics will not function.");
@@ -2193,6 +2184,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2193
2184
  this.slotLastAuctionIds.clear();
2194
2185
  this.auctionBidderOutcomes.clear();
2195
2186
  this.floorDecisions.clear();
2187
+ this.syntheticAuctionByRawTs.clear();
2188
+ this.syntheticAuctionByRawLatest.clear();
2189
+ this.syntheticAuctionByBidId.clear();
2190
+ this.syntheticAuctionByTxId.clear();
2191
+ this.syntheticAuctionByAdId.clear();
2192
+ this.syntheticToRawAuctionId.clear();
2196
2193
  if (this.flushTimer) {
2197
2194
  clearInterval(this.flushTimer);
2198
2195
  this.flushTimer = null;
@@ -2923,7 +2920,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2923
2920
  }
2924
2921
  }
2925
2922
  floorDecisionFor(auctionId, adUnitCode) {
2926
- return auctionId && adUnitCode ? this.floorDecisions.get(`${auctionId}:${adUnitCode}`) : void 0;
2923
+ if (!auctionId || !adUnitCode) return void 0;
2924
+ const direct = this.floorDecisions.get(`${auctionId}:${adUnitCode}`);
2925
+ if (direct) return direct;
2926
+ const rawAuctionId = this.syntheticToRawAuctionId.get(auctionId);
2927
+ return rawAuctionId ? this.floorDecisions.get(`${rawAuctionId}:${adUnitCode}`) : void 0;
2927
2928
  }
2928
2929
  /**
2929
2930
  * Enqueues one CONSENT event with the record flattened into metadata under snake_case keys.
@@ -3093,10 +3094,117 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3093
3094
  ...typeof bidderCount === "number" ? { metadata: { bidderCount: String(bidderCount) } } : {}
3094
3095
  });
3095
3096
  }
3097
+ collectHintBids(hints) {
3098
+ const items = [];
3099
+ if (Array.isArray(hints.bids)) items.push(...hints.bids);
3100
+ if (Array.isArray(hints.bidsReceived)) items.push(...hints.bidsReceived);
3101
+ if (Array.isArray(hints.noBids)) items.push(...hints.noBids);
3102
+ for (const req of Array.isArray(hints.bidderRequests) ? hints.bidderRequests : []) {
3103
+ if (Array.isArray(req?.bids)) items.push(...req.bids);
3104
+ }
3105
+ return items;
3106
+ }
3107
+ indexAuctionBids(syntheticId, bids) {
3108
+ for (const b of bids) {
3109
+ if (!b || typeof b !== "object") continue;
3110
+ if (b.adId) {
3111
+ setBoundedMap(
3112
+ this.syntheticAuctionByAdId,
3113
+ String(b.adId),
3114
+ syntheticId,
3115
+ MAX_SYNTHETIC_BID_MAPPINGS
3116
+ );
3117
+ }
3118
+ const bidId = b.bidId || b.requestId;
3119
+ if (bidId) {
3120
+ setBoundedMap(
3121
+ this.syntheticAuctionByBidId,
3122
+ String(bidId),
3123
+ syntheticId,
3124
+ MAX_SYNTHETIC_BID_MAPPINGS
3125
+ );
3126
+ }
3127
+ if (b.transactionId) {
3128
+ setBoundedMap(
3129
+ this.syntheticAuctionByTxId,
3130
+ String(b.transactionId),
3131
+ syntheticId,
3132
+ MAX_SYNTHETIC_BID_MAPPINGS
3133
+ );
3134
+ }
3135
+ }
3136
+ }
3137
+ lookupSyntheticFromHints(rawAuctionId, hints, hintBids) {
3138
+ if (hints.adId) {
3139
+ const m = this.syntheticAuctionByAdId.get(hints.adId);
3140
+ if (m) return m;
3141
+ }
3142
+ if (hints.bidId) {
3143
+ const m = this.syntheticAuctionByBidId.get(hints.bidId);
3144
+ if (m) return m;
3145
+ }
3146
+ if (hints.timestamp !== void 0 && Number.isFinite(hints.timestamp)) {
3147
+ const m = this.syntheticAuctionByRawTs.get(`${rawAuctionId}:${hints.timestamp}`);
3148
+ if (m) return m;
3149
+ }
3150
+ for (const b of hintBids) {
3151
+ const bidKey = b?.bidId || b?.requestId;
3152
+ const m = b?.adId && this.syntheticAuctionByAdId.get(String(b.adId)) || bidKey && this.syntheticAuctionByBidId.get(String(bidKey));
3153
+ if (m) return m;
3154
+ }
3155
+ if (hints.transactionId) {
3156
+ const m = this.syntheticAuctionByTxId.get(hints.transactionId);
3157
+ if (m) return m;
3158
+ }
3159
+ for (const b of hintBids) {
3160
+ if (b?.transactionId) {
3161
+ const m = this.syntheticAuctionByTxId.get(String(b.transactionId));
3162
+ if (m) return m;
3163
+ }
3164
+ }
3165
+ if (hints.cachedAuctionId && this.syntheticToRawAuctionId.get(hints.cachedAuctionId) === rawAuctionId) {
3166
+ return hints.cachedAuctionId;
3167
+ }
3168
+ return this.syntheticAuctionByRawLatest.get(rawAuctionId);
3169
+ }
3170
+ mintSyntheticAuction(rawAuctionId, timestamp, trackAsLatest) {
3171
+ const id = generateUUID2();
3172
+ setBoundedMap(this.syntheticToRawAuctionId, id, rawAuctionId, MAX_SYNTHETIC_AUCTION_MAPPINGS);
3173
+ if (!trackAsLatest) return id;
3174
+ setBoundedMap(
3175
+ this.syntheticAuctionByRawLatest,
3176
+ rawAuctionId,
3177
+ id,
3178
+ MAX_SYNTHETIC_AUCTION_MAPPINGS
3179
+ );
3180
+ if (timestamp !== void 0 && Number.isFinite(timestamp)) {
3181
+ setBoundedMap(
3182
+ this.syntheticAuctionByRawTs,
3183
+ `${rawAuctionId}:${timestamp}`,
3184
+ id,
3185
+ MAX_SYNTHETIC_AUCTION_MAPPINGS
3186
+ );
3187
+ }
3188
+ return id;
3189
+ }
3190
+ startPrebidAuction(rawAuctionId, data) {
3191
+ if (!rawAuctionId || isCanonicalUuid(rawAuctionId)) return rawAuctionId;
3192
+ const ts = Number.isFinite(data?.timestamp) ? data.timestamp : void 0;
3193
+ const id = this.mintSyntheticAuction(rawAuctionId, ts, true);
3194
+ this.indexAuctionBids(id, this.collectHintBids({ bidderRequests: data?.bidderRequests }));
3195
+ return id;
3196
+ }
3197
+ resolvePrebidAuctionId(rawAuctionId, hints, mintPerEventIfUnmatched = false) {
3198
+ if (!rawAuctionId || isCanonicalUuid(rawAuctionId)) return rawAuctionId;
3199
+ const hintBids = this.collectHintBids(hints);
3200
+ const resolved = this.lookupSyntheticFromHints(rawAuctionId, hints, hintBids) || this.mintSyntheticAuction(rawAuctionId, hints.timestamp, !mintPerEventIfUnmatched);
3201
+ this.indexAuctionBids(resolved, [hints, ...hintBids]);
3202
+ return resolved;
3203
+ }
3096
3204
  handleAuctionInit(data) {
3097
3205
  if (this.isDuplicate("auctionInit", data)) return;
3098
3206
  this.log("DEBUG", "auctionInit", data);
3099
- const auctionId = data.auctionId || "";
3207
+ const auctionId = this.startPrebidAuction(data.auctionId || "", data);
3100
3208
  if (auctionId) {
3101
3209
  this.auctionBidderOutcomes.delete(auctionId);
3102
3210
  this.getOrCreateAuctionOutcomes(auctionId);
@@ -3113,7 +3221,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3113
3221
  handleAuctionEnd(data) {
3114
3222
  if (this.isDuplicate("auctionEnd", data)) return;
3115
3223
  this.log("DEBUG", "auctionEnd", data);
3116
- const auctionId = data.auctionId || "";
3224
+ const auctionId = this.resolvePrebidAuctionId(data.auctionId || "", {
3225
+ timestamp: Number.isFinite(data.timestamp) ? data.timestamp : void 0,
3226
+ bidderRequests: data.bidderRequests,
3227
+ bidsReceived: data.bidsReceived,
3228
+ noBids: data.noBids
3229
+ });
3117
3230
  const outcomesMap = auctionId ? this.auctionBidderOutcomes.get(auctionId) : void 0;
3118
3231
  const bidderOutcomes = outcomesMap ? Array.from(outcomesMap.values()) : [];
3119
3232
  if (auctionId) {
@@ -3141,7 +3254,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3141
3254
  handleBidRequested(data) {
3142
3255
  if (this.isDuplicate("bidRequested", data)) return;
3143
3256
  this.log("DEBUG", "bidRequested", data);
3144
- const auctionId = data.auctionId || "";
3257
+ const auctionId = this.resolvePrebidAuctionId(data.auctionId || "", {
3258
+ timestamp: Number.isFinite(data.auctionStart) ? data.auctionStart : void 0,
3259
+ bids: Array.isArray(data.bids) ? data.bids : void 0
3260
+ });
3145
3261
  const bidder = data.bidderCode || data.bidder || "";
3146
3262
  if (!auctionId || !bidder) return;
3147
3263
  const auctionMap = this.getOrCreateAuctionOutcomes(auctionId);
@@ -3164,7 +3280,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3164
3280
  handleBidResponse(data) {
3165
3281
  if (this.isDuplicate("bidResponse", data)) return;
3166
3282
  this.log("DEBUG", "bidResponse", data);
3167
- const auctionId = data.auctionId || "";
3283
+ const auctionId = this.resolvePrebidAuctionId(data.auctionId || "", {
3284
+ timestamp: Number.isFinite(data.requestTimestamp) ? data.requestTimestamp : void 0,
3285
+ bidId: data.requestId || data.bidId || void 0,
3286
+ transactionId: data.transactionId || void 0,
3287
+ adId: data.adId || void 0
3288
+ });
3168
3289
  const bidder = data.bidderCode || data.bidder || "";
3169
3290
  const adUnitCode = data.adUnitCode || "";
3170
3291
  const pricing = resolveBidPricing(data);
@@ -3194,7 +3315,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3194
3315
  this.log("DEBUG", "bidTimeout", data);
3195
3316
  const items = Array.isArray(data) ? data : data ? [data] : [];
3196
3317
  for (const t of items) {
3197
- const auctionId = t.auctionId || "";
3318
+ const auctionId = this.resolvePrebidAuctionId(t.auctionId || "", {
3319
+ bidId: t.bidId || t.requestId || void 0,
3320
+ transactionId: t.transactionId || void 0
3321
+ });
3198
3322
  const bidder = t.bidderCode || t.bidder || "";
3199
3323
  const adUnitCode = t.adUnitCode || "";
3200
3324
  const latencyMs = Number.isFinite(t.timeout) ? t.timeout : 0;
@@ -3218,8 +3342,17 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3218
3342
  handleBidWon(data) {
3219
3343
  if (this.isDuplicate("bidWon", data)) return;
3220
3344
  this.log("DEBUG", "bidWon", data);
3221
- const auctionId = data.auctionId || "";
3222
3345
  const transactionId = data.transactionId || "";
3346
+ const auctionId = this.resolvePrebidAuctionId(
3347
+ data.auctionId || "",
3348
+ {
3349
+ timestamp: Number.isFinite(data.requestTimestamp) ? data.requestTimestamp : void 0,
3350
+ bidId: data.requestId || data.bidId || void 0,
3351
+ transactionId: transactionId || void 0,
3352
+ adId: data.adId || void 0
3353
+ },
3354
+ true
3355
+ );
3223
3356
  const adUnitCode = data.adUnitCode || data.adId || "";
3224
3357
  const wonMediaTypes = Object.keys(data.mediaTypes || {});
3225
3358
  const resolvedMediaType = data.mediaType || (data.mediaTypes?.video ? "video" : wonMediaTypes.length > 0 ? wonMediaTypes[0] : "banner");
@@ -3264,7 +3397,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3264
3397
  handleNoBid(data) {
3265
3398
  if (this.isDuplicate("noBid", data)) return;
3266
3399
  this.log("DEBUG", "noBid", data);
3267
- const auctionId = data.auctionId || "";
3400
+ const auctionId = this.resolvePrebidAuctionId(data.auctionId || "", {
3401
+ bidId: data.bidId || data.requestId || void 0,
3402
+ transactionId: data.transactionId || void 0
3403
+ });
3268
3404
  const bidder = data.bidderCode || data.bidder || "";
3269
3405
  const adUnitCode = data.adUnitCode || "";
3270
3406
  if (auctionId && bidder) {
@@ -3288,9 +3424,19 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3288
3424
  if (this.isDuplicate("adRenderFailed", data)) return;
3289
3425
  this.log("DEBUG", "adRenderFailed", data);
3290
3426
  const bid = data.bid || {};
3427
+ const transactionId = bid.transactionId || data.transactionId || "";
3428
+ const auctionId = this.resolvePrebidAuctionId(
3429
+ bid.auctionId || data.auctionId || "",
3430
+ {
3431
+ bidId: bid.requestId || bid.bidId || void 0,
3432
+ transactionId: transactionId || void 0,
3433
+ adId: bid.adId || data.adId || void 0
3434
+ },
3435
+ true
3436
+ );
3291
3437
  this.enqueue(TraceEventType.AD_RENDER_FAILED, "adRenderFailed", {
3292
- auctionId: bid.auctionId || data.auctionId || "",
3293
- transactionId: bid.transactionId || data.transactionId || "",
3438
+ auctionId,
3439
+ transactionId,
3294
3440
  adUnitCode: bid.adUnitCode || data.adUnitCode || "",
3295
3441
  bid: {
3296
3442
  bidder: bid.bidderCode || bid.bidder || data.bidderCode || data.bidder || ""
@@ -3309,12 +3455,24 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3309
3455
  this.log("DEBUG", "adRenderSucceeded", data);
3310
3456
  const bid = data.bid || data || {};
3311
3457
  const adUnitCode = data.adUnitCode || bid.adUnitCode || data.adId || bid.adId || "";
3312
- const auctionId = bid.auctionId || data.auctionId || "";
3458
+ const rawAuctionId = bid.auctionId || data.auctionId || "";
3313
3459
  const transactionId = bid.transactionId || data.transactionId || "";
3314
3460
  const mediaType = bid.mediaType || "banner";
3315
3461
  const slotKey = data.adUnitCode || bid.adUnitCode || "";
3316
3462
  const altKey = data.adId || bid.adId || "";
3317
- const cached = (auctionId && slotKey ? this.getCachedBid(`${auctionId}:${slotKey}`) : void 0) || (auctionId && altKey ? this.getCachedBid(`${auctionId}:${altKey}`) : void 0) || (slotKey ? this.getCachedBid(slotKey) : void 0) || (altKey ? this.getCachedBid(altKey) : void 0);
3463
+ const slotAltCached = (slotKey ? this.getCachedBid(slotKey) : void 0) || (altKey ? this.getCachedBid(altKey) : void 0);
3464
+ const cachedHintAuctionId = !altKey || !slotAltCached?.rawBid?.adId || slotAltCached.rawBid.adId === altKey ? slotAltCached?.auctionId : void 0;
3465
+ const auctionId = this.resolvePrebidAuctionId(
3466
+ rawAuctionId,
3467
+ {
3468
+ bidId: bid.requestId || bid.bidId || void 0,
3469
+ transactionId: transactionId || void 0,
3470
+ adId: altKey || void 0,
3471
+ cachedAuctionId: cachedHintAuctionId
3472
+ },
3473
+ true
3474
+ );
3475
+ const cached = (auctionId && slotKey ? this.getCachedBid(`${auctionId}:${slotKey}`) : void 0) || (auctionId && altKey ? this.getCachedBid(`${auctionId}:${altKey}`) : void 0) || slotAltCached;
3318
3476
  const isVideo = mediaType === "video" || bid.mediaType === "video" || bid.mediaTypes?.video !== void 0 || cached?.bidTrace?.mediaType === "video" || cached?.rawBid?.mediaType === "video" || adUnitCode && this.slotViewabilityRecords.get(adUnitCode)?.mediaType === "video";
3319
3477
  const resolvedMediaType = isVideo ? "video" : mediaType || cached?.bidTrace?.mediaType || "banner";
3320
3478
  const bidTrace = {
@@ -3907,73 +4065,194 @@ function getStashedConfig(win) {
3907
4065
  }
3908
4066
  return null;
3909
4067
  }
3910
- function registerPrebidAnalytics(pbjsGlobalName = "pbjs", defaults) {
4068
+ var UNSAFE_GLOBAL_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
4069
+ var wrappedPbjsGlobalsArrays = /* @__PURE__ */ new WeakSet();
4070
+ var pbjsGlobalsWatchers = /* @__PURE__ */ new WeakMap();
4071
+ function validPrebidGlobalName(name) {
4072
+ if (typeof name !== "string") return null;
4073
+ const trimmed = name.trim();
4074
+ return trimmed && !UNSAFE_GLOBAL_NAMES.has(trimmed) ? trimmed : null;
4075
+ }
4076
+ function detectPrebidGlobals(win) {
4077
+ const target = win ?? (typeof window !== "undefined" ? window : void 0);
4078
+ const raw = target?._pbjsGlobals;
4079
+ if (!Array.isArray(raw)) return [];
4080
+ const seen = /* @__PURE__ */ new Set();
4081
+ const out = [];
4082
+ for (const item of raw) {
4083
+ const name = validPrebidGlobalName(item);
4084
+ if (name && !seen.has(name)) {
4085
+ seen.add(name);
4086
+ out.push(name);
4087
+ }
4088
+ }
4089
+ return out;
4090
+ }
4091
+ function hasPrebidOnEvent(win, name) {
4092
+ const candidate = win?.[name];
4093
+ return typeof candidate?.onEvent === "function";
4094
+ }
4095
+ function detectPrebidGlobalName(win) {
4096
+ const target = win ?? (typeof window !== "undefined" ? window : void 0);
4097
+ const detected = detectPrebidGlobals(target);
4098
+ const ready = detected.find((name) => hasPrebidOnEvent(target, name));
4099
+ if (ready) return ready;
4100
+ if (hasPrebidOnEvent(target, "pbjs")) return "pbjs";
4101
+ return detected[0] || "pbjs";
4102
+ }
4103
+ function getRegisterAnalyticsAdapter(pbjs) {
4104
+ if (!pbjs) return null;
4105
+ if (typeof pbjs.registerAnalyticsAdapter === "function") {
4106
+ return (spec) => pbjs.registerAnalyticsAdapter(spec);
4107
+ }
4108
+ const am = pbjs.adapterManager;
4109
+ if (typeof am?.registerAnalyticsAdapter === "function") {
4110
+ return (spec) => am.registerAnalyticsAdapter(spec);
4111
+ }
4112
+ return null;
4113
+ }
4114
+ function watchPrebidGlobals(win, onGlobal) {
4115
+ const desc = Object.getOwnPropertyDescriptor(win, "_pbjsGlobals");
4116
+ if (desc?.get && pbjsGlobalsWatchers.has(desc.get)) {
4117
+ pbjsGlobalsWatchers.get(desc.get).setHandler(onGlobal);
4118
+ return;
4119
+ }
4120
+ let handler = onGlobal;
4121
+ const notify = (item) => {
4122
+ const name = validPrebidGlobalName(item);
4123
+ if (name) handler(name);
4124
+ };
4125
+ const wrapArray = (arr) => {
4126
+ for (const item of arr) notify(item);
4127
+ if (wrappedPbjsGlobalsArrays.has(arr)) return;
4128
+ wrappedPbjsGlobalsArrays.add(arr);
4129
+ const origPush = arr.push;
4130
+ Object.defineProperty(arr, "push", {
4131
+ configurable: true,
4132
+ writable: true,
4133
+ value(...items) {
4134
+ const res = origPush.apply(this, items);
4135
+ for (const item of items) notify(item);
4136
+ return res;
4137
+ }
4138
+ });
4139
+ };
4140
+ let current = win._pbjsGlobals;
4141
+ if (Array.isArray(current)) {
4142
+ wrapArray(current);
4143
+ }
4144
+ if (desc && (!desc.configurable || desc.get || desc.set)) return;
4145
+ const getter = () => current;
4146
+ const setter = (val) => {
4147
+ if (val === current) return;
4148
+ current = val;
4149
+ if (Array.isArray(val)) wrapArray(val);
4150
+ };
4151
+ pbjsGlobalsWatchers.set(getter, {
4152
+ setHandler(fn) {
4153
+ handler = fn;
4154
+ }
4155
+ });
4156
+ try {
4157
+ Object.defineProperty(win, "_pbjsGlobals", {
4158
+ configurable: true,
4159
+ enumerable: true,
4160
+ get: getter,
4161
+ set: setter
4162
+ });
4163
+ } catch {
4164
+ }
4165
+ }
4166
+ function registerPrebidAnalytics(pbjsGlobalName, defaults) {
3911
4167
  const win = typeof window !== "undefined" ? window : {};
3912
- win[pbjsGlobalName] = win[pbjsGlobalName] || {};
3913
- const pbjs = win[pbjsGlobalName];
3914
- const enableInstance = (options) => {
3915
- const previous = win._bidsparkPrebidAnalytics;
3916
- const pinnedEndpoint = previous?.getEndpoint?.() || "";
3917
- const defaultUsageEndpoint = defaults?.usageEndpoint || "https://by.bidspark.io/u";
3918
- const merged = {
3919
- pbjsGlobalName,
3920
- ...defaults,
3921
- ...options
4168
+ const registerOnGlobal = (globalName) => {
4169
+ win[globalName] = win[globalName] || {};
4170
+ const pbjs = win[globalName];
4171
+ const enableInstance = (options) => {
4172
+ const previous = win._bidsparkPrebidAnalytics;
4173
+ const pinnedEndpoint = previous?.getEndpoint?.() || "";
4174
+ const defaultUsageEndpoint = defaults?.usageEndpoint || "https://by.bidspark.io/u";
4175
+ const merged = {
4176
+ pbjsGlobalName: globalName,
4177
+ ...defaults,
4178
+ ...options
4179
+ };
4180
+ merged.usageEndpoint = defaultUsageEndpoint;
4181
+ if (pinnedEndpoint && !sameEndpointOrigin(merged.endpoint || "", pinnedEndpoint)) {
4182
+ defaultLogger.warn(
4183
+ `Ignoring analytics endpoint change to ${merged.endpoint || "(empty)"}: this page is pinned to ${pinnedEndpoint}. Reload to change the ingest endpoint.`
4184
+ );
4185
+ merged.endpoint = pinnedEndpoint;
4186
+ }
4187
+ if (previous) {
4188
+ try {
4189
+ previous.disable();
4190
+ } catch (e) {
4191
+ defaultLogger.warn("Failed to disable previous analytics instance:", e);
4192
+ }
4193
+ }
4194
+ const analytics = new BidsparkPrebidAnalytics(merged);
4195
+ if (previous && !merged.pageviewId) analytics.continuePageview(previous);
4196
+ analytics.enable();
4197
+ win._bidsparkPrebidAnalytics = analytics;
4198
+ return analytics;
3922
4199
  };
3923
- merged.usageEndpoint = defaultUsageEndpoint;
3924
- if (pinnedEndpoint && !sameEndpointOrigin(merged.endpoint || "", pinnedEndpoint)) {
3925
- defaultLogger.warn(
3926
- `Ignoring analytics endpoint change to ${merged.endpoint || "(empty)"}: this page is pinned to ${pinnedEndpoint}. Reload to change the ingest endpoint.`
3927
- );
3928
- merged.endpoint = pinnedEndpoint;
3929
- }
3930
- if (previous) {
4200
+ const doRegister = () => {
3931
4201
  try {
3932
- previous.disable();
4202
+ const registerAdapter = getRegisterAnalyticsAdapter(pbjs);
4203
+ if (registerAdapter) {
4204
+ const adapter = {
4205
+ enableAnalytics: (config) => {
4206
+ const options = extractAnalyticsOptions(config, !Array.isArray(config));
4207
+ if (options) {
4208
+ enableInstance(options);
4209
+ }
4210
+ },
4211
+ disableAnalytics: () => {
4212
+ if (win._bidsparkPrebidAnalytics) {
4213
+ win._bidsparkPrebidAnalytics.disable();
4214
+ }
4215
+ }
4216
+ };
4217
+ registerAdapter({
4218
+ adapter: { ...adapter },
4219
+ code: "bidspark"
4220
+ });
4221
+ }
4222
+ const stashed = getStashedConfig(win);
4223
+ if (stashed && (stashed.propertyId || defaults?.propertyId)) {
4224
+ enableInstance(stashed);
4225
+ }
3933
4226
  } catch (e) {
3934
- defaultLogger.warn("Failed to disable previous analytics instance:", e);
4227
+ defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
3935
4228
  }
4229
+ };
4230
+ if (getRegisterAnalyticsAdapter(pbjs)) {
4231
+ doRegister();
4232
+ } else {
4233
+ pbjs.que = pbjs.que || [];
4234
+ pbjs.que.push(doRegister);
3936
4235
  }
3937
- const analytics = new BidsparkPrebidAnalytics(merged);
3938
- if (previous && !merged.pageviewId) analytics.continuePageview(previous);
3939
- analytics.enable();
3940
- win._bidsparkPrebidAnalytics = analytics;
3941
- return analytics;
3942
4236
  };
3943
- const doRegister = () => {
3944
- try {
3945
- if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3946
- const adapter = {
3947
- enableAnalytics: (config) => {
3948
- const options = extractAnalyticsOptions(config, !Array.isArray(config));
3949
- if (options) {
3950
- enableInstance(options);
3951
- }
3952
- },
3953
- disableAnalytics: () => {
3954
- if (win._bidsparkPrebidAnalytics) {
3955
- win._bidsparkPrebidAnalytics.disable();
3956
- }
3957
- }
3958
- };
3959
- pbjs.adapterManager.registerAnalyticsAdapter({
3960
- adapter: { ...adapter },
3961
- code: "bidspark"
3962
- });
3963
- }
3964
- const stashed = getStashedConfig(win);
3965
- if (stashed && (stashed.propertyId || defaults?.propertyId)) {
3966
- enableInstance(stashed);
3967
- }
3968
- } catch (e) {
3969
- defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
3970
- }
4237
+ const explicitGlobal = validPrebidGlobalName(pbjsGlobalName);
4238
+ if (explicitGlobal) {
4239
+ registerOnGlobal(explicitGlobal);
4240
+ return;
4241
+ }
4242
+ const registered = /* @__PURE__ */ new Set();
4243
+ const registerOnce = (name) => {
4244
+ if (registered.has(name)) return;
4245
+ registered.add(name);
4246
+ registerOnGlobal(name);
3971
4247
  };
3972
- if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3973
- doRegister();
4248
+ const detected = detectPrebidGlobals(win);
4249
+ if (detected.length > 0) {
4250
+ for (const name of detected) registerOnce(name);
3974
4251
  } else {
3975
- pbjs.que = pbjs.que || [];
3976
- pbjs.que.push(doRegister);
4252
+ registerOnce("pbjs");
4253
+ }
4254
+ if (typeof window !== "undefined") {
4255
+ watchPrebidGlobals(win, registerOnce);
3977
4256
  }
3978
4257
  }
3979
4258
 
@@ -3981,6 +4260,8 @@ function registerPrebidAnalytics(pbjsGlobalName = "pbjs", defaults) {
3981
4260
  var internals = (analytics) => analytics;
3982
4261
  var adsLoaderListenerMap = /* @__PURE__ */ new WeakMap();
3983
4262
  var adsLoadersWithErrorListener = /* @__PURE__ */ new WeakSet();
4263
+ var hookedImaFns = /* @__PURE__ */ new WeakSet();
4264
+ var attachedImaManagers = /* @__PURE__ */ new WeakMap();
3984
4265
  function describeImaError(event) {
3985
4266
  const err = typeof event?.getError === "function" ? event.getError() : event?.error || event;
3986
4267
  const call = (name) => err && typeof err[name] === "function" ? err[name]() : void 0;
@@ -4040,7 +4321,7 @@ function hookAdsManagerLoadedEvent(loadedEventCtor) {
4040
4321
  if (!loadedEventCtor) return;
4041
4322
  try {
4042
4323
  const loadedProto = loadedEventCtor.prototype;
4043
- if (loadedProto && typeof loadedProto.getAdsManager === "function" && !loadedProto.getAdsManager.__bidsparkHooked) {
4324
+ if (loadedProto && typeof loadedProto.getAdsManager === "function" && !hookedImaFns.has(loadedProto.getAdsManager)) {
4044
4325
  const originalGetAdsManager = loadedProto.getAdsManager;
4045
4326
  const hookedGetAdsManager = function(...args) {
4046
4327
  const adsManager = originalGetAdsManager.apply(this, args);
@@ -4054,7 +4335,7 @@ function hookAdsManagerLoadedEvent(loadedEventCtor) {
4054
4335
  }
4055
4336
  return adsManager;
4056
4337
  };
4057
- hookedGetAdsManager.__bidsparkHooked = true;
4338
+ hookedImaFns.add(hookedGetAdsManager);
4058
4339
  loadedProto.getAdsManager = hookedGetAdsManager;
4059
4340
  }
4060
4341
  } catch {
@@ -4064,7 +4345,7 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4064
4345
  if (!adsManagerCtorOrProto) return;
4065
4346
  try {
4066
4347
  const proto = adsManagerCtorOrProto.prototype || adsManagerCtorOrProto;
4067
- if (proto && typeof proto.init === "function" && !proto.init.__bidsparkHooked) {
4348
+ if (proto && typeof proto.init === "function" && !hookedImaFns.has(proto.init)) {
4068
4349
  const origInit = proto.init;
4069
4350
  const hookedInit = function(...args) {
4070
4351
  for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4075,10 +4356,10 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4075
4356
  }
4076
4357
  return origInit.apply(this, args);
4077
4358
  };
4078
- hookedInit.__bidsparkHooked = true;
4359
+ hookedImaFns.add(hookedInit);
4079
4360
  proto.init = hookedInit;
4080
4361
  }
4081
- if (proto && typeof proto.start === "function" && !proto.start.__bidsparkHooked) {
4362
+ if (proto && typeof proto.start === "function" && !hookedImaFns.has(proto.start)) {
4082
4363
  const origStart = proto.start;
4083
4364
  const hookedStart = function(...args) {
4084
4365
  for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4089,7 +4370,7 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4089
4370
  }
4090
4371
  return origStart.apply(this, args);
4091
4372
  };
4092
- hookedStart.__bidsparkHooked = true;
4373
+ hookedImaFns.add(hookedStart);
4093
4374
  proto.start = hookedStart;
4094
4375
  }
4095
4376
  } catch {
@@ -4100,7 +4381,7 @@ function hookAdsLoader(adsLoaderCtor) {
4100
4381
  try {
4101
4382
  const proto = adsLoaderCtor.prototype;
4102
4383
  if (!proto) return;
4103
- if (typeof proto.addEventListener === "function" && !proto.addEventListener.__bidsparkHooked) {
4384
+ if (typeof proto.addEventListener === "function" && !hookedImaFns.has(proto.addEventListener)) {
4104
4385
  const origAddEventListener = proto.addEventListener;
4105
4386
  const hookedAddEventListener = function(type, listener, ...rest) {
4106
4387
  ensureAdsLoaderErrorListener(this, origAddEventListener);
@@ -4108,9 +4389,9 @@ function hookAdsLoader(adsLoaderCtor) {
4108
4389
  let wrappedListener = adsLoaderListenerMap.get(listener);
4109
4390
  if (!wrappedListener) {
4110
4391
  wrappedListener = function(event) {
4111
- if (event && typeof event.getAdsManager === "function" && !event.getAdsManager.__bidsparkHooked) {
4392
+ if (event && typeof event.getAdsManager === "function" && !hookedImaFns.has(event.getAdsManager)) {
4112
4393
  const origGetAdsManager = event.getAdsManager;
4113
- event.getAdsManager = function(...args) {
4394
+ const hookedGetAdsManager = function(...args) {
4114
4395
  const adsManager = origGetAdsManager.apply(this, args);
4115
4396
  if (adsManager) {
4116
4397
  for (const sdk of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4122,7 +4403,8 @@ function hookAdsLoader(adsLoaderCtor) {
4122
4403
  }
4123
4404
  return adsManager;
4124
4405
  };
4125
- event.getAdsManager.__bidsparkHooked = true;
4406
+ hookedImaFns.add(hookedGetAdsManager);
4407
+ event.getAdsManager = hookedGetAdsManager;
4126
4408
  }
4127
4409
  return listener.apply(this, arguments);
4128
4410
  };
@@ -4132,16 +4414,16 @@ function hookAdsLoader(adsLoaderCtor) {
4132
4414
  }
4133
4415
  return origAddEventListener.call(this, type, listener, ...rest);
4134
4416
  };
4135
- hookedAddEventListener.__bidsparkHooked = true;
4417
+ hookedImaFns.add(hookedAddEventListener);
4136
4418
  proto.addEventListener = hookedAddEventListener;
4137
4419
  }
4138
- if (typeof proto.removeEventListener === "function" && !proto.removeEventListener.__bidsparkHooked) {
4420
+ if (typeof proto.removeEventListener === "function" && !hookedImaFns.has(proto.removeEventListener)) {
4139
4421
  const origRemoveEventListener = proto.removeEventListener;
4140
4422
  const hookedRemoveEventListener = function(type, listener, ...rest) {
4141
4423
  const wrapped = typeof listener === "function" ? adsLoaderListenerMap.get(listener) : void 0;
4142
4424
  return origRemoveEventListener.call(this, type, wrapped || listener, ...rest);
4143
4425
  };
4144
- hookedRemoveEventListener.__bidsparkHooked = true;
4426
+ hookedImaFns.add(hookedRemoveEventListener);
4145
4427
  proto.removeEventListener = hookedRemoveEventListener;
4146
4428
  }
4147
4429
  } catch {
@@ -4283,9 +4565,6 @@ function initImaInterception() {
4283
4565
  }
4284
4566
  }
4285
4567
  }
4286
- if (typeof window !== "undefined") {
4287
- initImaInterception();
4288
- }
4289
4568
  function findCachedWinningBid(analytics, filter) {
4290
4569
  const self = internals(analytics);
4291
4570
  const now = Date.now();
@@ -4356,18 +4635,11 @@ function attachImaAdsManager(analytics, adsManager, options) {
4356
4635
  return () => {
4357
4636
  };
4358
4637
  }
4359
- if (!adsManager.__bidsparkAttachedInstances) {
4360
- try {
4361
- Object.defineProperty(adsManager, "__bidsparkAttachedInstances", {
4362
- value: /* @__PURE__ */ new Map(),
4363
- configurable: true,
4364
- writable: true
4365
- });
4366
- } catch {
4367
- adsManager.__bidsparkAttachedInstances = /* @__PURE__ */ new Map();
4368
- }
4638
+ let attached = attachedImaManagers.get(adsManager);
4639
+ if (!attached) {
4640
+ attached = /* @__PURE__ */ new Map();
4641
+ attachedImaManagers.set(adsManager, attached);
4369
4642
  }
4370
- const attached = adsManager.__bidsparkAttachedInstances;
4371
4643
  const previous = attached.get(analytics);
4372
4644
  if (previous) {
4373
4645
  if (!options) return () => {
@@ -4579,7 +4851,9 @@ function attachImaAdsManager(analytics, adsManager, options) {
4579
4851
  }
4580
4852
  const cleanup = () => {
4581
4853
  activeAdSession = null;
4582
- attached.delete(analytics);
4854
+ if (attached.get(analytics) === cleanup) {
4855
+ attached.delete(analytics);
4856
+ }
4583
4857
  for (const { type, handler } of listeners) {
4584
4858
  try {
4585
4859
  adsManager.removeEventListener(type, handler);
@@ -4624,14 +4898,22 @@ function attachVideoPlayer(analytics, target, options) {
4624
4898
  const getWinningBid = () => {
4625
4899
  return (auctionId ? self.getCachedBid(`${auctionId}:${adUnitCode}`) : void 0) || (auctionId && slotId !== adUnitCode ? self.getCachedBid(`${auctionId}:${slotId}`) : void 0) || self.getCachedBid(adUnitCode) || (slotId !== adUnitCode ? self.getCachedBid(slotId) : void 0);
4626
4900
  };
4627
- let videoEl = null;
4628
- if (el) {
4629
- if (el.tagName && el.tagName.toLowerCase() === "video") {
4630
- videoEl = el;
4631
- } else {
4632
- videoEl = el.querySelector("video");
4901
+ const isVideoEl = Boolean(el?.tagName && el.tagName.toLowerCase() === "video");
4902
+ const resolveTargetVideo = (e) => {
4903
+ const target2 = e?.target;
4904
+ if (target2 && (typeof HTMLVideoElement !== "undefined" && target2 instanceof HTMLVideoElement || target2.tagName?.toLowerCase() === "video")) {
4905
+ return target2;
4633
4906
  }
4634
- }
4907
+ if (target2 && typeof target2.closest === "function") {
4908
+ const parentVideo = target2.closest("video");
4909
+ if (parentVideo) return parentVideo;
4910
+ }
4911
+ if (target2 && target2 !== el) {
4912
+ return null;
4913
+ }
4914
+ return isVideoEl ? el : el?.querySelector?.("video") ?? null;
4915
+ };
4916
+ const isForeignChildEvent = (e, targetVideo) => Boolean(e?.target && e.target !== el && !targetVideo);
4635
4917
  const quartilesFired = {
4636
4918
  q1: false,
4637
4919
  q2: false,
@@ -4639,7 +4921,7 @@ function attachVideoPlayer(analytics, target, options) {
4639
4921
  q4: false
4640
4922
  };
4641
4923
  const triggerPlaybackImpression = (activeVideo) => {
4642
- const vEl = activeVideo || videoEl || (el?.querySelector ? el.querySelector("video") : null);
4924
+ const vEl = activeVideo || resolveTargetVideo();
4643
4925
  const cached = getWinningBid();
4644
4926
  const mergedBid = {
4645
4927
  ...cached?.rawBid || options?.bid,
@@ -4666,12 +4948,13 @@ function attachVideoPlayer(analytics, target, options) {
4666
4948
  }
4667
4949
  };
4668
4950
  const handlePlaying = (e) => {
4951
+ const targetVideo = resolveTargetVideo(e);
4952
+ if (isForeignChildEvent(e, targetVideo)) return;
4669
4953
  self.log("DEBUG", "HTML5 video playing event received");
4670
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4671
4954
  triggerPlaybackImpression(targetVideo);
4672
4955
  };
4673
4956
  const handleTimeUpdate = (e) => {
4674
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4957
+ const targetVideo = resolveTargetVideo(e);
4675
4958
  if (targetVideo && targetVideo.currentTime > 0) {
4676
4959
  triggerPlaybackImpression(targetVideo);
4677
4960
  if (Number.isFinite(targetVideo.duration) && targetVideo.duration > 0) {
@@ -4691,15 +4974,17 @@ function attachVideoPlayer(analytics, target, options) {
4691
4974
  }
4692
4975
  }
4693
4976
  };
4694
- const handleEnded = () => {
4977
+ const handleEnded = (e) => {
4978
+ if (isForeignChildEvent(e, resolveTargetVideo(e))) return;
4695
4979
  if (!quartilesFired.q4) {
4696
4980
  quartilesFired.q4 = true;
4697
4981
  options?.onMilestone?.("complete", slotId);
4698
4982
  }
4699
4983
  };
4700
4984
  const handleError = (e) => {
4701
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4702
- const err = targetVideo?.error || videoEl?.error;
4985
+ const targetVideo = resolveTargetVideo(e);
4986
+ if (isForeignChildEvent(e, targetVideo)) return;
4987
+ const err = targetVideo?.error;
4703
4988
  const cached = getWinningBid();
4704
4989
  const msg = err ? `HTML5 video error code ${err.code}: ${err.message}` : "Video playback error";
4705
4990
  self.log("WARN", msg);
@@ -4724,41 +5009,13 @@ function attachVideoPlayer(analytics, target, options) {
4724
5009
  }
4725
5010
  }
4726
5011
  };
4727
- const attachListenersToVideo = (targetVideo) => {
4728
- targetVideo.addEventListener("playing", handlePlaying);
4729
- targetVideo.addEventListener("play", handlePlaying);
4730
- targetVideo.addEventListener("timeupdate", handleTimeUpdate);
4731
- targetVideo.addEventListener("ended", handleEnded);
4732
- targetVideo.addEventListener("error", handleError);
4733
- };
4734
- const removeListenersFromVideo = (targetVideo) => {
4735
- targetVideo.removeEventListener("playing", handlePlaying);
4736
- targetVideo.removeEventListener("play", handlePlaying);
4737
- targetVideo.removeEventListener("timeupdate", handleTimeUpdate);
4738
- targetVideo.removeEventListener("ended", handleEnded);
4739
- targetVideo.removeEventListener("error", handleError);
4740
- };
4741
- let mutationObserver = null;
4742
- if (el && el !== videoEl) {
4743
- el.addEventListener("playing", handlePlaying, true);
4744
- el.addEventListener("play", handlePlaying, true);
4745
- el.addEventListener("timeupdate", handleTimeUpdate, true);
4746
- el.addEventListener("ended", handleEnded, true);
4747
- el.addEventListener("error", handleError, true);
4748
- }
4749
- if (videoEl) {
4750
- attachListenersToVideo(videoEl);
4751
- }
4752
- if (el && el.tagName?.toLowerCase() !== "video" && typeof MutationObserver !== "undefined") {
4753
- mutationObserver = new MutationObserver(() => {
4754
- const found = el.querySelector("video");
4755
- if (found && found !== videoEl) {
4756
- if (videoEl) removeListenersFromVideo(videoEl);
4757
- videoEl = found;
4758
- if (videoEl) attachListenersToVideo(videoEl);
4759
- }
4760
- });
4761
- mutationObserver.observe(el, { childList: true, subtree: true });
5012
+ const useCapture = !isVideoEl;
5013
+ if (el) {
5014
+ el.addEventListener("playing", handlePlaying, useCapture);
5015
+ el.addEventListener("play", handlePlaying, useCapture);
5016
+ el.addEventListener("timeupdate", handleTimeUpdate, useCapture);
5017
+ el.addEventListener("ended", handleEnded, useCapture);
5018
+ el.addEventListener("error", handleError, useCapture);
4762
5019
  }
4763
5020
  const cachedInitial = getWinningBid();
4764
5021
  if (options?.trackViewability !== false && el) {
@@ -4772,19 +5029,12 @@ function attachVideoPlayer(analytics, target, options) {
4772
5029
  });
4773
5030
  }
4774
5031
  const cleanup = () => {
4775
- if (mutationObserver) {
4776
- mutationObserver.disconnect();
4777
- mutationObserver = null;
4778
- }
4779
- if (el && el !== videoEl) {
4780
- el.removeEventListener("playing", handlePlaying, true);
4781
- el.removeEventListener("play", handlePlaying, true);
4782
- el.removeEventListener("timeupdate", handleTimeUpdate, true);
4783
- el.removeEventListener("ended", handleEnded, true);
4784
- el.removeEventListener("error", handleError, true);
4785
- }
4786
- if (videoEl) {
4787
- removeListenersFromVideo(videoEl);
5032
+ if (el) {
5033
+ el.removeEventListener("playing", handlePlaying, useCapture);
5034
+ el.removeEventListener("play", handlePlaying, useCapture);
5035
+ el.removeEventListener("timeupdate", handleTimeUpdate, useCapture);
5036
+ el.removeEventListener("ended", handleEnded, useCapture);
5037
+ el.removeEventListener("error", handleError, useCapture);
4788
5038
  }
4789
5039
  self.videoDetachCleanups.delete(cleanup);
4790
5040
  };
@@ -4797,16 +5047,17 @@ BidsparkPrebidAnalytics.prototype.attachImaAdsManager = function(adsManager, opt
4797
5047
  BidsparkPrebidAnalytics.prototype.attachVideoPlayer = function(target, options) {
4798
5048
  return attachVideoPlayer(this, target, options);
4799
5049
  };
4800
- var coreEnable = BidsparkPrebidAnalytics.prototype.enable;
4801
- BidsparkPrebidAnalytics.prototype.enable = function() {
4802
- coreEnable.call(this);
4803
- if (typeof window !== "undefined") {
5050
+ var imaAutoInterceptionInstalled = false;
5051
+ function installImaAutoInterception() {
5052
+ if (imaAutoInterceptionInstalled) return;
5053
+ imaAutoInterceptionInstalled = true;
5054
+ initImaInterception();
5055
+ const coreEnable = BidsparkPrebidAnalytics.prototype.enable;
5056
+ BidsparkPrebidAnalytics.prototype.enable = function() {
5057
+ coreEnable.call(this);
4804
5058
  initImaInterception();
4805
- if (window.google?.ima) {
4806
- hookImaPrototype(window.google.ima);
4807
- }
4808
- }
4809
- };
5059
+ };
5060
+ }
4810
5061
  function normalizeImaEventName(name) {
4811
5062
  if (!name) return "";
4812
5063
  const lower = name.toLowerCase().replace(/[_-]/g, "");
@@ -4925,6 +5176,7 @@ var ImaAdsManagerStub = class {
4925
5176
  };
4926
5177
 
4927
5178
  // src/index.ts
5179
+ installImaAutoInterception();
4928
5180
  function getAdsGlobal(alias = DEFAULT_ALIAS) {
4929
5181
  if (typeof window === "undefined") {
4930
5182
  return { q: [] };
@@ -4988,6 +5240,7 @@ export {
4988
5240
  attachVideoPlayer,
4989
5241
  clearStoredSession,
4990
5242
  clearStoredUserId,
5243
+ detectPrebidGlobals,
4991
5244
  generateUUID,
4992
5245
  getAdsGlobal,
4993
5246
  getOrCreateSessionId,
@@ -4995,7 +5248,9 @@ export {
4995
5248
  getPrebidEventKey,
4996
5249
  idToBytes,
4997
5250
  idToString,
5251
+ installImaAutoInterception,
4998
5252
  isAutomatedClient,
5253
+ isCanonicalUuid,
4999
5254
  isSessionActive,
5000
5255
  isTrustedEndpoint,
5001
5256
  isVisitorSampled,