@bidspark/analytics 0.45.2 → 0.46.1

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
@@ -42,6 +42,7 @@ __export(src_exports, {
42
42
  getPrebidEventKey: () => getPrebidEventKey,
43
43
  idToBytes: () => idToBytes,
44
44
  idToString: () => idToString,
45
+ installImaAutoInterception: () => installImaAutoInterception,
45
46
  isAutomatedClient: () => isAutomatedClient,
46
47
  isSessionActive: () => isSessionActive,
47
48
  isTrustedEndpoint: () => isTrustedEndpoint,
@@ -79,18 +80,6 @@ var COLORS = {
79
80
  eventError: "color: #ef4444; font-weight: bold",
80
81
  reset: "color: inherit"
81
82
  };
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
83
  function formatTime(ms) {
95
84
  if (ms < 0 || !Number.isFinite(ms)) ms = 0;
96
85
  if (ms < 1e3) return `${ms.toFixed(2)}ms`;
@@ -116,15 +105,11 @@ var Logger = class {
116
105
  _loadedAt;
117
106
  _now;
118
107
  _console;
119
- _listeners = /* @__PURE__ */ new Set();
120
108
  constructor(options = {}) {
121
109
  this._prefix = options.prefix ?? "[ads]";
122
110
  this._level = normalizeLogLevel(options.logLevel ?? LogLevel.INFO);
123
111
  this._now = options.now;
124
112
  this._console = options.console;
125
- if (options.onLog) {
126
- this._listeners.add(options.onLog);
127
- }
128
113
  this._loadedAt = options.loadedAt ?? (this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now());
129
114
  }
130
115
  get prefix() {
@@ -157,15 +142,6 @@ var Logger = class {
157
142
  getLoadedAt() {
158
143
  return this._loadedAt;
159
144
  }
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
145
  isEnabled(level) {
170
146
  const target = normalizeLogLevel(level);
171
147
  return (LOG_LEVEL_MAP[target] ?? 20) >= (LOG_LEVEL_MAP[this._level] ?? 20);
@@ -179,23 +155,6 @@ var Logger = class {
179
155
  const current = this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
180
156
  return Math.max(0, current - this._loadedAt);
181
157
  }
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
158
  log(level, nameOrMsg, ...args) {
200
159
  const normLevel = normalizeLogLevel(level);
201
160
  if (!this.isEnabled(normLevel)) {
@@ -203,19 +162,6 @@ var Logger = class {
203
162
  }
204
163
  const elapsed = this._getElapsed();
205
164
  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
165
  const c = this._getConsole();
220
166
  if (!c) return;
221
167
  let badgeStyle = COLORS.badge;
@@ -1518,9 +1464,11 @@ var CLICK_DEDUP_MS = 1e3;
1518
1464
  var SESSION_KEY = "ads_session";
1519
1465
  var SESSION_TS_KEY = "ads_session_ts";
1520
1466
  var THIRTY_MINUTES_MS = 30 * 60 * 1e3;
1467
+ var PAGE_EVENT_NAME_RE = /^[a-zA-Z0-9:_.-]{1,64}$/;
1521
1468
  var inMemorySessionId = null;
1522
1469
  var inMemorySessionTs = 0;
1523
1470
  var sessionStartedHere = false;
1471
+ var announcedSessionId = "";
1524
1472
  var storageAllowed = true;
1525
1473
  function generateUUID2() {
1526
1474
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
@@ -1975,6 +1923,7 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1975
1923
  recordedConsentKeys = /* @__PURE__ */ new Set();
1976
1924
  consentCount = 0;
1977
1925
  cmpDetach = null;
1926
+ sessionResumeUnsub = null;
1978
1927
  pageviewEmitted = false;
1979
1928
  logger;
1980
1929
  // True when managing session lifecycle internally; false if caller supplied fixed sessionId.
@@ -2036,7 +1985,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2036
1985
  pbjsGlobalName: config.pbjsGlobalName || "pbjs",
2037
1986
  attachPbjsListeners: config.attachPbjsListeners ?? true,
2038
1987
  revenueFlushDelayMs: Number.isFinite(config.revenueFlushDelayMs) && config.revenueFlushDelayMs >= 0 ? config.revenueFlushDelayMs : REVENUE_FLUSH_DELAY_MS,
2039
- alias: config.alias || DEFAULT_ALIAS
1988
+ alias: config.alias || DEFAULT_ALIAS,
1989
+ events: config.events || {}
2040
1990
  };
2041
1991
  _BidsparkPrebidAnalytics.allInstances.add(this);
2042
1992
  this.logger = createLogger({
@@ -2130,8 +2080,11 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2130
2080
  document.addEventListener("visibilitychange", this.boundVisibilityChange);
2131
2081
  }
2132
2082
  bindActivityListeners();
2083
+ this.sessionResumeUnsub = onSessionResume(() => this.syncSessionAndRotateVisitor());
2084
+ this.syncSessionId();
2133
2085
  if (!this.pageviewEmitted) {
2134
2086
  this.pageviewEmitted = true;
2087
+ this.emitPageEvent("pageview");
2135
2088
  this.enqueue(TraceEventType.PAGEVIEW, "pageview", {});
2136
2089
  }
2137
2090
  this.flushTimer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
@@ -2273,6 +2226,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
2273
2226
  }
2274
2227
  this.cmpDetach = null;
2275
2228
  }
2229
+ this.sessionResumeUnsub?.();
2230
+ this.sessionResumeUnsub = null;
2276
2231
  this.flush();
2277
2232
  }
2278
2233
  handleVisibilityChange() {
@@ -3078,6 +3033,9 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3078
3033
  setSampleRate(sampleRate) {
3079
3034
  this.config.sampleRate = normalizeSampleRate(sampleRate);
3080
3035
  }
3036
+ setEvents(events) {
3037
+ this.config.events = events || {};
3038
+ }
3081
3039
  setSessionId(sessionId) {
3082
3040
  this.config.sessionId = sessionId;
3083
3041
  this.managesSessionId = !sessionId;
@@ -3120,12 +3078,8 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3120
3078
  this.config.pageviewId = pageviewId || generateUUID2();
3121
3079
  this.pageUrl = nextPageUrl;
3122
3080
  this.logger.resetTiming();
3123
- const prevSessionId = this.config.sessionId;
3124
3081
  recordActivity();
3125
- this.syncSessionId();
3126
- if (!this.config.visitorId || this.config.sessionId !== prevSessionId && this.config.visitorId === prevSessionId) {
3127
- this.config.visitorId = this.config.userId || this.config.sessionId;
3128
- }
3082
+ this.syncSessionAndRotateVisitor();
3129
3083
  this.enable();
3130
3084
  }
3131
3085
  recordAuctionStart(auctionId, adUnitCode = "", bidderCount, mediaType) {
@@ -3568,6 +3522,55 @@ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
3568
3522
  syncSessionId() {
3569
3523
  if (!this.managesSessionId) return;
3570
3524
  this.config.sessionId = sessionNeedsSync() ? getOrCreateSessionId() : inMemorySessionId;
3525
+ this.announceSession();
3526
+ }
3527
+ syncSessionAndRotateVisitor() {
3528
+ const prevSessionId = this.config.sessionId;
3529
+ this.syncSessionId();
3530
+ if (!this.config.visitorId || this.config.sessionId !== prevSessionId && this.config.visitorId === prevSessionId) {
3531
+ this.config.visitorId = this.config.userId || this.config.sessionId;
3532
+ }
3533
+ }
3534
+ announceSession() {
3535
+ if (!this.isEnabled || !this.managesSessionId || !sessionStartedHere || this.config.sessionId === announcedSessionId) {
3536
+ return;
3537
+ }
3538
+ announcedSessionId = this.config.sessionId;
3539
+ this.emitPageEvent("session");
3540
+ }
3541
+ emitPageEvent(key) {
3542
+ const detail = {
3543
+ pageviewId: this.config.pageviewId,
3544
+ sessionId: this.config.sessionId
3545
+ };
3546
+ const configured = this.config.events?.[key];
3547
+ if (typeof configured === "function") {
3548
+ try {
3549
+ configured(detail);
3550
+ } catch (e) {
3551
+ this.log("ERROR", `Error in ${key} event handler`, e);
3552
+ }
3553
+ return;
3554
+ }
3555
+ const defaultName = `${this.config.alias}:${key}`;
3556
+ let eventName = defaultName;
3557
+ const trimmed = typeof configured === "string" ? configured.trim() : "";
3558
+ if (trimmed) {
3559
+ if (PAGE_EVENT_NAME_RE.test(trimmed) && (!trimmed.startsWith("ads:") || trimmed === defaultName)) {
3560
+ eventName = trimmed;
3561
+ } else {
3562
+ this.log(
3563
+ "WARN",
3564
+ `Invalid ${key} event name "${configured}"; falling back to "${defaultName}".`
3565
+ );
3566
+ }
3567
+ }
3568
+ if (typeof window === "undefined" || typeof window.dispatchEvent !== "function") return;
3569
+ try {
3570
+ window.dispatchEvent(new CustomEvent(eventName, { detail }));
3571
+ } catch (e) {
3572
+ this.log("ERROR", `Failed to dispatch ${eventName} event`, e);
3573
+ }
3571
3574
  }
3572
3575
  isSampledVisitor() {
3573
3576
  const key = this.config.visitorId || this.config.sessionId;
@@ -3976,6 +3979,8 @@ function registerPrebidAnalytics(pbjsGlobalName = "pbjs", defaults) {
3976
3979
  var internals = (analytics) => analytics;
3977
3980
  var adsLoaderListenerMap = /* @__PURE__ */ new WeakMap();
3978
3981
  var adsLoadersWithErrorListener = /* @__PURE__ */ new WeakSet();
3982
+ var hookedImaFns = /* @__PURE__ */ new WeakSet();
3983
+ var attachedImaManagers = /* @__PURE__ */ new WeakMap();
3979
3984
  function describeImaError(event) {
3980
3985
  const err = typeof event?.getError === "function" ? event.getError() : event?.error || event;
3981
3986
  const call = (name) => err && typeof err[name] === "function" ? err[name]() : void 0;
@@ -4035,7 +4040,7 @@ function hookAdsManagerLoadedEvent(loadedEventCtor) {
4035
4040
  if (!loadedEventCtor) return;
4036
4041
  try {
4037
4042
  const loadedProto = loadedEventCtor.prototype;
4038
- if (loadedProto && typeof loadedProto.getAdsManager === "function" && !loadedProto.getAdsManager.__bidsparkHooked) {
4043
+ if (loadedProto && typeof loadedProto.getAdsManager === "function" && !hookedImaFns.has(loadedProto.getAdsManager)) {
4039
4044
  const originalGetAdsManager = loadedProto.getAdsManager;
4040
4045
  const hookedGetAdsManager = function(...args) {
4041
4046
  const adsManager = originalGetAdsManager.apply(this, args);
@@ -4049,7 +4054,7 @@ function hookAdsManagerLoadedEvent(loadedEventCtor) {
4049
4054
  }
4050
4055
  return adsManager;
4051
4056
  };
4052
- hookedGetAdsManager.__bidsparkHooked = true;
4057
+ hookedImaFns.add(hookedGetAdsManager);
4053
4058
  loadedProto.getAdsManager = hookedGetAdsManager;
4054
4059
  }
4055
4060
  } catch {
@@ -4059,7 +4064,7 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4059
4064
  if (!adsManagerCtorOrProto) return;
4060
4065
  try {
4061
4066
  const proto = adsManagerCtorOrProto.prototype || adsManagerCtorOrProto;
4062
- if (proto && typeof proto.init === "function" && !proto.init.__bidsparkHooked) {
4067
+ if (proto && typeof proto.init === "function" && !hookedImaFns.has(proto.init)) {
4063
4068
  const origInit = proto.init;
4064
4069
  const hookedInit = function(...args) {
4065
4070
  for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4070,10 +4075,10 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4070
4075
  }
4071
4076
  return origInit.apply(this, args);
4072
4077
  };
4073
- hookedInit.__bidsparkHooked = true;
4078
+ hookedImaFns.add(hookedInit);
4074
4079
  proto.init = hookedInit;
4075
4080
  }
4076
- if (proto && typeof proto.start === "function" && !proto.start.__bidsparkHooked) {
4081
+ if (proto && typeof proto.start === "function" && !hookedImaFns.has(proto.start)) {
4077
4082
  const origStart = proto.start;
4078
4083
  const hookedStart = function(...args) {
4079
4084
  for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4084,7 +4089,7 @@ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
4084
4089
  }
4085
4090
  return origStart.apply(this, args);
4086
4091
  };
4087
- hookedStart.__bidsparkHooked = true;
4092
+ hookedImaFns.add(hookedStart);
4088
4093
  proto.start = hookedStart;
4089
4094
  }
4090
4095
  } catch {
@@ -4095,7 +4100,7 @@ function hookAdsLoader(adsLoaderCtor) {
4095
4100
  try {
4096
4101
  const proto = adsLoaderCtor.prototype;
4097
4102
  if (!proto) return;
4098
- if (typeof proto.addEventListener === "function" && !proto.addEventListener.__bidsparkHooked) {
4103
+ if (typeof proto.addEventListener === "function" && !hookedImaFns.has(proto.addEventListener)) {
4099
4104
  const origAddEventListener = proto.addEventListener;
4100
4105
  const hookedAddEventListener = function(type, listener, ...rest) {
4101
4106
  ensureAdsLoaderErrorListener(this, origAddEventListener);
@@ -4103,9 +4108,9 @@ function hookAdsLoader(adsLoaderCtor) {
4103
4108
  let wrappedListener = adsLoaderListenerMap.get(listener);
4104
4109
  if (!wrappedListener) {
4105
4110
  wrappedListener = function(event) {
4106
- if (event && typeof event.getAdsManager === "function" && !event.getAdsManager.__bidsparkHooked) {
4111
+ if (event && typeof event.getAdsManager === "function" && !hookedImaFns.has(event.getAdsManager)) {
4107
4112
  const origGetAdsManager = event.getAdsManager;
4108
- event.getAdsManager = function(...args) {
4113
+ const hookedGetAdsManager = function(...args) {
4109
4114
  const adsManager = origGetAdsManager.apply(this, args);
4110
4115
  if (adsManager) {
4111
4116
  for (const sdk of BidsparkPrebidAnalytics.getActiveInstances()) {
@@ -4117,7 +4122,8 @@ function hookAdsLoader(adsLoaderCtor) {
4117
4122
  }
4118
4123
  return adsManager;
4119
4124
  };
4120
- event.getAdsManager.__bidsparkHooked = true;
4125
+ hookedImaFns.add(hookedGetAdsManager);
4126
+ event.getAdsManager = hookedGetAdsManager;
4121
4127
  }
4122
4128
  return listener.apply(this, arguments);
4123
4129
  };
@@ -4127,16 +4133,16 @@ function hookAdsLoader(adsLoaderCtor) {
4127
4133
  }
4128
4134
  return origAddEventListener.call(this, type, listener, ...rest);
4129
4135
  };
4130
- hookedAddEventListener.__bidsparkHooked = true;
4136
+ hookedImaFns.add(hookedAddEventListener);
4131
4137
  proto.addEventListener = hookedAddEventListener;
4132
4138
  }
4133
- if (typeof proto.removeEventListener === "function" && !proto.removeEventListener.__bidsparkHooked) {
4139
+ if (typeof proto.removeEventListener === "function" && !hookedImaFns.has(proto.removeEventListener)) {
4134
4140
  const origRemoveEventListener = proto.removeEventListener;
4135
4141
  const hookedRemoveEventListener = function(type, listener, ...rest) {
4136
4142
  const wrapped = typeof listener === "function" ? adsLoaderListenerMap.get(listener) : void 0;
4137
4143
  return origRemoveEventListener.call(this, type, wrapped || listener, ...rest);
4138
4144
  };
4139
- hookedRemoveEventListener.__bidsparkHooked = true;
4145
+ hookedImaFns.add(hookedRemoveEventListener);
4140
4146
  proto.removeEventListener = hookedRemoveEventListener;
4141
4147
  }
4142
4148
  } catch {
@@ -4278,9 +4284,6 @@ function initImaInterception() {
4278
4284
  }
4279
4285
  }
4280
4286
  }
4281
- if (typeof window !== "undefined") {
4282
- initImaInterception();
4283
- }
4284
4287
  function findCachedWinningBid(analytics, filter) {
4285
4288
  const self = internals(analytics);
4286
4289
  const now = Date.now();
@@ -4351,18 +4354,11 @@ function attachImaAdsManager(analytics, adsManager, options) {
4351
4354
  return () => {
4352
4355
  };
4353
4356
  }
4354
- if (!adsManager.__bidsparkAttachedInstances) {
4355
- try {
4356
- Object.defineProperty(adsManager, "__bidsparkAttachedInstances", {
4357
- value: /* @__PURE__ */ new Map(),
4358
- configurable: true,
4359
- writable: true
4360
- });
4361
- } catch {
4362
- adsManager.__bidsparkAttachedInstances = /* @__PURE__ */ new Map();
4363
- }
4357
+ let attached = attachedImaManagers.get(adsManager);
4358
+ if (!attached) {
4359
+ attached = /* @__PURE__ */ new Map();
4360
+ attachedImaManagers.set(adsManager, attached);
4364
4361
  }
4365
- const attached = adsManager.__bidsparkAttachedInstances;
4366
4362
  const previous = attached.get(analytics);
4367
4363
  if (previous) {
4368
4364
  if (!options) return () => {
@@ -4574,7 +4570,9 @@ function attachImaAdsManager(analytics, adsManager, options) {
4574
4570
  }
4575
4571
  const cleanup = () => {
4576
4572
  activeAdSession = null;
4577
- attached.delete(analytics);
4573
+ if (attached.get(analytics) === cleanup) {
4574
+ attached.delete(analytics);
4575
+ }
4578
4576
  for (const { type, handler } of listeners) {
4579
4577
  try {
4580
4578
  adsManager.removeEventListener(type, handler);
@@ -4619,14 +4617,22 @@ function attachVideoPlayer(analytics, target, options) {
4619
4617
  const getWinningBid = () => {
4620
4618
  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);
4621
4619
  };
4622
- let videoEl = null;
4623
- if (el) {
4624
- if (el.tagName && el.tagName.toLowerCase() === "video") {
4625
- videoEl = el;
4626
- } else {
4627
- videoEl = el.querySelector("video");
4620
+ const isVideoEl = Boolean(el?.tagName && el.tagName.toLowerCase() === "video");
4621
+ const resolveTargetVideo = (e) => {
4622
+ const target2 = e?.target;
4623
+ if (target2 && (typeof HTMLVideoElement !== "undefined" && target2 instanceof HTMLVideoElement || target2.tagName?.toLowerCase() === "video")) {
4624
+ return target2;
4628
4625
  }
4629
- }
4626
+ if (target2 && typeof target2.closest === "function") {
4627
+ const parentVideo = target2.closest("video");
4628
+ if (parentVideo) return parentVideo;
4629
+ }
4630
+ if (target2 && target2 !== el) {
4631
+ return null;
4632
+ }
4633
+ return isVideoEl ? el : el?.querySelector?.("video") ?? null;
4634
+ };
4635
+ const isForeignChildEvent = (e, targetVideo) => Boolean(e?.target && e.target !== el && !targetVideo);
4630
4636
  const quartilesFired = {
4631
4637
  q1: false,
4632
4638
  q2: false,
@@ -4634,7 +4640,7 @@ function attachVideoPlayer(analytics, target, options) {
4634
4640
  q4: false
4635
4641
  };
4636
4642
  const triggerPlaybackImpression = (activeVideo) => {
4637
- const vEl = activeVideo || videoEl || (el?.querySelector ? el.querySelector("video") : null);
4643
+ const vEl = activeVideo || resolveTargetVideo();
4638
4644
  const cached = getWinningBid();
4639
4645
  const mergedBid = {
4640
4646
  ...cached?.rawBid || options?.bid,
@@ -4661,12 +4667,13 @@ function attachVideoPlayer(analytics, target, options) {
4661
4667
  }
4662
4668
  };
4663
4669
  const handlePlaying = (e) => {
4670
+ const targetVideo = resolveTargetVideo(e);
4671
+ if (isForeignChildEvent(e, targetVideo)) return;
4664
4672
  self.log("DEBUG", "HTML5 video playing event received");
4665
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4666
4673
  triggerPlaybackImpression(targetVideo);
4667
4674
  };
4668
4675
  const handleTimeUpdate = (e) => {
4669
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4676
+ const targetVideo = resolveTargetVideo(e);
4670
4677
  if (targetVideo && targetVideo.currentTime > 0) {
4671
4678
  triggerPlaybackImpression(targetVideo);
4672
4679
  if (Number.isFinite(targetVideo.duration) && targetVideo.duration > 0) {
@@ -4686,15 +4693,17 @@ function attachVideoPlayer(analytics, target, options) {
4686
4693
  }
4687
4694
  }
4688
4695
  };
4689
- const handleEnded = () => {
4696
+ const handleEnded = (e) => {
4697
+ if (isForeignChildEvent(e, resolveTargetVideo(e))) return;
4690
4698
  if (!quartilesFired.q4) {
4691
4699
  quartilesFired.q4 = true;
4692
4700
  options?.onMilestone?.("complete", slotId);
4693
4701
  }
4694
4702
  };
4695
4703
  const handleError = (e) => {
4696
- const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4697
- const err = targetVideo?.error || videoEl?.error;
4704
+ const targetVideo = resolveTargetVideo(e);
4705
+ if (isForeignChildEvent(e, targetVideo)) return;
4706
+ const err = targetVideo?.error;
4698
4707
  const cached = getWinningBid();
4699
4708
  const msg = err ? `HTML5 video error code ${err.code}: ${err.message}` : "Video playback error";
4700
4709
  self.log("WARN", msg);
@@ -4719,41 +4728,13 @@ function attachVideoPlayer(analytics, target, options) {
4719
4728
  }
4720
4729
  }
4721
4730
  };
4722
- const attachListenersToVideo = (targetVideo) => {
4723
- targetVideo.addEventListener("playing", handlePlaying);
4724
- targetVideo.addEventListener("play", handlePlaying);
4725
- targetVideo.addEventListener("timeupdate", handleTimeUpdate);
4726
- targetVideo.addEventListener("ended", handleEnded);
4727
- targetVideo.addEventListener("error", handleError);
4728
- };
4729
- const removeListenersFromVideo = (targetVideo) => {
4730
- targetVideo.removeEventListener("playing", handlePlaying);
4731
- targetVideo.removeEventListener("play", handlePlaying);
4732
- targetVideo.removeEventListener("timeupdate", handleTimeUpdate);
4733
- targetVideo.removeEventListener("ended", handleEnded);
4734
- targetVideo.removeEventListener("error", handleError);
4735
- };
4736
- let mutationObserver = null;
4737
- if (el && el !== videoEl) {
4738
- el.addEventListener("playing", handlePlaying, true);
4739
- el.addEventListener("play", handlePlaying, true);
4740
- el.addEventListener("timeupdate", handleTimeUpdate, true);
4741
- el.addEventListener("ended", handleEnded, true);
4742
- el.addEventListener("error", handleError, true);
4743
- }
4744
- if (videoEl) {
4745
- attachListenersToVideo(videoEl);
4746
- }
4747
- if (el && el.tagName?.toLowerCase() !== "video" && typeof MutationObserver !== "undefined") {
4748
- mutationObserver = new MutationObserver(() => {
4749
- const found = el.querySelector("video");
4750
- if (found && found !== videoEl) {
4751
- if (videoEl) removeListenersFromVideo(videoEl);
4752
- videoEl = found;
4753
- if (videoEl) attachListenersToVideo(videoEl);
4754
- }
4755
- });
4756
- mutationObserver.observe(el, { childList: true, subtree: true });
4731
+ const useCapture = !isVideoEl;
4732
+ if (el) {
4733
+ el.addEventListener("playing", handlePlaying, useCapture);
4734
+ el.addEventListener("play", handlePlaying, useCapture);
4735
+ el.addEventListener("timeupdate", handleTimeUpdate, useCapture);
4736
+ el.addEventListener("ended", handleEnded, useCapture);
4737
+ el.addEventListener("error", handleError, useCapture);
4757
4738
  }
4758
4739
  const cachedInitial = getWinningBid();
4759
4740
  if (options?.trackViewability !== false && el) {
@@ -4767,19 +4748,12 @@ function attachVideoPlayer(analytics, target, options) {
4767
4748
  });
4768
4749
  }
4769
4750
  const cleanup = () => {
4770
- if (mutationObserver) {
4771
- mutationObserver.disconnect();
4772
- mutationObserver = null;
4773
- }
4774
- if (el && el !== videoEl) {
4775
- el.removeEventListener("playing", handlePlaying, true);
4776
- el.removeEventListener("play", handlePlaying, true);
4777
- el.removeEventListener("timeupdate", handleTimeUpdate, true);
4778
- el.removeEventListener("ended", handleEnded, true);
4779
- el.removeEventListener("error", handleError, true);
4780
- }
4781
- if (videoEl) {
4782
- removeListenersFromVideo(videoEl);
4751
+ if (el) {
4752
+ el.removeEventListener("playing", handlePlaying, useCapture);
4753
+ el.removeEventListener("play", handlePlaying, useCapture);
4754
+ el.removeEventListener("timeupdate", handleTimeUpdate, useCapture);
4755
+ el.removeEventListener("ended", handleEnded, useCapture);
4756
+ el.removeEventListener("error", handleError, useCapture);
4783
4757
  }
4784
4758
  self.videoDetachCleanups.delete(cleanup);
4785
4759
  };
@@ -4792,16 +4766,17 @@ BidsparkPrebidAnalytics.prototype.attachImaAdsManager = function(adsManager, opt
4792
4766
  BidsparkPrebidAnalytics.prototype.attachVideoPlayer = function(target, options) {
4793
4767
  return attachVideoPlayer(this, target, options);
4794
4768
  };
4795
- var coreEnable = BidsparkPrebidAnalytics.prototype.enable;
4796
- BidsparkPrebidAnalytics.prototype.enable = function() {
4797
- coreEnable.call(this);
4798
- if (typeof window !== "undefined") {
4769
+ var imaAutoInterceptionInstalled = false;
4770
+ function installImaAutoInterception() {
4771
+ if (imaAutoInterceptionInstalled) return;
4772
+ imaAutoInterceptionInstalled = true;
4773
+ initImaInterception();
4774
+ const coreEnable = BidsparkPrebidAnalytics.prototype.enable;
4775
+ BidsparkPrebidAnalytics.prototype.enable = function() {
4776
+ coreEnable.call(this);
4799
4777
  initImaInterception();
4800
- if (window.google?.ima) {
4801
- hookImaPrototype(window.google.ima);
4802
- }
4803
- }
4804
- };
4778
+ };
4779
+ }
4805
4780
  function normalizeImaEventName(name) {
4806
4781
  if (!name) return "";
4807
4782
  const lower = name.toLowerCase().replace(/[_-]/g, "");
@@ -4920,6 +4895,7 @@ var ImaAdsManagerStub = class {
4920
4895
  };
4921
4896
 
4922
4897
  // src/index.ts
4898
+ installImaAutoInterception();
4923
4899
  function getAdsGlobal(alias = DEFAULT_ALIAS) {
4924
4900
  if (typeof window === "undefined") {
4925
4901
  return { q: [] };
@@ -4991,6 +4967,7 @@ function getAdsGlobal(alias = DEFAULT_ALIAS) {
4991
4967
  getPrebidEventKey,
4992
4968
  idToBytes,
4993
4969
  idToString,
4970
+ installImaAutoInterception,
4994
4971
  isAutomatedClient,
4995
4972
  isSessionActive,
4996
4973
  isTrustedEndpoint,