@bidspark/analytics 0.46.1 → 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,
@@ -44,6 +45,7 @@ __export(src_exports, {
44
45
  idToString: () => idToString,
45
46
  installImaAutoInterception: () => installImaAutoInterception,
46
47
  isAutomatedClient: () => isAutomatedClient,
48
+ isCanonicalUuid: () => isCanonicalUuid,
47
49
  isSessionActive: () => isSessionActive,
48
50
  isTrustedEndpoint: () => isTrustedEndpoint,
49
51
  isVisitorSampled: () => isVisitorSampled,
@@ -984,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]{
984
986
  var UUID_BYTES = 16;
985
987
  var utf8Encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
986
988
  var utf8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder() : null;
987
- function idToBytes(id) {
988
- if (!id) return new Uint8Array(0);
989
+ function normalizeUuidString(id) {
990
+ if (!id) return null;
989
991
  let clean = id.trim();
990
992
  if (clean.startsWith("{") && clean.endsWith("}")) {
991
993
  clean = clean.slice(1, -1).trim();
992
994
  }
993
995
  const lower = clean.toLowerCase();
994
- 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) {
995
1005
  const hex = lower.replace(/-/g, "");
996
1006
  const out2 = new Uint8Array(UUID_BYTES);
997
1007
  for (let i = 0; i < UUID_BYTES; i++) {
@@ -1455,6 +1465,8 @@ var MAX_CACHED_BID_KEYS = 200;
1455
1465
  var MAX_IMPRESSION_KEYS = 1e3;
1456
1466
  var MAX_TRACKED_AUCTIONS = 50;
1457
1467
  var MAX_FLOOR_DECISIONS = 200;
1468
+ var MAX_SYNTHETIC_AUCTION_MAPPINGS = 200;
1469
+ var MAX_SYNTHETIC_BID_MAPPINGS = 2e3;
1458
1470
  var FLOOR_SOURCE_PROTO = {
1459
1471
  static: FloorSource.FLOOR_SOURCE_STATIC,
1460
1472
  pool: FloorSource.FLOOR_SOURCE_POOL,
@@ -1731,19 +1743,41 @@ function cmpStorageAllowed(alias) {
1731
1743
  function escapeKeyPart(str) {
1732
1744
  return String(str ?? "").replace(/%/g, "%25").replace(/:/g, "%3A");
1733
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
+ }
1734
1767
  function getPrebidEventKey(eventName, data) {
1735
1768
  switch (eventName) {
1736
1769
  case "auctionInit":
1737
- return `auctionInit:${escapeKeyPart(data?.auctionId)}`;
1770
+ return `auctionInit:${escapeKeyPart(data?.auctionId)}${auctionInstanceDiscriminator(data)}`;
1738
1771
  case "auctionEnd":
1739
- return `auctionEnd:${escapeKeyPart(data?.auctionId)}`;
1772
+ return `auctionEnd:${escapeKeyPart(data?.auctionId)}${auctionInstanceDiscriminator(data)}`;
1740
1773
  case "bidRequested": {
1741
1774
  const bids = Array.isArray(data?.bids) ? data.bids.map((b) => escapeKeyPart(b?.bidId || b?.transactionId || b?.adUnitCode)).join(",") : "";
1742
- 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}`;
1743
1777
  }
1744
1778
  case "bidResponse": {
1745
1779
  const bid = data || {};
1746
- const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1780
+ const uniqueBidId = bid.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1747
1781
  const price = bid.originalCpm ?? bid.cpm ?? "";
1748
1782
  return `bidResponse:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1749
1783
  }
@@ -1755,7 +1789,7 @@ function getPrebidEventKey(eventName, data) {
1755
1789
  }
1756
1790
  case "bidWon": {
1757
1791
  const bid = data || {};
1758
- const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1792
+ const uniqueBidId = bid.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1759
1793
  const price = bid.originalCpm ?? bid.cpm ?? "";
1760
1794
  return `bidWon:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1761
1795
  }
@@ -1763,11 +1797,13 @@ function getPrebidEventKey(eventName, data) {
1763
1797
  return `noBid:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.adUnitCode)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${escapeKeyPart(data?.bidId || data?.transactionId)}`;
1764
1798
  case "adRenderFailed": {
1765
1799
  const bid = data?.bid || {};
1766
- 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}`;
1767
1803
  }
1768
1804
  case "adRenderSucceeded": {
1769
1805
  const bid = data?.bid || data || {};
1770
- const uniqueId = bid.creativeId || bid.adId || data?.adId || "";
1806
+ const uniqueId = bid.adId || data?.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1771
1807
  const price = bid.originalCpm ?? bid.cpm ?? "";
1772
1808
  return `adRenderSucceeded:${escapeKeyPart(bid.auctionId || data?.auctionId)}:${escapeKeyPart(bid.adUnitCode || data?.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueId)}:${escapeKeyPart(price)}`;
1773
1809
  }
@@ -1920,6 +1956,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1920
1956
  videoDetachCleanups = /* @__PURE__ */ new Set();
1921
1957
  auctionBidderOutcomes = /* @__PURE__ */ new Map();
1922
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();
1923
1965
  recordedConsentKeys = /* @__PURE__ */ new Set();
1924
1966
  consentCount = 0;
1925
1967
  cmpDetach = null;
@@ -1933,6 +1975,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1933
1975
  managesVisitorId;
1934
1976
  // True once visitorId is settled (storage read, caller-supplied, or first batch drained).
1935
1977
  visitorKeyLocked;
1978
+ hasExplicitPbjsGlobalName;
1936
1979
  constructor(config) {
1937
1980
  const tcfStorage = probeTcfStorageAllowed();
1938
1981
  if (typeof window !== "undefined" && typeof window.__tcfapi === "function") {
@@ -1964,6 +2007,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1964
2007
  }
1965
2008
  this.managesVisitorId = !config.visitorId && !config.userId && !config.sessionId;
1966
2009
  this.visitorKeyLocked = isStorageOn || !this.managesVisitorId;
2010
+ const explicitPbjsGlobal = validPrebidGlobalName(config.pbjsGlobalName);
2011
+ this.hasExplicitPbjsGlobalName = Boolean(explicitPbjsGlobal);
1967
2012
  const usageEndpoint = config.usageEndpoint || "";
1968
2013
  this.config = {
1969
2014
  endpoint,
@@ -1982,7 +2027,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1982
2027
  viewabilityEnabled: config.viewabilityEnabled ?? true,
1983
2028
  storageAllowed: isStorageOn,
1984
2029
  logLevel: config.logLevel ? normalizeLogLevel(config.logLevel) : defaultLogger.getLevel(),
1985
- pbjsGlobalName: config.pbjsGlobalName || "pbjs",
2030
+ pbjsGlobalName: explicitPbjsGlobal || detectPrebidGlobalName(),
1986
2031
  attachPbjsListeners: config.attachPbjsListeners ?? true,
1987
2032
  revenueFlushDelayMs: Number.isFinite(config.revenueFlushDelayMs) && config.revenueFlushDelayMs >= 0 ? config.revenueFlushDelayMs : REVENUE_FLUSH_DELAY_MS,
1988
2033
  alias: config.alias || DEFAULT_ALIAS,
@@ -2099,6 +2144,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2099
2144
  if (!this.isEnabled) return false;
2100
2145
  if (this.boundPbjsHandlers.length > 0) return true;
2101
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
+ }
2102
2150
  const pbjs = win[this.config.pbjsGlobalName] || {};
2103
2151
  if (typeof pbjs.onEvent !== "function") {
2104
2152
  this.log("WARN", "pbjs.onEvent is not defined. Prebid analytics will not function.");
@@ -2191,6 +2239,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2191
2239
  this.slotLastAuctionIds.clear();
2192
2240
  this.auctionBidderOutcomes.clear();
2193
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();
2194
2248
  if (this.flushTimer) {
2195
2249
  clearInterval(this.flushTimer);
2196
2250
  this.flushTimer = null;
@@ -2921,7 +2975,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2921
2975
  }
2922
2976
  }
2923
2977
  floorDecisionFor(auctionId, adUnitCode) {
2924
- 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;
2925
2983
  }
2926
2984
  /**
2927
2985
  * Enqueues one CONSENT event with the record flattened into metadata under snake_case keys.
@@ -3091,10 +3149,117 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3091
3149
  ...typeof bidderCount === "number" ? { metadata: { bidderCount: String(bidderCount) } } : {}
3092
3150
  });
3093
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
+ }
3094
3259
  handleAuctionInit(data) {
3095
3260
  if (this.isDuplicate("auctionInit", data)) return;
3096
3261
  this.log("DEBUG", "auctionInit", data);
3097
- const auctionId = data.auctionId || "";
3262
+ const auctionId = this.startPrebidAuction(data.auctionId || "", data);
3098
3263
  if (auctionId) {
3099
3264
  this.auctionBidderOutcomes.delete(auctionId);
3100
3265
  this.getOrCreateAuctionOutcomes(auctionId);
@@ -3111,7 +3276,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3111
3276
  handleAuctionEnd(data) {
3112
3277
  if (this.isDuplicate("auctionEnd", data)) return;
3113
3278
  this.log("DEBUG", "auctionEnd", data);
3114
- 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
+ });
3115
3285
  const outcomesMap = auctionId ? this.auctionBidderOutcomes.get(auctionId) : void 0;
3116
3286
  const bidderOutcomes = outcomesMap ? Array.from(outcomesMap.values()) : [];
3117
3287
  if (auctionId) {
@@ -3139,7 +3309,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3139
3309
  handleBidRequested(data) {
3140
3310
  if (this.isDuplicate("bidRequested", data)) return;
3141
3311
  this.log("DEBUG", "bidRequested", data);
3142
- 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
+ });
3143
3316
  const bidder = data.bidderCode || data.bidder || "";
3144
3317
  if (!auctionId || !bidder) return;
3145
3318
  const auctionMap = this.getOrCreateAuctionOutcomes(auctionId);
@@ -3162,7 +3335,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3162
3335
  handleBidResponse(data) {
3163
3336
  if (this.isDuplicate("bidResponse", data)) return;
3164
3337
  this.log("DEBUG", "bidResponse", data);
3165
- 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
+ });
3166
3344
  const bidder = data.bidderCode || data.bidder || "";
3167
3345
  const adUnitCode = data.adUnitCode || "";
3168
3346
  const pricing = resolveBidPricing(data);
@@ -3192,7 +3370,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3192
3370
  this.log("DEBUG", "bidTimeout", data);
3193
3371
  const items = Array.isArray(data) ? data : data ? [data] : [];
3194
3372
  for (const t of items) {
3195
- 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
+ });
3196
3377
  const bidder = t.bidderCode || t.bidder || "";
3197
3378
  const adUnitCode = t.adUnitCode || "";
3198
3379
  const latencyMs = Number.isFinite(t.timeout) ? t.timeout : 0;
@@ -3216,8 +3397,17 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3216
3397
  handleBidWon(data) {
3217
3398
  if (this.isDuplicate("bidWon", data)) return;
3218
3399
  this.log("DEBUG", "bidWon", data);
3219
- const auctionId = data.auctionId || "";
3220
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
+ );
3221
3411
  const adUnitCode = data.adUnitCode || data.adId || "";
3222
3412
  const wonMediaTypes = Object.keys(data.mediaTypes || {});
3223
3413
  const resolvedMediaType = data.mediaType || (data.mediaTypes?.video ? "video" : wonMediaTypes.length > 0 ? wonMediaTypes[0] : "banner");
@@ -3262,7 +3452,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3262
3452
  handleNoBid(data) {
3263
3453
  if (this.isDuplicate("noBid", data)) return;
3264
3454
  this.log("DEBUG", "noBid", data);
3265
- 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
+ });
3266
3459
  const bidder = data.bidderCode || data.bidder || "";
3267
3460
  const adUnitCode = data.adUnitCode || "";
3268
3461
  if (auctionId && bidder) {
@@ -3286,9 +3479,19 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3286
3479
  if (this.isDuplicate("adRenderFailed", data)) return;
3287
3480
  this.log("DEBUG", "adRenderFailed", data);
3288
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
+ );
3289
3492
  this.enqueue(TraceEventType.AD_RENDER_FAILED, "adRenderFailed", {
3290
- auctionId: bid.auctionId || data.auctionId || "",
3291
- transactionId: bid.transactionId || data.transactionId || "",
3493
+ auctionId,
3494
+ transactionId,
3292
3495
  adUnitCode: bid.adUnitCode || data.adUnitCode || "",
3293
3496
  bid: {
3294
3497
  bidder: bid.bidderCode || bid.bidder || data.bidderCode || data.bidder || ""
@@ -3307,12 +3510,24 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3307
3510
  this.log("DEBUG", "adRenderSucceeded", data);
3308
3511
  const bid = data.bid || data || {};
3309
3512
  const adUnitCode = data.adUnitCode || bid.adUnitCode || data.adId || bid.adId || "";
3310
- const auctionId = bid.auctionId || data.auctionId || "";
3513
+ const rawAuctionId = bid.auctionId || data.auctionId || "";
3311
3514
  const transactionId = bid.transactionId || data.transactionId || "";
3312
3515
  const mediaType = bid.mediaType || "banner";
3313
3516
  const slotKey = data.adUnitCode || bid.adUnitCode || "";
3314
3517
  const altKey = data.adId || bid.adId || "";
3315
- 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;
3316
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";
3317
3532
  const resolvedMediaType = isVideo ? "video" : mediaType || cached?.bidTrace?.mediaType || "banner";
3318
3533
  const bidTrace = {
@@ -3905,73 +4120,194 @@ function getStashedConfig(win) {
3905
4120
  }
3906
4121
  return null;
3907
4122
  }
3908
- 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) {
3909
4222
  const win = typeof window !== "undefined" ? window : {};
3910
- win[pbjsGlobalName] = win[pbjsGlobalName] || {};
3911
- const pbjs = win[pbjsGlobalName];
3912
- const enableInstance = (options) => {
3913
- const previous = win._bidsparkPrebidAnalytics;
3914
- const pinnedEndpoint = previous?.getEndpoint?.() || "";
3915
- const defaultUsageEndpoint = defaults?.usageEndpoint || "https://by.bidspark.io/u";
3916
- const merged = {
3917
- pbjsGlobalName,
3918
- ...defaults,
3919
- ...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;
3920
4254
  };
3921
- merged.usageEndpoint = defaultUsageEndpoint;
3922
- if (pinnedEndpoint && !sameEndpointOrigin(merged.endpoint || "", pinnedEndpoint)) {
3923
- defaultLogger.warn(
3924
- `Ignoring analytics endpoint change to ${merged.endpoint || "(empty)"}: this page is pinned to ${pinnedEndpoint}. Reload to change the ingest endpoint.`
3925
- );
3926
- merged.endpoint = pinnedEndpoint;
3927
- }
3928
- if (previous) {
4255
+ const doRegister = () => {
3929
4256
  try {
3930
- 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
+ }
3931
4281
  } catch (e) {
3932
- defaultLogger.warn("Failed to disable previous analytics instance:", e);
4282
+ defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
3933
4283
  }
4284
+ };
4285
+ if (getRegisterAnalyticsAdapter(pbjs)) {
4286
+ doRegister();
4287
+ } else {
4288
+ pbjs.que = pbjs.que || [];
4289
+ pbjs.que.push(doRegister);
3934
4290
  }
3935
- const analytics = new BidsparkPrebidAnalytics(merged);
3936
- if (previous && !merged.pageviewId) analytics.continuePageview(previous);
3937
- analytics.enable();
3938
- win._bidsparkPrebidAnalytics = analytics;
3939
- return analytics;
3940
4291
  };
3941
- const doRegister = () => {
3942
- try {
3943
- if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3944
- const adapter = {
3945
- enableAnalytics: (config) => {
3946
- const options = extractAnalyticsOptions(config, !Array.isArray(config));
3947
- if (options) {
3948
- enableInstance(options);
3949
- }
3950
- },
3951
- disableAnalytics: () => {
3952
- if (win._bidsparkPrebidAnalytics) {
3953
- win._bidsparkPrebidAnalytics.disable();
3954
- }
3955
- }
3956
- };
3957
- pbjs.adapterManager.registerAnalyticsAdapter({
3958
- adapter: { ...adapter },
3959
- code: "bidspark"
3960
- });
3961
- }
3962
- const stashed = getStashedConfig(win);
3963
- if (stashed && (stashed.propertyId || defaults?.propertyId)) {
3964
- enableInstance(stashed);
3965
- }
3966
- } catch (e) {
3967
- defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
3968
- }
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);
3969
4302
  };
3970
- if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3971
- doRegister();
4303
+ const detected = detectPrebidGlobals(win);
4304
+ if (detected.length > 0) {
4305
+ for (const name of detected) registerOnce(name);
3972
4306
  } else {
3973
- pbjs.que = pbjs.que || [];
3974
- pbjs.que.push(doRegister);
4307
+ registerOnce("pbjs");
4308
+ }
4309
+ if (typeof window !== "undefined") {
4310
+ watchPrebidGlobals(win, registerOnce);
3975
4311
  }
3976
4312
  }
3977
4313
 
@@ -4960,6 +5296,7 @@ function getAdsGlobal(alias = DEFAULT_ALIAS) {
4960
5296
  attachVideoPlayer,
4961
5297
  clearStoredSession,
4962
5298
  clearStoredUserId,
5299
+ detectPrebidGlobals,
4963
5300
  generateUUID,
4964
5301
  getAdsGlobal,
4965
5302
  getOrCreateSessionId,
@@ -4969,6 +5306,7 @@ function getAdsGlobal(alias = DEFAULT_ALIAS) {
4969
5306
  idToString,
4970
5307
  installImaAutoInterception,
4971
5308
  isAutomatedClient,
5309
+ isCanonicalUuid,
4972
5310
  isSessionActive,
4973
5311
  isTrustedEndpoint,
4974
5312
  isVisitorSampled,