@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.js CHANGED
@@ -35,6 +35,7 @@ __export(src_exports, {
35
35
  attachVideoPlayer: () => attachVideoPlayer,
36
36
  clearStoredSession: () => clearStoredSession,
37
37
  clearStoredUserId: () => clearStoredUserId,
38
+ detectPrebidGlobals: () => detectPrebidGlobals,
38
39
  generateUUID: () => generateUUID,
39
40
  getAdsGlobal: () => getAdsGlobal,
40
41
  getOrCreateSessionId: () => getOrCreateSessionId,
@@ -42,7 +43,9 @@ __export(src_exports, {
42
43
  getPrebidEventKey: () => getPrebidEventKey,
43
44
  idToBytes: () => idToBytes,
44
45
  idToString: () => idToString,
46
+ installImaAutoInterception: () => installImaAutoInterception,
45
47
  isAutomatedClient: () => isAutomatedClient,
48
+ isCanonicalUuid: () => isCanonicalUuid,
46
49
  isSessionActive: () => isSessionActive,
47
50
  isTrustedEndpoint: () => isTrustedEndpoint,
48
51
  isVisitorSampled: () => isVisitorSampled,
@@ -79,18 +82,6 @@ var COLORS = {
79
82
  eventError: "color: #ef4444; font-weight: bold",
80
83
  reset: "color: inherit"
81
84
  };
82
- var logCounter = 0;
83
- var localGlobalListeners = /* @__PURE__ */ new Set();
84
- function getGlobalListeners() {
85
- if (typeof window !== "undefined") {
86
- const win = window;
87
- if (!win.__bidsparkLogListeners) {
88
- win.__bidsparkLogListeners = /* @__PURE__ */ new Set();
89
- }
90
- return win.__bidsparkLogListeners;
91
- }
92
- return localGlobalListeners;
93
- }
94
85
  function formatTime(ms) {
95
86
  if (ms < 0 || !Number.isFinite(ms)) ms = 0;
96
87
  if (ms < 1e3) return `${ms.toFixed(2)}ms`;
@@ -116,15 +107,11 @@ var Logger = class {
116
107
  _loadedAt;
117
108
  _now;
118
109
  _console;
119
- _listeners = /* @__PURE__ */ new Set();
120
110
  constructor(options = {}) {
121
111
  this._prefix = options.prefix ?? "[ads]";
122
112
  this._level = normalizeLogLevel(options.logLevel ?? LogLevel.INFO);
123
113
  this._now = options.now;
124
114
  this._console = options.console;
125
- if (options.onLog) {
126
- this._listeners.add(options.onLog);
127
- }
128
115
  this._loadedAt = options.loadedAt ?? (this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now());
129
116
  }
130
117
  get prefix() {
@@ -157,15 +144,6 @@ var Logger = class {
157
144
  getLoadedAt() {
158
145
  return this._loadedAt;
159
146
  }
160
- addListener(listener) {
161
- this._listeners.add(listener);
162
- return () => {
163
- this._listeners.delete(listener);
164
- };
165
- }
166
- removeListener(listener) {
167
- this._listeners.delete(listener);
168
- }
169
147
  isEnabled(level) {
170
148
  const target = normalizeLogLevel(level);
171
149
  return (LOG_LEVEL_MAP[target] ?? 20) >= (LOG_LEVEL_MAP[this._level] ?? 20);
@@ -179,23 +157,6 @@ var Logger = class {
179
157
  const current = this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
180
158
  return Math.max(0, current - this._loadedAt);
181
159
  }
182
- _dispatchRecord(record) {
183
- for (const l of this._listeners) {
184
- try {
185
- l(record);
186
- } catch {
187
- }
188
- }
189
- const globalListeners = getGlobalListeners();
190
- for (const gl of globalListeners) {
191
- if (!this._listeners.has(gl)) {
192
- try {
193
- gl(record);
194
- } catch {
195
- }
196
- }
197
- }
198
- }
199
160
  log(level, nameOrMsg, ...args) {
200
161
  const normLevel = normalizeLogLevel(level);
201
162
  if (!this.isEnabled(normLevel)) {
@@ -203,19 +164,6 @@ var Logger = class {
203
164
  }
204
165
  const elapsed = this._getElapsed();
205
166
  const formattedTimeStr = formatTime(elapsed);
206
- const nowEpoch = Date.now();
207
- const recordId = `bk_log_${nowEpoch}_${++logCounter}`;
208
- const record = {
209
- id: recordId,
210
- timestamp: nowEpoch,
211
- elapsedMs: elapsed,
212
- level: normLevel,
213
- prefix: this._prefix,
214
- message: nameOrMsg,
215
- args,
216
- data: args.length === 1 ? args[0] : args.length > 1 ? args : void 0
217
- };
218
- this._dispatchRecord(record);
219
167
  const c = this._getConsole();
220
168
  if (!c) return;
221
169
  let badgeStyle = COLORS.badge;
@@ -1038,14 +986,22 @@ var CANONICAL_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
1038
986
  var UUID_BYTES = 16;
1039
987
  var utf8Encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
1040
988
  var utf8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder() : null;
1041
- function idToBytes(id) {
1042
- if (!id) return new Uint8Array(0);
989
+ function normalizeUuidString(id) {
990
+ if (!id) return null;
1043
991
  let clean = id.trim();
1044
992
  if (clean.startsWith("{") && clean.endsWith("}")) {
1045
993
  clean = clean.slice(1, -1).trim();
1046
994
  }
1047
995
  const lower = clean.toLowerCase();
1048
- if (CANONICAL_UUID.test(lower)) {
996
+ return CANONICAL_UUID.test(lower) ? lower : null;
997
+ }
998
+ function isCanonicalUuid(id) {
999
+ return normalizeUuidString(id) !== null;
1000
+ }
1001
+ function idToBytes(id) {
1002
+ if (!id) return new Uint8Array(0);
1003
+ const lower = normalizeUuidString(id);
1004
+ if (lower) {
1049
1005
  const hex = lower.replace(/-/g, "");
1050
1006
  const out2 = new Uint8Array(UUID_BYTES);
1051
1007
  for (let i = 0; i < UUID_BYTES; i++) {
@@ -1509,6 +1465,8 @@ var MAX_CACHED_BID_KEYS = 200;
1509
1465
  var MAX_IMPRESSION_KEYS = 1e3;
1510
1466
  var MAX_TRACKED_AUCTIONS = 50;
1511
1467
  var MAX_FLOOR_DECISIONS = 200;
1468
+ var MAX_SYNTHETIC_AUCTION_MAPPINGS = 200;
1469
+ var MAX_SYNTHETIC_BID_MAPPINGS = 2e3;
1512
1470
  var FLOOR_SOURCE_PROTO = {
1513
1471
  static: FloorSource.FLOOR_SOURCE_STATIC,
1514
1472
  pool: FloorSource.FLOOR_SOURCE_POOL,
@@ -1785,19 +1743,41 @@ function cmpStorageAllowed(alias) {
1785
1743
  function escapeKeyPart(str) {
1786
1744
  return String(str ?? "").replace(/%/g, "%25").replace(/:/g, "%3A");
1787
1745
  }
1746
+ function setBoundedMap(map, key, value, maxSize) {
1747
+ if (map.has(key)) map.delete(key);
1748
+ map.set(key, value);
1749
+ while (map.size > maxSize) {
1750
+ const oldest = map.keys().next();
1751
+ if (oldest.done) break;
1752
+ map.delete(oldest.value);
1753
+ }
1754
+ }
1755
+ function auctionInstanceDiscriminator(data) {
1756
+ const parts = [];
1757
+ if (Number.isFinite(data?.timestamp)) {
1758
+ parts.push(escapeKeyPart(data.timestamp));
1759
+ }
1760
+ const req0 = Array.isArray(data?.bidderRequests) ? data.bidderRequests[0] : void 0;
1761
+ const reqId = req0?.bidderRequestId || req0?.bids?.[0]?.bidId || req0?.bids?.[0]?.transactionId;
1762
+ if (reqId) {
1763
+ parts.push(escapeKeyPart(reqId));
1764
+ }
1765
+ return parts.length > 0 ? `:${parts.join(":")}` : "";
1766
+ }
1788
1767
  function getPrebidEventKey(eventName, data) {
1789
1768
  switch (eventName) {
1790
1769
  case "auctionInit":
1791
- return `auctionInit:${escapeKeyPart(data?.auctionId)}`;
1770
+ return `auctionInit:${escapeKeyPart(data?.auctionId)}${auctionInstanceDiscriminator(data)}`;
1792
1771
  case "auctionEnd":
1793
- return `auctionEnd:${escapeKeyPart(data?.auctionId)}`;
1772
+ return `auctionEnd:${escapeKeyPart(data?.auctionId)}${auctionInstanceDiscriminator(data)}`;
1794
1773
  case "bidRequested": {
1795
1774
  const bids = Array.isArray(data?.bids) ? data.bids.map((b) => escapeKeyPart(b?.bidId || b?.transactionId || b?.adUnitCode)).join(",") : "";
1796
- return `bidRequested:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${bids}`;
1775
+ const start = Number.isFinite(data?.auctionStart) ? `:${escapeKeyPart(data.auctionStart)}` : "";
1776
+ return `bidRequested:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${bids}${start}`;
1797
1777
  }
1798
1778
  case "bidResponse": {
1799
1779
  const bid = data || {};
1800
- const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1780
+ const uniqueBidId = bid.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1801
1781
  const price = bid.originalCpm ?? bid.cpm ?? "";
1802
1782
  return `bidResponse:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1803
1783
  }
@@ -1809,7 +1789,7 @@ function getPrebidEventKey(eventName, data) {
1809
1789
  }
1810
1790
  case "bidWon": {
1811
1791
  const bid = data || {};
1812
- const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1792
+ const uniqueBidId = bid.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1813
1793
  const price = bid.originalCpm ?? bid.cpm ?? "";
1814
1794
  return `bidWon:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1815
1795
  }
@@ -1817,11 +1797,13 @@ function getPrebidEventKey(eventName, data) {
1817
1797
  return `noBid:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.adUnitCode)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${escapeKeyPart(data?.bidId || data?.transactionId)}`;
1818
1798
  case "adRenderFailed": {
1819
1799
  const bid = data?.bid || {};
1820
- 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)}`;
1800
+ const adId = bid.adId || data?.adId || "";
1801
+ const adPart = adId ? `:${escapeKeyPart(adId)}` : "";
1802
+ 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}`;
1821
1803
  }
1822
1804
  case "adRenderSucceeded": {
1823
1805
  const bid = data?.bid || data || {};
1824
- const uniqueId = bid.creativeId || bid.adId || data?.adId || "";
1806
+ const uniqueId = bid.adId || data?.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1825
1807
  const price = bid.originalCpm ?? bid.cpm ?? "";
1826
1808
  return `adRenderSucceeded:${escapeKeyPart(bid.auctionId || data?.auctionId)}:${escapeKeyPart(bid.adUnitCode || data?.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueId)}:${escapeKeyPart(price)}`;
1827
1809
  }
@@ -1974,6 +1956,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1974
1956
  videoDetachCleanups = /* @__PURE__ */ new Set();
1975
1957
  auctionBidderOutcomes = /* @__PURE__ */ new Map();
1976
1958
  floorDecisions = /* @__PURE__ */ new Map();
1959
+ syntheticAuctionByRawTs = /* @__PURE__ */ new Map();
1960
+ syntheticAuctionByRawLatest = /* @__PURE__ */ new Map();
1961
+ syntheticAuctionByBidId = /* @__PURE__ */ new Map();
1962
+ syntheticAuctionByTxId = /* @__PURE__ */ new Map();
1963
+ syntheticAuctionByAdId = /* @__PURE__ */ new Map();
1964
+ syntheticToRawAuctionId = /* @__PURE__ */ new Map();
1977
1965
  recordedConsentKeys = /* @__PURE__ */ new Set();
1978
1966
  consentCount = 0;
1979
1967
  cmpDetach = null;
@@ -1987,6 +1975,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1987
1975
  managesVisitorId;
1988
1976
  // True once visitorId is settled (storage read, caller-supplied, or first batch drained).
1989
1977
  visitorKeyLocked;
1978
+ hasExplicitPbjsGlobalName;
1990
1979
  constructor(config) {
1991
1980
  const tcfStorage = probeTcfStorageAllowed();
1992
1981
  if (typeof window !== "undefined" && typeof window.__tcfapi === "function") {
@@ -2018,6 +2007,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2018
2007
  }
2019
2008
  this.managesVisitorId = !config.visitorId && !config.userId && !config.sessionId;
2020
2009
  this.visitorKeyLocked = isStorageOn || !this.managesVisitorId;
2010
+ const explicitPbjsGlobal = validPrebidGlobalName(config.pbjsGlobalName);
2011
+ this.hasExplicitPbjsGlobalName = Boolean(explicitPbjsGlobal);
2021
2012
  const usageEndpoint = config.usageEndpoint || "";
2022
2013
  this.config = {
2023
2014
  endpoint,
@@ -2036,7 +2027,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2036
2027
  viewabilityEnabled: config.viewabilityEnabled ?? true,
2037
2028
  storageAllowed: isStorageOn,
2038
2029
  logLevel: config.logLevel ? normalizeLogLevel(config.logLevel) : defaultLogger.getLevel(),
2039
- pbjsGlobalName: config.pbjsGlobalName || "pbjs",
2030
+ pbjsGlobalName: explicitPbjsGlobal || detectPrebidGlobalName(),
2040
2031
  attachPbjsListeners: config.attachPbjsListeners ?? true,
2041
2032
  revenueFlushDelayMs: Number.isFinite(config.revenueFlushDelayMs) && config.revenueFlushDelayMs >= 0 ? config.revenueFlushDelayMs : REVENUE_FLUSH_DELAY_MS,
2042
2033
  alias: config.alias || DEFAULT_ALIAS,
@@ -2153,6 +2144,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2153
2144
  if (!this.isEnabled) return false;
2154
2145
  if (this.boundPbjsHandlers.length > 0) return true;
2155
2146
  const win = typeof window !== "undefined" ? window : {};
2147
+ if (!this.hasExplicitPbjsGlobalName && typeof win[this.config.pbjsGlobalName]?.onEvent !== "function") {
2148
+ this.config.pbjsGlobalName = detectPrebidGlobalName(win);
2149
+ }
2156
2150
  const pbjs = win[this.config.pbjsGlobalName] || {};
2157
2151
  if (typeof pbjs.onEvent !== "function") {
2158
2152
  this.log("WARN", "pbjs.onEvent is not defined. Prebid analytics will not function.");
@@ -2245,6 +2239,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2245
2239
  this.slotLastAuctionIds.clear();
2246
2240
  this.auctionBidderOutcomes.clear();
2247
2241
  this.floorDecisions.clear();
2242
+ this.syntheticAuctionByRawTs.clear();
2243
+ this.syntheticAuctionByRawLatest.clear();
2244
+ this.syntheticAuctionByBidId.clear();
2245
+ this.syntheticAuctionByTxId.clear();
2246
+ this.syntheticAuctionByAdId.clear();
2247
+ this.syntheticToRawAuctionId.clear();
2248
2248
  if (this.flushTimer) {
2249
2249
  clearInterval(this.flushTimer);
2250
2250
  this.flushTimer = null;
@@ -2975,7 +2975,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2975
2975
  }
2976
2976
  }
2977
2977
  floorDecisionFor(auctionId, adUnitCode) {
2978
- return auctionId && adUnitCode ? this.floorDecisions.get(`${auctionId}:${adUnitCode}`) : void 0;
2978
+ if (!auctionId || !adUnitCode) return void 0;
2979
+ const direct = this.floorDecisions.get(`${auctionId}:${adUnitCode}`);
2980
+ if (direct) return direct;
2981
+ const rawAuctionId = this.syntheticToRawAuctionId.get(auctionId);
2982
+ return rawAuctionId ? this.floorDecisions.get(`${rawAuctionId}:${adUnitCode}`) : void 0;
2979
2983
  }
2980
2984
  /**
2981
2985
  * Enqueues one CONSENT event with the record flattened into metadata under snake_case keys.
@@ -3145,10 +3149,117 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3145
3149
  ...typeof bidderCount === "number" ? { metadata: { bidderCount: String(bidderCount) } } : {}
3146
3150
  });
3147
3151
  }
3152
+ collectHintBids(hints) {
3153
+ const items = [];
3154
+ if (Array.isArray(hints.bids)) items.push(...hints.bids);
3155
+ if (Array.isArray(hints.bidsReceived)) items.push(...hints.bidsReceived);
3156
+ if (Array.isArray(hints.noBids)) items.push(...hints.noBids);
3157
+ for (const req of Array.isArray(hints.bidderRequests) ? hints.bidderRequests : []) {
3158
+ if (Array.isArray(req?.bids)) items.push(...req.bids);
3159
+ }
3160
+ return items;
3161
+ }
3162
+ indexAuctionBids(syntheticId, bids) {
3163
+ for (const b of bids) {
3164
+ if (!b || typeof b !== "object") continue;
3165
+ if (b.adId) {
3166
+ setBoundedMap(
3167
+ this.syntheticAuctionByAdId,
3168
+ String(b.adId),
3169
+ syntheticId,
3170
+ MAX_SYNTHETIC_BID_MAPPINGS
3171
+ );
3172
+ }
3173
+ const bidId = b.bidId || b.requestId;
3174
+ if (bidId) {
3175
+ setBoundedMap(
3176
+ this.syntheticAuctionByBidId,
3177
+ String(bidId),
3178
+ syntheticId,
3179
+ MAX_SYNTHETIC_BID_MAPPINGS
3180
+ );
3181
+ }
3182
+ if (b.transactionId) {
3183
+ setBoundedMap(
3184
+ this.syntheticAuctionByTxId,
3185
+ String(b.transactionId),
3186
+ syntheticId,
3187
+ MAX_SYNTHETIC_BID_MAPPINGS
3188
+ );
3189
+ }
3190
+ }
3191
+ }
3192
+ lookupSyntheticFromHints(rawAuctionId, hints, hintBids) {
3193
+ if (hints.adId) {
3194
+ const m = this.syntheticAuctionByAdId.get(hints.adId);
3195
+ if (m) return m;
3196
+ }
3197
+ if (hints.bidId) {
3198
+ const m = this.syntheticAuctionByBidId.get(hints.bidId);
3199
+ if (m) return m;
3200
+ }
3201
+ if (hints.timestamp !== void 0 && Number.isFinite(hints.timestamp)) {
3202
+ const m = this.syntheticAuctionByRawTs.get(`${rawAuctionId}:${hints.timestamp}`);
3203
+ if (m) return m;
3204
+ }
3205
+ for (const b of hintBids) {
3206
+ const bidKey = b?.bidId || b?.requestId;
3207
+ const m = b?.adId && this.syntheticAuctionByAdId.get(String(b.adId)) || bidKey && this.syntheticAuctionByBidId.get(String(bidKey));
3208
+ if (m) return m;
3209
+ }
3210
+ if (hints.transactionId) {
3211
+ const m = this.syntheticAuctionByTxId.get(hints.transactionId);
3212
+ if (m) return m;
3213
+ }
3214
+ for (const b of hintBids) {
3215
+ if (b?.transactionId) {
3216
+ const m = this.syntheticAuctionByTxId.get(String(b.transactionId));
3217
+ if (m) return m;
3218
+ }
3219
+ }
3220
+ if (hints.cachedAuctionId && this.syntheticToRawAuctionId.get(hints.cachedAuctionId) === rawAuctionId) {
3221
+ return hints.cachedAuctionId;
3222
+ }
3223
+ return this.syntheticAuctionByRawLatest.get(rawAuctionId);
3224
+ }
3225
+ mintSyntheticAuction(rawAuctionId, timestamp, trackAsLatest) {
3226
+ const id = generateUUID2();
3227
+ setBoundedMap(this.syntheticToRawAuctionId, id, rawAuctionId, MAX_SYNTHETIC_AUCTION_MAPPINGS);
3228
+ if (!trackAsLatest) return id;
3229
+ setBoundedMap(
3230
+ this.syntheticAuctionByRawLatest,
3231
+ rawAuctionId,
3232
+ id,
3233
+ MAX_SYNTHETIC_AUCTION_MAPPINGS
3234
+ );
3235
+ if (timestamp !== void 0 && Number.isFinite(timestamp)) {
3236
+ setBoundedMap(
3237
+ this.syntheticAuctionByRawTs,
3238
+ `${rawAuctionId}:${timestamp}`,
3239
+ id,
3240
+ MAX_SYNTHETIC_AUCTION_MAPPINGS
3241
+ );
3242
+ }
3243
+ return id;
3244
+ }
3245
+ startPrebidAuction(rawAuctionId, data) {
3246
+ if (!rawAuctionId || isCanonicalUuid(rawAuctionId)) return rawAuctionId;
3247
+ const ts = Number.isFinite(data?.timestamp) ? data.timestamp : void 0;
3248
+ const id = this.mintSyntheticAuction(rawAuctionId, ts, true);
3249
+ this.indexAuctionBids(id, this.collectHintBids({ bidderRequests: data?.bidderRequests }));
3250
+ return id;
3251
+ }
3252
+ resolvePrebidAuctionId(rawAuctionId, hints, mintPerEventIfUnmatched = false) {
3253
+ if (!rawAuctionId || isCanonicalUuid(rawAuctionId)) return rawAuctionId;
3254
+ const hintBids = this.collectHintBids(hints);
3255
+ const resolved = this.lookupSyntheticFromHints(rawAuctionId, hints, hintBids) || this.mintSyntheticAuction(rawAuctionId, hints.timestamp, !mintPerEventIfUnmatched);
3256
+ this.indexAuctionBids(resolved, [hints, ...hintBids]);
3257
+ return resolved;
3258
+ }
3148
3259
  handleAuctionInit(data) {
3149
3260
  if (this.isDuplicate("auctionInit", data)) return;
3150
3261
  this.log("DEBUG", "auctionInit", data);
3151
- const auctionId = data.auctionId || "";
3262
+ const auctionId = this.startPrebidAuction(data.auctionId || "", data);
3152
3263
  if (auctionId) {
3153
3264
  this.auctionBidderOutcomes.delete(auctionId);
3154
3265
  this.getOrCreateAuctionOutcomes(auctionId);
@@ -3165,7 +3276,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3165
3276
  handleAuctionEnd(data) {
3166
3277
  if (this.isDuplicate("auctionEnd", data)) return;
3167
3278
  this.log("DEBUG", "auctionEnd", data);
3168
- const auctionId = data.auctionId || "";
3279
+ const auctionId = this.resolvePrebidAuctionId(data.auctionId || "", {
3280
+ timestamp: Number.isFinite(data.timestamp) ? data.timestamp : void 0,
3281
+ bidderRequests: data.bidderRequests,
3282
+ bidsReceived: data.bidsReceived,
3283
+ noBids: data.noBids
3284
+ });
3169
3285
  const outcomesMap = auctionId ? this.auctionBidderOutcomes.get(auctionId) : void 0;
3170
3286
  const bidderOutcomes = outcomesMap ? Array.from(outcomesMap.values()) : [];
3171
3287
  if (auctionId) {
@@ -3193,7 +3309,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3193
3309
  handleBidRequested(data) {
3194
3310
  if (this.isDuplicate("bidRequested", data)) return;
3195
3311
  this.log("DEBUG", "bidRequested", data);
3196
- const auctionId = data.auctionId || "";
3312
+ const auctionId = this.resolvePrebidAuctionId(data.auctionId || "", {
3313
+ timestamp: Number.isFinite(data.auctionStart) ? data.auctionStart : void 0,
3314
+ bids: Array.isArray(data.bids) ? data.bids : void 0
3315
+ });
3197
3316
  const bidder = data.bidderCode || data.bidder || "";
3198
3317
  if (!auctionId || !bidder) return;
3199
3318
  const auctionMap = this.getOrCreateAuctionOutcomes(auctionId);
@@ -3216,7 +3335,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3216
3335
  handleBidResponse(data) {
3217
3336
  if (this.isDuplicate("bidResponse", data)) return;
3218
3337
  this.log("DEBUG", "bidResponse", data);
3219
- const auctionId = data.auctionId || "";
3338
+ const auctionId = this.resolvePrebidAuctionId(data.auctionId || "", {
3339
+ timestamp: Number.isFinite(data.requestTimestamp) ? data.requestTimestamp : void 0,
3340
+ bidId: data.requestId || data.bidId || void 0,
3341
+ transactionId: data.transactionId || void 0,
3342
+ adId: data.adId || void 0
3343
+ });
3220
3344
  const bidder = data.bidderCode || data.bidder || "";
3221
3345
  const adUnitCode = data.adUnitCode || "";
3222
3346
  const pricing = resolveBidPricing(data);
@@ -3246,7 +3370,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3246
3370
  this.log("DEBUG", "bidTimeout", data);
3247
3371
  const items = Array.isArray(data) ? data : data ? [data] : [];
3248
3372
  for (const t of items) {
3249
- const auctionId = t.auctionId || "";
3373
+ const auctionId = this.resolvePrebidAuctionId(t.auctionId || "", {
3374
+ bidId: t.bidId || t.requestId || void 0,
3375
+ transactionId: t.transactionId || void 0
3376
+ });
3250
3377
  const bidder = t.bidderCode || t.bidder || "";
3251
3378
  const adUnitCode = t.adUnitCode || "";
3252
3379
  const latencyMs = Number.isFinite(t.timeout) ? t.timeout : 0;
@@ -3270,8 +3397,17 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3270
3397
  handleBidWon(data) {
3271
3398
  if (this.isDuplicate("bidWon", data)) return;
3272
3399
  this.log("DEBUG", "bidWon", data);
3273
- const auctionId = data.auctionId || "";
3274
3400
  const transactionId = data.transactionId || "";
3401
+ const auctionId = this.resolvePrebidAuctionId(
3402
+ data.auctionId || "",
3403
+ {
3404
+ timestamp: Number.isFinite(data.requestTimestamp) ? data.requestTimestamp : void 0,
3405
+ bidId: data.requestId || data.bidId || void 0,
3406
+ transactionId: transactionId || void 0,
3407
+ adId: data.adId || void 0
3408
+ },
3409
+ true
3410
+ );
3275
3411
  const adUnitCode = data.adUnitCode || data.adId || "";
3276
3412
  const wonMediaTypes = Object.keys(data.mediaTypes || {});
3277
3413
  const resolvedMediaType = data.mediaType || (data.mediaTypes?.video ? "video" : wonMediaTypes.length > 0 ? wonMediaTypes[0] : "banner");
@@ -3316,7 +3452,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3316
3452
  handleNoBid(data) {
3317
3453
  if (this.isDuplicate("noBid", data)) return;
3318
3454
  this.log("DEBUG", "noBid", data);
3319
- const auctionId = data.auctionId || "";
3455
+ const auctionId = this.resolvePrebidAuctionId(data.auctionId || "", {
3456
+ bidId: data.bidId || data.requestId || void 0,
3457
+ transactionId: data.transactionId || void 0
3458
+ });
3320
3459
  const bidder = data.bidderCode || data.bidder || "";
3321
3460
  const adUnitCode = data.adUnitCode || "";
3322
3461
  if (auctionId && bidder) {
@@ -3340,9 +3479,19 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3340
3479
  if (this.isDuplicate("adRenderFailed", data)) return;
3341
3480
  this.log("DEBUG", "adRenderFailed", data);
3342
3481
  const bid = data.bid || {};
3482
+ const transactionId = bid.transactionId || data.transactionId || "";
3483
+ const auctionId = this.resolvePrebidAuctionId(
3484
+ bid.auctionId || data.auctionId || "",
3485
+ {
3486
+ bidId: bid.requestId || bid.bidId || void 0,
3487
+ transactionId: transactionId || void 0,
3488
+ adId: bid.adId || data.adId || void 0
3489
+ },
3490
+ true
3491
+ );
3343
3492
  this.enqueue(TraceEventType.AD_RENDER_FAILED, "adRenderFailed", {
3344
- auctionId: bid.auctionId || data.auctionId || "",
3345
- transactionId: bid.transactionId || data.transactionId || "",
3493
+ auctionId,
3494
+ transactionId,
3346
3495
  adUnitCode: bid.adUnitCode || data.adUnitCode || "",
3347
3496
  bid: {
3348
3497
  bidder: bid.bidderCode || bid.bidder || data.bidderCode || data.bidder || ""
@@ -3361,12 +3510,24 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3361
3510
  this.log("DEBUG", "adRenderSucceeded", data);
3362
3511
  const bid = data.bid || data || {};
3363
3512
  const adUnitCode = data.adUnitCode || bid.adUnitCode || data.adId || bid.adId || "";
3364
- const auctionId = bid.auctionId || data.auctionId || "";
3513
+ const rawAuctionId = bid.auctionId || data.auctionId || "";
3365
3514
  const transactionId = bid.transactionId || data.transactionId || "";
3366
3515
  const mediaType = bid.mediaType || "banner";
3367
3516
  const slotKey = data.adUnitCode || bid.adUnitCode || "";
3368
3517
  const altKey = data.adId || bid.adId || "";
3369
- 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);
3518
+ const slotAltCached = (slotKey ? this.getCachedBid(slotKey) : void 0) || (altKey ? this.getCachedBid(altKey) : void 0);
3519
+ const cachedHintAuctionId = !altKey || !slotAltCached?.rawBid?.adId || slotAltCached.rawBid.adId === altKey ? slotAltCached?.auctionId : void 0;
3520
+ const auctionId = this.resolvePrebidAuctionId(
3521
+ rawAuctionId,
3522
+ {
3523
+ bidId: bid.requestId || bid.bidId || void 0,
3524
+ transactionId: transactionId || void 0,
3525
+ adId: altKey || void 0,
3526
+ cachedAuctionId: cachedHintAuctionId
3527
+ },
3528
+ true
3529
+ );
3530
+ const cached = (auctionId && slotKey ? this.getCachedBid(`${auctionId}:${slotKey}`) : void 0) || (auctionId && altKey ? this.getCachedBid(`${auctionId}:${altKey}`) : void 0) || slotAltCached;
3370
3531
  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";
3371
3532
  const resolvedMediaType = isVideo ? "video" : mediaType || cached?.bidTrace?.mediaType || "banner";
3372
3533
  const bidTrace = {
@@ -3959,73 +4120,194 @@ function getStashedConfig(win) {
3959
4120
  }
3960
4121
  return null;
3961
4122
  }
3962
- function registerPrebidAnalytics(pbjsGlobalName = "pbjs", defaults) {
4123
+ var UNSAFE_GLOBAL_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
4124
+ var wrappedPbjsGlobalsArrays = /* @__PURE__ */ new WeakSet();
4125
+ var pbjsGlobalsWatchers = /* @__PURE__ */ new WeakMap();
4126
+ function validPrebidGlobalName(name) {
4127
+ if (typeof name !== "string") return null;
4128
+ const trimmed = name.trim();
4129
+ return trimmed && !UNSAFE_GLOBAL_NAMES.has(trimmed) ? trimmed : null;
4130
+ }
4131
+ function detectPrebidGlobals(win) {
4132
+ const target = win ?? (typeof window !== "undefined" ? window : void 0);
4133
+ const raw = target?._pbjsGlobals;
4134
+ if (!Array.isArray(raw)) return [];
4135
+ const seen = /* @__PURE__ */ new Set();
4136
+ const out = [];
4137
+ for (const item of raw) {
4138
+ const name = validPrebidGlobalName(item);
4139
+ if (name && !seen.has(name)) {
4140
+ seen.add(name);
4141
+ out.push(name);
4142
+ }
4143
+ }
4144
+ return out;
4145
+ }
4146
+ function hasPrebidOnEvent(win, name) {
4147
+ const candidate = win?.[name];
4148
+ return typeof candidate?.onEvent === "function";
4149
+ }
4150
+ function detectPrebidGlobalName(win) {
4151
+ const target = win ?? (typeof window !== "undefined" ? window : void 0);
4152
+ const detected = detectPrebidGlobals(target);
4153
+ const ready = detected.find((name) => hasPrebidOnEvent(target, name));
4154
+ if (ready) return ready;
4155
+ if (hasPrebidOnEvent(target, "pbjs")) return "pbjs";
4156
+ return detected[0] || "pbjs";
4157
+ }
4158
+ function getRegisterAnalyticsAdapter(pbjs) {
4159
+ if (!pbjs) return null;
4160
+ if (typeof pbjs.registerAnalyticsAdapter === "function") {
4161
+ return (spec) => pbjs.registerAnalyticsAdapter(spec);
4162
+ }
4163
+ const am = pbjs.adapterManager;
4164
+ if (typeof am?.registerAnalyticsAdapter === "function") {
4165
+ return (spec) => am.registerAnalyticsAdapter(spec);
4166
+ }
4167
+ return null;
4168
+ }
4169
+ function watchPrebidGlobals(win, onGlobal) {
4170
+ const desc = Object.getOwnPropertyDescriptor(win, "_pbjsGlobals");
4171
+ if (desc?.get && pbjsGlobalsWatchers.has(desc.get)) {
4172
+ pbjsGlobalsWatchers.get(desc.get).setHandler(onGlobal);
4173
+ return;
4174
+ }
4175
+ let handler = onGlobal;
4176
+ const notify = (item) => {
4177
+ const name = validPrebidGlobalName(item);
4178
+ if (name) handler(name);
4179
+ };
4180
+ const wrapArray = (arr) => {
4181
+ for (const item of arr) notify(item);
4182
+ if (wrappedPbjsGlobalsArrays.has(arr)) return;
4183
+ wrappedPbjsGlobalsArrays.add(arr);
4184
+ const origPush = arr.push;
4185
+ Object.defineProperty(arr, "push", {
4186
+ configurable: true,
4187
+ writable: true,
4188
+ value(...items) {
4189
+ const res = origPush.apply(this, items);
4190
+ for (const item of items) notify(item);
4191
+ return res;
4192
+ }
4193
+ });
4194
+ };
4195
+ let current = win._pbjsGlobals;
4196
+ if (Array.isArray(current)) {
4197
+ wrapArray(current);
4198
+ }
4199
+ if (desc && (!desc.configurable || desc.get || desc.set)) return;
4200
+ const getter = () => current;
4201
+ const setter = (val) => {
4202
+ if (val === current) return;
4203
+ current = val;
4204
+ if (Array.isArray(val)) wrapArray(val);
4205
+ };
4206
+ pbjsGlobalsWatchers.set(getter, {
4207
+ setHandler(fn) {
4208
+ handler = fn;
4209
+ }
4210
+ });
4211
+ try {
4212
+ Object.defineProperty(win, "_pbjsGlobals", {
4213
+ configurable: true,
4214
+ enumerable: true,
4215
+ get: getter,
4216
+ set: setter
4217
+ });
4218
+ } catch {
4219
+ }
4220
+ }
4221
+ function registerPrebidAnalytics(pbjsGlobalName, defaults) {
3963
4222
  const win = typeof window !== "undefined" ? window : {};
3964
- win[pbjsGlobalName] = win[pbjsGlobalName] || {};
3965
- const pbjs = win[pbjsGlobalName];
3966
- const enableInstance = (options) => {
3967
- const previous = win._bidsparkPrebidAnalytics;
3968
- const pinnedEndpoint = previous?.getEndpoint?.() || "";
3969
- const defaultUsageEndpoint = defaults?.usageEndpoint || "https://by.bidspark.io/u";
3970
- const merged = {
3971
- pbjsGlobalName,
3972
- ...defaults,
3973
- ...options
4223
+ const registerOnGlobal = (globalName) => {
4224
+ win[globalName] = win[globalName] || {};
4225
+ const pbjs = win[globalName];
4226
+ const enableInstance = (options) => {
4227
+ const previous = win._bidsparkPrebidAnalytics;
4228
+ const pinnedEndpoint = previous?.getEndpoint?.() || "";
4229
+ const defaultUsageEndpoint = defaults?.usageEndpoint || "https://by.bidspark.io/u";
4230
+ const merged = {
4231
+ pbjsGlobalName: globalName,
4232
+ ...defaults,
4233
+ ...options
4234
+ };
4235
+ merged.usageEndpoint = defaultUsageEndpoint;
4236
+ if (pinnedEndpoint && !sameEndpointOrigin(merged.endpoint || "", pinnedEndpoint)) {
4237
+ defaultLogger.warn(
4238
+ `Ignoring analytics endpoint change to ${merged.endpoint || "(empty)"}: this page is pinned to ${pinnedEndpoint}. Reload to change the ingest endpoint.`
4239
+ );
4240
+ merged.endpoint = pinnedEndpoint;
4241
+ }
4242
+ if (previous) {
4243
+ try {
4244
+ previous.disable();
4245
+ } catch (e) {
4246
+ defaultLogger.warn("Failed to disable previous analytics instance:", e);
4247
+ }
4248
+ }
4249
+ const analytics = new BidsparkPrebidAnalytics(merged);
4250
+ if (previous && !merged.pageviewId) analytics.continuePageview(previous);
4251
+ analytics.enable();
4252
+ win._bidsparkPrebidAnalytics = analytics;
4253
+ return analytics;
3974
4254
  };
3975
- merged.usageEndpoint = defaultUsageEndpoint;
3976
- if (pinnedEndpoint && !sameEndpointOrigin(merged.endpoint || "", pinnedEndpoint)) {
3977
- defaultLogger.warn(
3978
- `Ignoring analytics endpoint change to ${merged.endpoint || "(empty)"}: this page is pinned to ${pinnedEndpoint}. Reload to change the ingest endpoint.`
3979
- );
3980
- merged.endpoint = pinnedEndpoint;
3981
- }
3982
- if (previous) {
4255
+ const doRegister = () => {
3983
4256
  try {
3984
- previous.disable();
4257
+ const registerAdapter = getRegisterAnalyticsAdapter(pbjs);
4258
+ if (registerAdapter) {
4259
+ const adapter = {
4260
+ enableAnalytics: (config) => {
4261
+ const options = extractAnalyticsOptions(config, !Array.isArray(config));
4262
+ if (options) {
4263
+ enableInstance(options);
4264
+ }
4265
+ },
4266
+ disableAnalytics: () => {
4267
+ if (win._bidsparkPrebidAnalytics) {
4268
+ win._bidsparkPrebidAnalytics.disable();
4269
+ }
4270
+ }
4271
+ };
4272
+ registerAdapter({
4273
+ adapter: { ...adapter },
4274
+ code: "bidspark"
4275
+ });
4276
+ }
4277
+ const stashed = getStashedConfig(win);
4278
+ if (stashed && (stashed.propertyId || defaults?.propertyId)) {
4279
+ enableInstance(stashed);
4280
+ }
3985
4281
  } catch (e) {
3986
- defaultLogger.warn("Failed to disable previous analytics instance:", e);
4282
+ defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
3987
4283
  }
4284
+ };
4285
+ if (getRegisterAnalyticsAdapter(pbjs)) {
4286
+ doRegister();
4287
+ } else {
4288
+ pbjs.que = pbjs.que || [];
4289
+ pbjs.que.push(doRegister);
3988
4290
  }
3989
- const analytics = new BidsparkPrebidAnalytics(merged);
3990
- if (previous && !merged.pageviewId) analytics.continuePageview(previous);
3991
- analytics.enable();
3992
- win._bidsparkPrebidAnalytics = analytics;
3993
- return analytics;
3994
4291
  };
3995
- const doRegister = () => {
3996
- try {
3997
- if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3998
- const adapter = {
3999
- enableAnalytics: (config) => {
4000
- const options = extractAnalyticsOptions(config, !Array.isArray(config));
4001
- if (options) {
4002
- enableInstance(options);
4003
- }
4004
- },
4005
- disableAnalytics: () => {
4006
- if (win._bidsparkPrebidAnalytics) {
4007
- win._bidsparkPrebidAnalytics.disable();
4008
- }
4009
- }
4010
- };
4011
- pbjs.adapterManager.registerAnalyticsAdapter({
4012
- adapter: { ...adapter },
4013
- code: "bidspark"
4014
- });
4015
- }
4016
- const stashed = getStashedConfig(win);
4017
- if (stashed && (stashed.propertyId || defaults?.propertyId)) {
4018
- enableInstance(stashed);
4019
- }
4020
- } catch (e) {
4021
- defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
4022
- }
4292
+ const explicitGlobal = validPrebidGlobalName(pbjsGlobalName);
4293
+ if (explicitGlobal) {
4294
+ registerOnGlobal(explicitGlobal);
4295
+ return;
4296
+ }
4297
+ const registered = /* @__PURE__ */ new Set();
4298
+ const registerOnce = (name) => {
4299
+ if (registered.has(name)) return;
4300
+ registered.add(name);
4301
+ registerOnGlobal(name);
4023
4302
  };
4024
- if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
4025
- doRegister();
4303
+ const detected = detectPrebidGlobals(win);
4304
+ if (detected.length > 0) {
4305
+ for (const name of detected) registerOnce(name);
4026
4306
  } else {
4027
- pbjs.que = pbjs.que || [];
4028
- pbjs.que.push(doRegister);
4307
+ registerOnce("pbjs");
4308
+ }
4309
+ if (typeof window !== "undefined") {
4310
+ watchPrebidGlobals(win, registerOnce);
4029
4311
  }
4030
4312
  }
4031
4313
 
@@ -4033,6 +4315,8 @@ function registerPrebidAnalytics(pbjsGlobalName = "pbjs", defaults) {
4033
4315
  var internals = (analytics) => analytics;
4034
4316
  var adsLoaderListenerMap = /* @__PURE__ */ new WeakMap();
4035
4317
  var adsLoadersWithErrorListener = /* @__PURE__ */ new WeakSet();
4318
+ var hookedImaFns = /* @__PURE__ */ new WeakSet();
4319
+ var attachedImaManagers = /* @__PURE__ */ new WeakMap();
4036
4320
  function describeImaError(event) {
4037
4321
  const err = typeof event?.getError === "function" ? event.getError() : event?.error || event;
4038
4322
  const call = (name) => err && typeof err[name] === "function" ? err[name]() : void 0;
@@ -4092,7 +4376,7 @@ function hookAdsManagerLoadedEvent(loadedEventCtor) {
4092
4376
  if (!loadedEventCtor) return;
4093
4377
  try {
4094
4378
  const loadedProto = loadedEventCtor.prototype;
4095
- if (loadedProto && typeof loadedProto.getAdsManager === "function" && !loadedProto.getAdsManager.__bidsparkHooked) {
4379
+ if (loadedProto && typeof loadedProto.getAdsManager === "function" && !hookedImaFns.has(loadedProto.getAdsManager)) {
4096
4380
  const originalGetAdsManager = loadedProto.getAdsManager;
4097
4381
  const hookedGetAdsManager = function(...args) {
4098
4382
  const adsManager = originalGetAdsManager.apply(this, args);
@@ -4106,7 +4390,7 @@ function hookAdsManagerLoadedEvent(loadedEventCtor) {
4106
4390
  }
4107
4391
  return adsManager;
4108
4392
  };
4109
- hookedGetAdsManager.__bidsparkHooked = true;
4393
+ hookedImaFns.add(hookedGetAdsManager);
4110
4394
  loadedProto.getAdsManager = hookedGetAdsManager;
4111
4395
  }
4112
4396
  } catch {
@@ -4116,7 +4400,7 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4116
4400
  if (!adsManagerCtorOrProto) return;
4117
4401
  try {
4118
4402
  const proto = adsManagerCtorOrProto.prototype || adsManagerCtorOrProto;
4119
- if (proto && typeof proto.init === "function" && !proto.init.__bidsparkHooked) {
4403
+ if (proto && typeof proto.init === "function" && !hookedImaFns.has(proto.init)) {
4120
4404
  const origInit = proto.init;
4121
4405
  const hookedInit = function(...args) {
4122
4406
  for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4127,10 +4411,10 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4127
4411
  }
4128
4412
  return origInit.apply(this, args);
4129
4413
  };
4130
- hookedInit.__bidsparkHooked = true;
4414
+ hookedImaFns.add(hookedInit);
4131
4415
  proto.init = hookedInit;
4132
4416
  }
4133
- if (proto && typeof proto.start === "function" && !proto.start.__bidsparkHooked) {
4417
+ if (proto && typeof proto.start === "function" && !hookedImaFns.has(proto.start)) {
4134
4418
  const origStart = proto.start;
4135
4419
  const hookedStart = function(...args) {
4136
4420
  for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4141,7 +4425,7 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4141
4425
  }
4142
4426
  return origStart.apply(this, args);
4143
4427
  };
4144
- hookedStart.__bidsparkHooked = true;
4428
+ hookedImaFns.add(hookedStart);
4145
4429
  proto.start = hookedStart;
4146
4430
  }
4147
4431
  } catch {
@@ -4152,7 +4436,7 @@ function hookAdsLoader(adsLoaderCtor) {
4152
4436
  try {
4153
4437
  const proto = adsLoaderCtor.prototype;
4154
4438
  if (!proto) return;
4155
- if (typeof proto.addEventListener === "function" && !proto.addEventListener.__bidsparkHooked) {
4439
+ if (typeof proto.addEventListener === "function" && !hookedImaFns.has(proto.addEventListener)) {
4156
4440
  const origAddEventListener = proto.addEventListener;
4157
4441
  const hookedAddEventListener = function(type, listener, ...rest) {
4158
4442
  ensureAdsLoaderErrorListener(this, origAddEventListener);
@@ -4160,9 +4444,9 @@ function hookAdsLoader(adsLoaderCtor) {
4160
4444
  let wrappedListener = adsLoaderListenerMap.get(listener);
4161
4445
  if (!wrappedListener) {
4162
4446
  wrappedListener = function(event) {
4163
- if (event && typeof event.getAdsManager === "function" && !event.getAdsManager.__bidsparkHooked) {
4447
+ if (event && typeof event.getAdsManager === "function" && !hookedImaFns.has(event.getAdsManager)) {
4164
4448
  const origGetAdsManager = event.getAdsManager;
4165
- event.getAdsManager = function(...args) {
4449
+ const hookedGetAdsManager = function(...args) {
4166
4450
  const adsManager = origGetAdsManager.apply(this, args);
4167
4451
  if (adsManager) {
4168
4452
  for (const sdk of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4174,7 +4458,8 @@ function hookAdsLoader(adsLoaderCtor) {
4174
4458
  }
4175
4459
  return adsManager;
4176
4460
  };
4177
- event.getAdsManager.__bidsparkHooked = true;
4461
+ hookedImaFns.add(hookedGetAdsManager);
4462
+ event.getAdsManager = hookedGetAdsManager;
4178
4463
  }
4179
4464
  return listener.apply(this, arguments);
4180
4465
  };
@@ -4184,16 +4469,16 @@ function hookAdsLoader(adsLoaderCtor) {
4184
4469
  }
4185
4470
  return origAddEventListener.call(this, type, listener, ...rest);
4186
4471
  };
4187
- hookedAddEventListener.__bidsparkHooked = true;
4472
+ hookedImaFns.add(hookedAddEventListener);
4188
4473
  proto.addEventListener = hookedAddEventListener;
4189
4474
  }
4190
- if (typeof proto.removeEventListener === "function" && !proto.removeEventListener.__bidsparkHooked) {
4475
+ if (typeof proto.removeEventListener === "function" && !hookedImaFns.has(proto.removeEventListener)) {
4191
4476
  const origRemoveEventListener = proto.removeEventListener;
4192
4477
  const hookedRemoveEventListener = function(type, listener, ...rest) {
4193
4478
  const wrapped = typeof listener === "function" ? adsLoaderListenerMap.get(listener) : void 0;
4194
4479
  return origRemoveEventListener.call(this, type, wrapped || listener, ...rest);
4195
4480
  };
4196
- hookedRemoveEventListener.__bidsparkHooked = true;
4481
+ hookedImaFns.add(hookedRemoveEventListener);
4197
4482
  proto.removeEventListener = hookedRemoveEventListener;
4198
4483
  }
4199
4484
  } catch {
@@ -4335,9 +4620,6 @@ function initImaInterception() {
4335
4620
  }
4336
4621
  }
4337
4622
  }
4338
- if (typeof window !== "undefined") {
4339
- initImaInterception();
4340
- }
4341
4623
  function findCachedWinningBid(analytics, filter) {
4342
4624
  const self = internals(analytics);
4343
4625
  const now = Date.now();
@@ -4408,18 +4690,11 @@ function attachImaAdsManager(analytics, adsManager, options) {
4408
4690
  return () => {
4409
4691
  };
4410
4692
  }
4411
- if (!adsManager.__bidsparkAttachedInstances) {
4412
- try {
4413
- Object.defineProperty(adsManager, "__bidsparkAttachedInstances", {
4414
- value: /* @__PURE__ */ new Map(),
4415
- configurable: true,
4416
- writable: true
4417
- });
4418
- } catch {
4419
- adsManager.__bidsparkAttachedInstances = /* @__PURE__ */ new Map();
4420
- }
4693
+ let attached = attachedImaManagers.get(adsManager);
4694
+ if (!attached) {
4695
+ attached = /* @__PURE__ */ new Map();
4696
+ attachedImaManagers.set(adsManager, attached);
4421
4697
  }
4422
- const attached = adsManager.__bidsparkAttachedInstances;
4423
4698
  const previous = attached.get(analytics);
4424
4699
  if (previous) {
4425
4700
  if (!options) return () => {
@@ -4631,7 +4906,9 @@ function attachImaAdsManager(analytics, adsManager, options) {
4631
4906
  }
4632
4907
  const cleanup = () => {
4633
4908
  activeAdSession = null;
4634
- attached.delete(analytics);
4909
+ if (attached.get(analytics) === cleanup) {
4910
+ attached.delete(analytics);
4911
+ }
4635
4912
  for (const { type, handler } of listeners) {
4636
4913
  try {
4637
4914
  adsManager.removeEventListener(type, handler);
@@ -4676,14 +4953,22 @@ function attachVideoPlayer(analytics, target, options) {
4676
4953
  const getWinningBid = () => {
4677
4954
  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);
4678
4955
  };
4679
- let videoEl = null;
4680
- if (el) {
4681
- if (el.tagName && el.tagName.toLowerCase() === "video") {
4682
- videoEl = el;
4683
- } else {
4684
- videoEl = el.querySelector("video");
4956
+ const isVideoEl = Boolean(el?.tagName && el.tagName.toLowerCase() === "video");
4957
+ const resolveTargetVideo = (e) => {
4958
+ const target2 = e?.target;
4959
+ if (target2 && (typeof HTMLVideoElement !== "undefined" && target2 instanceof HTMLVideoElement || target2.tagName?.toLowerCase() === "video")) {
4960
+ return target2;
4685
4961
  }
4686
- }
4962
+ if (target2 && typeof target2.closest === "function") {
4963
+ const parentVideo = target2.closest("video");
4964
+ if (parentVideo) return parentVideo;
4965
+ }
4966
+ if (target2 && target2 !== el) {
4967
+ return null;
4968
+ }
4969
+ return isVideoEl ? el : el?.querySelector?.("video") ?? null;
4970
+ };
4971
+ const isForeignChildEvent = (e, targetVideo) => Boolean(e?.target && e.target !== el && !targetVideo);
4687
4972
  const quartilesFired = {
4688
4973
  q1: false,
4689
4974
  q2: false,
@@ -4691,7 +4976,7 @@ function attachVideoPlayer(analytics, target, options) {
4691
4976
  q4: false
4692
4977
  };
4693
4978
  const triggerPlaybackImpression = (activeVideo) => {
4694
- const vEl = activeVideo || videoEl || (el?.querySelector ? el.querySelector("video") : null);
4979
+ const vEl = activeVideo || resolveTargetVideo();
4695
4980
  const cached = getWinningBid();
4696
4981
  const mergedBid = {
4697
4982
  ...cached?.rawBid || options?.bid,
@@ -4718,12 +5003,13 @@ function attachVideoPlayer(analytics, target, options) {
4718
5003
  }
4719
5004
  };
4720
5005
  const handlePlaying = (e) => {
5006
+ const targetVideo = resolveTargetVideo(e);
5007
+ if (isForeignChildEvent(e, targetVideo)) return;
4721
5008
  self.log("DEBUG", "HTML5 video playing event received");
4722
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4723
5009
  triggerPlaybackImpression(targetVideo);
4724
5010
  };
4725
5011
  const handleTimeUpdate = (e) => {
4726
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
5012
+ const targetVideo = resolveTargetVideo(e);
4727
5013
  if (targetVideo && targetVideo.currentTime > 0) {
4728
5014
  triggerPlaybackImpression(targetVideo);
4729
5015
  if (Number.isFinite(targetVideo.duration) && targetVideo.duration > 0) {
@@ -4743,15 +5029,17 @@ function attachVideoPlayer(analytics, target, options) {
4743
5029
  }
4744
5030
  }
4745
5031
  };
4746
- const handleEnded = () => {
5032
+ const handleEnded = (e) => {
5033
+ if (isForeignChildEvent(e, resolveTargetVideo(e))) return;
4747
5034
  if (!quartilesFired.q4) {
4748
5035
  quartilesFired.q4 = true;
4749
5036
  options?.onMilestone?.("complete", slotId);
4750
5037
  }
4751
5038
  };
4752
5039
  const handleError = (e) => {
4753
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4754
- const err = targetVideo?.error || videoEl?.error;
5040
+ const targetVideo = resolveTargetVideo(e);
5041
+ if (isForeignChildEvent(e, targetVideo)) return;
5042
+ const err = targetVideo?.error;
4755
5043
  const cached = getWinningBid();
4756
5044
  const msg = err ? `HTML5 video error code ${err.code}: ${err.message}` : "Video playback error";
4757
5045
  self.log("WARN", msg);
@@ -4776,41 +5064,13 @@ function attachVideoPlayer(analytics, target, options) {
4776
5064
  }
4777
5065
  }
4778
5066
  };
4779
- const attachListenersToVideo = (targetVideo) => {
4780
- targetVideo.addEventListener("playing", handlePlaying);
4781
- targetVideo.addEventListener("play", handlePlaying);
4782
- targetVideo.addEventListener("timeupdate", handleTimeUpdate);
4783
- targetVideo.addEventListener("ended", handleEnded);
4784
- targetVideo.addEventListener("error", handleError);
4785
- };
4786
- const removeListenersFromVideo = (targetVideo) => {
4787
- targetVideo.removeEventListener("playing", handlePlaying);
4788
- targetVideo.removeEventListener("play", handlePlaying);
4789
- targetVideo.removeEventListener("timeupdate", handleTimeUpdate);
4790
- targetVideo.removeEventListener("ended", handleEnded);
4791
- targetVideo.removeEventListener("error", handleError);
4792
- };
4793
- let mutationObserver = null;
4794
- if (el && el !== videoEl) {
4795
- el.addEventListener("playing", handlePlaying, true);
4796
- el.addEventListener("play", handlePlaying, true);
4797
- el.addEventListener("timeupdate", handleTimeUpdate, true);
4798
- el.addEventListener("ended", handleEnded, true);
4799
- el.addEventListener("error", handleError, true);
4800
- }
4801
- if (videoEl) {
4802
- attachListenersToVideo(videoEl);
4803
- }
4804
- if (el && el.tagName?.toLowerCase() !== "video" && typeof MutationObserver !== "undefined") {
4805
- mutationObserver = new MutationObserver(() => {
4806
- const found = el.querySelector("video");
4807
- if (found && found !== videoEl) {
4808
- if (videoEl) removeListenersFromVideo(videoEl);
4809
- videoEl = found;
4810
- if (videoEl) attachListenersToVideo(videoEl);
4811
- }
4812
- });
4813
- mutationObserver.observe(el, { childList: true, subtree: true });
5067
+ const useCapture = !isVideoEl;
5068
+ if (el) {
5069
+ el.addEventListener("playing", handlePlaying, useCapture);
5070
+ el.addEventListener("play", handlePlaying, useCapture);
5071
+ el.addEventListener("timeupdate", handleTimeUpdate, useCapture);
5072
+ el.addEventListener("ended", handleEnded, useCapture);
5073
+ el.addEventListener("error", handleError, useCapture);
4814
5074
  }
4815
5075
  const cachedInitial = getWinningBid();
4816
5076
  if (options?.trackViewability !== false && el) {
@@ -4824,19 +5084,12 @@ function attachVideoPlayer(analytics, target, options) {
4824
5084
  });
4825
5085
  }
4826
5086
  const cleanup = () => {
4827
- if (mutationObserver) {
4828
- mutationObserver.disconnect();
4829
- mutationObserver = null;
4830
- }
4831
- if (el && el !== videoEl) {
4832
- el.removeEventListener("playing", handlePlaying, true);
4833
- el.removeEventListener("play", handlePlaying, true);
4834
- el.removeEventListener("timeupdate", handleTimeUpdate, true);
4835
- el.removeEventListener("ended", handleEnded, true);
4836
- el.removeEventListener("error", handleError, true);
4837
- }
4838
- if (videoEl) {
4839
- removeListenersFromVideo(videoEl);
5087
+ if (el) {
5088
+ el.removeEventListener("playing", handlePlaying, useCapture);
5089
+ el.removeEventListener("play", handlePlaying, useCapture);
5090
+ el.removeEventListener("timeupdate", handleTimeUpdate, useCapture);
5091
+ el.removeEventListener("ended", handleEnded, useCapture);
5092
+ el.removeEventListener("error", handleError, useCapture);
4840
5093
  }
4841
5094
  self.videoDetachCleanups.delete(cleanup);
4842
5095
  };
@@ -4849,16 +5102,17 @@ BidsparkPrebidAnalytics.prototype.attachImaAdsManager = function(adsManager, opt
4849
5102
  BidsparkPrebidAnalytics.prototype.attachVideoPlayer = function(target, options) {
4850
5103
  return attachVideoPlayer(this, target, options);
4851
5104
  };
4852
- var coreEnable = BidsparkPrebidAnalytics.prototype.enable;
4853
- BidsparkPrebidAnalytics.prototype.enable = function() {
4854
- coreEnable.call(this);
4855
- if (typeof window !== "undefined") {
5105
+ var imaAutoInterceptionInstalled = false;
5106
+ function installImaAutoInterception() {
5107
+ if (imaAutoInterceptionInstalled) return;
5108
+ imaAutoInterceptionInstalled = true;
5109
+ initImaInterception();
5110
+ const coreEnable = BidsparkPrebidAnalytics.prototype.enable;
5111
+ BidsparkPrebidAnalytics.prototype.enable = function() {
5112
+ coreEnable.call(this);
4856
5113
  initImaInterception();
4857
- if (window.google?.ima) {
4858
- hookImaPrototype(window.google.ima);
4859
- }
4860
- }
4861
- };
5114
+ };
5115
+ }
4862
5116
  function normalizeImaEventName(name) {
4863
5117
  if (!name) return "";
4864
5118
  const lower = name.toLowerCase().replace(/[_-]/g, "");
@@ -4977,6 +5231,7 @@ var ImaAdsManagerStub = class {
4977
5231
  };
4978
5232
 
4979
5233
  // src/index.ts
5234
+ installImaAutoInterception();
4980
5235
  function getAdsGlobal(alias = DEFAULT_ALIAS) {
4981
5236
  if (typeof window === "undefined") {
4982
5237
  return { q: [] };
@@ -5041,6 +5296,7 @@ function getAdsGlobal(alias = DEFAULT_ALIAS) {
5041
5296
  attachVideoPlayer,
5042
5297
  clearStoredSession,
5043
5298
  clearStoredUserId,
5299
+ detectPrebidGlobals,
5044
5300
  generateUUID,
5045
5301
  getAdsGlobal,
5046
5302
  getOrCreateSessionId,
@@ -5048,7 +5304,9 @@ function getAdsGlobal(alias = DEFAULT_ALIAS) {
5048
5304
  getPrebidEventKey,
5049
5305
  idToBytes,
5050
5306
  idToString,
5307
+ installImaAutoInterception,
5051
5308
  isAutomatedClient,
5309
+ isCanonicalUuid,
5052
5310
  isSessionActive,
5053
5311
  isTrustedEndpoint,
5054
5312
  isVisitorSampled,