@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.mjs CHANGED
@@ -931,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]{
931
931
  var UUID_BYTES = 16;
932
932
  var utf8Encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
933
933
  var utf8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder() : null;
934
- function idToBytes(id) {
935
- if (!id) return new Uint8Array(0);
934
+ function normalizeUuidString(id) {
935
+ if (!id) return null;
936
936
  let clean = id.trim();
937
937
  if (clean.startsWith("{") && clean.endsWith("}")) {
938
938
  clean = clean.slice(1, -1).trim();
939
939
  }
940
940
  const lower = clean.toLowerCase();
941
- 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) {
942
950
  const hex = lower.replace(/-/g, "");
943
951
  const out2 = new Uint8Array(UUID_BYTES);
944
952
  for (let i = 0; i < UUID_BYTES; i++) {
@@ -1402,6 +1410,8 @@ var MAX_CACHED_BID_KEYS = 200;
1402
1410
  var MAX_IMPRESSION_KEYS = 1e3;
1403
1411
  var MAX_TRACKED_AUCTIONS = 50;
1404
1412
  var MAX_FLOOR_DECISIONS = 200;
1413
+ var MAX_SYNTHETIC_AUCTION_MAPPINGS = 200;
1414
+ var MAX_SYNTHETIC_BID_MAPPINGS = 2e3;
1405
1415
  var FLOOR_SOURCE_PROTO = {
1406
1416
  static: FloorSource.FLOOR_SOURCE_STATIC,
1407
1417
  pool: FloorSource.FLOOR_SOURCE_POOL,
@@ -1678,19 +1688,41 @@ function cmpStorageAllowed(alias) {
1678
1688
  function escapeKeyPart(str) {
1679
1689
  return String(str ?? "").replace(/%/g, "%25").replace(/:/g, "%3A");
1680
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
+ }
1681
1712
  function getPrebidEventKey(eventName, data) {
1682
1713
  switch (eventName) {
1683
1714
  case "auctionInit":
1684
- return `auctionInit:${escapeKeyPart(data?.auctionId)}`;
1715
+ return `auctionInit:${escapeKeyPart(data?.auctionId)}${auctionInstanceDiscriminator(data)}`;
1685
1716
  case "auctionEnd":
1686
- return `auctionEnd:${escapeKeyPart(data?.auctionId)}`;
1717
+ return `auctionEnd:${escapeKeyPart(data?.auctionId)}${auctionInstanceDiscriminator(data)}`;
1687
1718
  case "bidRequested": {
1688
1719
  const bids = Array.isArray(data?.bids) ? data.bids.map((b) => escapeKeyPart(b?.bidId || b?.transactionId || b?.adUnitCode)).join(",") : "";
1689
- 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}`;
1690
1722
  }
1691
1723
  case "bidResponse": {
1692
1724
  const bid = data || {};
1693
- const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1725
+ const uniqueBidId = bid.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1694
1726
  const price = bid.originalCpm ?? bid.cpm ?? "";
1695
1727
  return `bidResponse:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1696
1728
  }
@@ -1702,7 +1734,7 @@ function getPrebidEventKey(eventName, data) {
1702
1734
  }
1703
1735
  case "bidWon": {
1704
1736
  const bid = data || {};
1705
- const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1737
+ const uniqueBidId = bid.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1706
1738
  const price = bid.originalCpm ?? bid.cpm ?? "";
1707
1739
  return `bidWon:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1708
1740
  }
@@ -1710,11 +1742,13 @@ function getPrebidEventKey(eventName, data) {
1710
1742
  return `noBid:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.adUnitCode)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${escapeKeyPart(data?.bidId || data?.transactionId)}`;
1711
1743
  case "adRenderFailed": {
1712
1744
  const bid = data?.bid || {};
1713
- 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}`;
1714
1748
  }
1715
1749
  case "adRenderSucceeded": {
1716
1750
  const bid = data?.bid || data || {};
1717
- const uniqueId = bid.creativeId || bid.adId || data?.adId || "";
1751
+ const uniqueId = bid.adId || data?.adId || bid.requestId || bid.bidId || bid.creativeId || "";
1718
1752
  const price = bid.originalCpm ?? bid.cpm ?? "";
1719
1753
  return `adRenderSucceeded:${escapeKeyPart(bid.auctionId || data?.auctionId)}:${escapeKeyPart(bid.adUnitCode || data?.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueId)}:${escapeKeyPart(price)}`;
1720
1754
  }
@@ -1867,6 +1901,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1867
1901
  videoDetachCleanups = /* @__PURE__ */ new Set();
1868
1902
  auctionBidderOutcomes = /* @__PURE__ */ new Map();
1869
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();
1870
1910
  recordedConsentKeys = /* @__PURE__ */ new Set();
1871
1911
  consentCount = 0;
1872
1912
  cmpDetach = null;
@@ -1880,6 +1920,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1880
1920
  managesVisitorId;
1881
1921
  // True once visitorId is settled (storage read, caller-supplied, or first batch drained).
1882
1922
  visitorKeyLocked;
1923
+ hasExplicitPbjsGlobalName;
1883
1924
  constructor(config) {
1884
1925
  const tcfStorage = probeTcfStorageAllowed();
1885
1926
  if (typeof window !== "undefined" && typeof window.__tcfapi === "function") {
@@ -1911,6 +1952,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1911
1952
  }
1912
1953
  this.managesVisitorId = !config.visitorId && !config.userId && !config.sessionId;
1913
1954
  this.visitorKeyLocked = isStorageOn || !this.managesVisitorId;
1955
+ const explicitPbjsGlobal = validPrebidGlobalName(config.pbjsGlobalName);
1956
+ this.hasExplicitPbjsGlobalName = Boolean(explicitPbjsGlobal);
1914
1957
  const usageEndpoint = config.usageEndpoint || "";
1915
1958
  this.config = {
1916
1959
  endpoint,
@@ -1929,7 +1972,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1929
1972
  viewabilityEnabled: config.viewabilityEnabled ?? true,
1930
1973
  storageAllowed: isStorageOn,
1931
1974
  logLevel: config.logLevel ? normalizeLogLevel(config.logLevel) : defaultLogger.getLevel(),
1932
- pbjsGlobalName: config.pbjsGlobalName || "pbjs",
1975
+ pbjsGlobalName: explicitPbjsGlobal || detectPrebidGlobalName(),
1933
1976
  attachPbjsListeners: config.attachPbjsListeners ?? true,
1934
1977
  revenueFlushDelayMs: Number.isFinite(config.revenueFlushDelayMs) && config.revenueFlushDelayMs >= 0 ? config.revenueFlushDelayMs : REVENUE_FLUSH_DELAY_MS,
1935
1978
  alias: config.alias || DEFAULT_ALIAS,
@@ -2046,6 +2089,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2046
2089
  if (!this.isEnabled) return false;
2047
2090
  if (this.boundPbjsHandlers.length > 0) return true;
2048
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
+ }
2049
2095
  const pbjs = win[this.config.pbjsGlobalName] || {};
2050
2096
  if (typeof pbjs.onEvent !== "function") {
2051
2097
  this.log("WARN", "pbjs.onEvent is not defined. Prebid analytics will not function.");
@@ -2138,6 +2184,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2138
2184
  this.slotLastAuctionIds.clear();
2139
2185
  this.auctionBidderOutcomes.clear();
2140
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();
2141
2193
  if (this.flushTimer) {
2142
2194
  clearInterval(this.flushTimer);
2143
2195
  this.flushTimer = null;
@@ -2868,7 +2920,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2868
2920
  }
2869
2921
  }
2870
2922
  floorDecisionFor(auctionId, adUnitCode) {
2871
- 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;
2872
2928
  }
2873
2929
  /**
2874
2930
  * Enqueues one CONSENT event with the record flattened into metadata under snake_case keys.
@@ -3038,10 +3094,117 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3038
3094
  ...typeof bidderCount === "number" ? { metadata: { bidderCount: String(bidderCount) } } : {}
3039
3095
  });
3040
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
+ }
3041
3204
  handleAuctionInit(data) {
3042
3205
  if (this.isDuplicate("auctionInit", data)) return;
3043
3206
  this.log("DEBUG", "auctionInit", data);
3044
- const auctionId = data.auctionId || "";
3207
+ const auctionId = this.startPrebidAuction(data.auctionId || "", data);
3045
3208
  if (auctionId) {
3046
3209
  this.auctionBidderOutcomes.delete(auctionId);
3047
3210
  this.getOrCreateAuctionOutcomes(auctionId);
@@ -3058,7 +3221,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3058
3221
  handleAuctionEnd(data) {
3059
3222
  if (this.isDuplicate("auctionEnd", data)) return;
3060
3223
  this.log("DEBUG", "auctionEnd", data);
3061
- 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
+ });
3062
3230
  const outcomesMap = auctionId ? this.auctionBidderOutcomes.get(auctionId) : void 0;
3063
3231
  const bidderOutcomes = outcomesMap ? Array.from(outcomesMap.values()) : [];
3064
3232
  if (auctionId) {
@@ -3086,7 +3254,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3086
3254
  handleBidRequested(data) {
3087
3255
  if (this.isDuplicate("bidRequested", data)) return;
3088
3256
  this.log("DEBUG", "bidRequested", data);
3089
- 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
+ });
3090
3261
  const bidder = data.bidderCode || data.bidder || "";
3091
3262
  if (!auctionId || !bidder) return;
3092
3263
  const auctionMap = this.getOrCreateAuctionOutcomes(auctionId);
@@ -3109,7 +3280,12 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3109
3280
  handleBidResponse(data) {
3110
3281
  if (this.isDuplicate("bidResponse", data)) return;
3111
3282
  this.log("DEBUG", "bidResponse", data);
3112
- 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
+ });
3113
3289
  const bidder = data.bidderCode || data.bidder || "";
3114
3290
  const adUnitCode = data.adUnitCode || "";
3115
3291
  const pricing = resolveBidPricing(data);
@@ -3139,7 +3315,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3139
3315
  this.log("DEBUG", "bidTimeout", data);
3140
3316
  const items = Array.isArray(data) ? data : data ? [data] : [];
3141
3317
  for (const t of items) {
3142
- 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
+ });
3143
3322
  const bidder = t.bidderCode || t.bidder || "";
3144
3323
  const adUnitCode = t.adUnitCode || "";
3145
3324
  const latencyMs = Number.isFinite(t.timeout) ? t.timeout : 0;
@@ -3163,8 +3342,17 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3163
3342
  handleBidWon(data) {
3164
3343
  if (this.isDuplicate("bidWon", data)) return;
3165
3344
  this.log("DEBUG", "bidWon", data);
3166
- const auctionId = data.auctionId || "";
3167
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
+ );
3168
3356
  const adUnitCode = data.adUnitCode || data.adId || "";
3169
3357
  const wonMediaTypes = Object.keys(data.mediaTypes || {});
3170
3358
  const resolvedMediaType = data.mediaType || (data.mediaTypes?.video ? "video" : wonMediaTypes.length > 0 ? wonMediaTypes[0] : "banner");
@@ -3209,7 +3397,10 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3209
3397
  handleNoBid(data) {
3210
3398
  if (this.isDuplicate("noBid", data)) return;
3211
3399
  this.log("DEBUG", "noBid", data);
3212
- 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
+ });
3213
3404
  const bidder = data.bidderCode || data.bidder || "";
3214
3405
  const adUnitCode = data.adUnitCode || "";
3215
3406
  if (auctionId && bidder) {
@@ -3233,9 +3424,19 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3233
3424
  if (this.isDuplicate("adRenderFailed", data)) return;
3234
3425
  this.log("DEBUG", "adRenderFailed", data);
3235
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
+ );
3236
3437
  this.enqueue(TraceEventType.AD_RENDER_FAILED, "adRenderFailed", {
3237
- auctionId: bid.auctionId || data.auctionId || "",
3238
- transactionId: bid.transactionId || data.transactionId || "",
3438
+ auctionId,
3439
+ transactionId,
3239
3440
  adUnitCode: bid.adUnitCode || data.adUnitCode || "",
3240
3441
  bid: {
3241
3442
  bidder: bid.bidderCode || bid.bidder || data.bidderCode || data.bidder || ""
@@ -3254,12 +3455,24 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3254
3455
  this.log("DEBUG", "adRenderSucceeded", data);
3255
3456
  const bid = data.bid || data || {};
3256
3457
  const adUnitCode = data.adUnitCode || bid.adUnitCode || data.adId || bid.adId || "";
3257
- const auctionId = bid.auctionId || data.auctionId || "";
3458
+ const rawAuctionId = bid.auctionId || data.auctionId || "";
3258
3459
  const transactionId = bid.transactionId || data.transactionId || "";
3259
3460
  const mediaType = bid.mediaType || "banner";
3260
3461
  const slotKey = data.adUnitCode || bid.adUnitCode || "";
3261
3462
  const altKey = data.adId || bid.adId || "";
3262
- 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;
3263
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";
3264
3477
  const resolvedMediaType = isVideo ? "video" : mediaType || cached?.bidTrace?.mediaType || "banner";
3265
3478
  const bidTrace = {
@@ -3852,73 +4065,194 @@ function getStashedConfig(win) {
3852
4065
  }
3853
4066
  return null;
3854
4067
  }
3855
- 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) {
3856
4167
  const win = typeof window !== "undefined" ? window : {};
3857
- win[pbjsGlobalName] = win[pbjsGlobalName] || {};
3858
- const pbjs = win[pbjsGlobalName];
3859
- const enableInstance = (options) => {
3860
- const previous = win._bidsparkPrebidAnalytics;
3861
- const pinnedEndpoint = previous?.getEndpoint?.() || "";
3862
- const defaultUsageEndpoint = defaults?.usageEndpoint || "https://by.bidspark.io/u";
3863
- const merged = {
3864
- pbjsGlobalName,
3865
- ...defaults,
3866
- ...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;
3867
4199
  };
3868
- merged.usageEndpoint = defaultUsageEndpoint;
3869
- if (pinnedEndpoint && !sameEndpointOrigin(merged.endpoint || "", pinnedEndpoint)) {
3870
- defaultLogger.warn(
3871
- `Ignoring analytics endpoint change to ${merged.endpoint || "(empty)"}: this page is pinned to ${pinnedEndpoint}. Reload to change the ingest endpoint.`
3872
- );
3873
- merged.endpoint = pinnedEndpoint;
3874
- }
3875
- if (previous) {
4200
+ const doRegister = () => {
3876
4201
  try {
3877
- 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
+ }
3878
4226
  } catch (e) {
3879
- defaultLogger.warn("Failed to disable previous analytics instance:", e);
4227
+ defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
3880
4228
  }
4229
+ };
4230
+ if (getRegisterAnalyticsAdapter(pbjs)) {
4231
+ doRegister();
4232
+ } else {
4233
+ pbjs.que = pbjs.que || [];
4234
+ pbjs.que.push(doRegister);
3881
4235
  }
3882
- const analytics = new BidsparkPrebidAnalytics(merged);
3883
- if (previous && !merged.pageviewId) analytics.continuePageview(previous);
3884
- analytics.enable();
3885
- win._bidsparkPrebidAnalytics = analytics;
3886
- return analytics;
3887
4236
  };
3888
- const doRegister = () => {
3889
- try {
3890
- if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3891
- const adapter = {
3892
- enableAnalytics: (config) => {
3893
- const options = extractAnalyticsOptions(config, !Array.isArray(config));
3894
- if (options) {
3895
- enableInstance(options);
3896
- }
3897
- },
3898
- disableAnalytics: () => {
3899
- if (win._bidsparkPrebidAnalytics) {
3900
- win._bidsparkPrebidAnalytics.disable();
3901
- }
3902
- }
3903
- };
3904
- pbjs.adapterManager.registerAnalyticsAdapter({
3905
- adapter: { ...adapter },
3906
- code: "bidspark"
3907
- });
3908
- }
3909
- const stashed = getStashedConfig(win);
3910
- if (stashed && (stashed.propertyId || defaults?.propertyId)) {
3911
- enableInstance(stashed);
3912
- }
3913
- } catch (e) {
3914
- defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
3915
- }
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);
3916
4247
  };
3917
- if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3918
- doRegister();
4248
+ const detected = detectPrebidGlobals(win);
4249
+ if (detected.length > 0) {
4250
+ for (const name of detected) registerOnce(name);
3919
4251
  } else {
3920
- pbjs.que = pbjs.que || [];
3921
- pbjs.que.push(doRegister);
4252
+ registerOnce("pbjs");
4253
+ }
4254
+ if (typeof window !== "undefined") {
4255
+ watchPrebidGlobals(win, registerOnce);
3922
4256
  }
3923
4257
  }
3924
4258
 
@@ -4906,6 +5240,7 @@ export {
4906
5240
  attachVideoPlayer,
4907
5241
  clearStoredSession,
4908
5242
  clearStoredUserId,
5243
+ detectPrebidGlobals,
4909
5244
  generateUUID,
4910
5245
  getAdsGlobal,
4911
5246
  getOrCreateSessionId,
@@ -4915,6 +5250,7 @@ export {
4915
5250
  idToString,
4916
5251
  installImaAutoInterception,
4917
5252
  isAutomatedClient,
5253
+ isCanonicalUuid,
4918
5254
  isSessionActive,
4919
5255
  isTrustedEndpoint,
4920
5256
  isVisitorSampled,