@bidspark/analytics 0.0.0-stage → 0.44.0

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 ADDED
@@ -0,0 +1,4847 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ BidsparkPrebidAnalytics: () => BidsparkPrebidAnalytics,
24
+ CACHED_BID_TTL_MS: () => CACHED_BID_TTL_MS,
25
+ DEFAULT_ALIAS: () => DEFAULT_ALIAS,
26
+ ImaAdsManagerStub: () => ImaAdsManagerStub,
27
+ LogLevel: () => LogLevel,
28
+ MAX_USAGE_BATCH_SIZE: () => MAX_USAGE_BATCH_SIZE,
29
+ PrebidEventDeduper: () => PrebidEventDeduper,
30
+ SAFE_CONTENT_TYPE: () => SAFE_CONTENT_TYPE,
31
+ USAGE_FLUSH_INTERVAL_MS: () => USAGE_FLUSH_INTERVAL_MS,
32
+ UsageProto: () => usage_event_exports,
33
+ UsageRecorder: () => UsageRecorder,
34
+ attachImaAdsManager: () => attachImaAdsManager,
35
+ attachVideoPlayer: () => attachVideoPlayer,
36
+ clearStoredSession: () => clearStoredSession,
37
+ clearStoredUserId: () => clearStoredUserId,
38
+ generateUUID: () => generateUUID,
39
+ getAdsGlobal: () => getAdsGlobal,
40
+ getOrCreateSessionId: () => getOrCreateSessionId,
41
+ getOrCreateUserId: () => getOrCreateUserId,
42
+ getPrebidEventKey: () => getPrebidEventKey,
43
+ idToBytes: () => idToBytes,
44
+ idToString: () => idToString,
45
+ isSessionActive: () => isSessionActive,
46
+ isTrustedEndpoint: () => isTrustedEndpoint,
47
+ isVisitorSampled: () => isVisitorSampled,
48
+ normalizeLogLevel: () => normalizeLogLevel,
49
+ normalizeSampleRate: () => normalizeSampleRate,
50
+ onSessionResume: () => onSessionResume,
51
+ registerPrebidAnalytics: () => registerPrebidAnalytics,
52
+ resetTcfListener: () => resetTcfListener,
53
+ sendEvents: () => sendEvents,
54
+ sessionStarted: () => sessionStarted
55
+ });
56
+ module.exports = __toCommonJS(src_exports);
57
+
58
+ // ../logger/src/index.ts
59
+ var LogLevel = {
60
+ DEBUG: "DEBUG",
61
+ INFO: "INFO",
62
+ WARN: "WARN",
63
+ ERROR: "ERROR"
64
+ };
65
+ var LOG_LEVEL_MAP = {
66
+ [LogLevel.DEBUG]: 10,
67
+ [LogLevel.INFO]: 20,
68
+ [LogLevel.WARN]: 30,
69
+ [LogLevel.ERROR]: 40
70
+ };
71
+ var COLORS = {
72
+ badge: "color: #2dd4bf; font-weight: bold",
73
+ badgeWarn: "background: #f59e0b; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",
74
+ badgeError: "background: #ef4444; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",
75
+ dim: "color: #6b7280",
76
+ event: "color: #38bdf8; font-weight: bold",
77
+ eventWarn: "color: #f59e0b; font-weight: bold",
78
+ eventError: "color: #ef4444; font-weight: bold",
79
+ reset: "color: inherit"
80
+ };
81
+ var logCounter = 0;
82
+ var localGlobalListeners = /* @__PURE__ */ new Set();
83
+ function getGlobalListeners() {
84
+ if (typeof window !== "undefined") {
85
+ const win = window;
86
+ if (!win.__bidsparkLogListeners) {
87
+ win.__bidsparkLogListeners = /* @__PURE__ */ new Set();
88
+ }
89
+ return win.__bidsparkLogListeners;
90
+ }
91
+ return localGlobalListeners;
92
+ }
93
+ function formatTime(ms) {
94
+ if (ms < 0 || !Number.isFinite(ms)) ms = 0;
95
+ if (ms < 1e3) return `${ms.toFixed(2)}ms`;
96
+ const s = ms / 1e3;
97
+ if (s < 60) return `${s.toFixed(2)}s`;
98
+ const m = Math.floor(s / 60);
99
+ if (m < 60) return `${m}m ${(s % 60).toFixed(2)}s`;
100
+ const h = Math.floor(m / 60);
101
+ return `${h}h ${m % 60}m ${(s % 60).toFixed(2)}s`;
102
+ }
103
+ function normalizeLogLevel(level) {
104
+ if (typeof level === "string") {
105
+ const upper = level.toUpperCase();
106
+ if (upper === "DEBUG" || upper === "INFO" || upper === "WARN" || upper === "ERROR") {
107
+ return upper;
108
+ }
109
+ }
110
+ return LogLevel.INFO;
111
+ }
112
+ var Logger = class {
113
+ _prefix;
114
+ _level;
115
+ _loadedAt;
116
+ _now;
117
+ _console;
118
+ _listeners = /* @__PURE__ */ new Set();
119
+ constructor(options = {}) {
120
+ this._prefix = options.prefix ?? "[ads]";
121
+ this._level = normalizeLogLevel(options.logLevel ?? LogLevel.INFO);
122
+ this._now = options.now;
123
+ this._console = options.console;
124
+ if (options.onLog) {
125
+ this._listeners.add(options.onLog);
126
+ }
127
+ this._loadedAt = options.loadedAt ?? (this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now());
128
+ }
129
+ get prefix() {
130
+ return this._prefix;
131
+ }
132
+ set prefix(val) {
133
+ this._prefix = val;
134
+ }
135
+ get logLevel() {
136
+ return this._level;
137
+ }
138
+ set logLevel(val) {
139
+ this._level = normalizeLogLevel(val);
140
+ }
141
+ getLevel() {
142
+ return this._level;
143
+ }
144
+ setLevel(level) {
145
+ this._level = normalizeLogLevel(level);
146
+ }
147
+ getPrefix() {
148
+ return this._prefix;
149
+ }
150
+ setPrefix(prefix) {
151
+ this._prefix = prefix;
152
+ }
153
+ resetTiming(loadedAt) {
154
+ this._loadedAt = loadedAt ?? (this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now());
155
+ }
156
+ getLoadedAt() {
157
+ return this._loadedAt;
158
+ }
159
+ addListener(listener) {
160
+ this._listeners.add(listener);
161
+ return () => {
162
+ this._listeners.delete(listener);
163
+ };
164
+ }
165
+ removeListener(listener) {
166
+ this._listeners.delete(listener);
167
+ }
168
+ isEnabled(level) {
169
+ const target = normalizeLogLevel(level);
170
+ return (LOG_LEVEL_MAP[target] ?? 20) >= (LOG_LEVEL_MAP[this._level] ?? 20);
171
+ }
172
+ _getConsole() {
173
+ if (this._console) return this._console;
174
+ if (typeof console !== "undefined") return console;
175
+ return void 0;
176
+ }
177
+ _getElapsed() {
178
+ const current = this._now ? this._now() : typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
179
+ return Math.max(0, current - this._loadedAt);
180
+ }
181
+ _dispatchRecord(record) {
182
+ for (const l of this._listeners) {
183
+ try {
184
+ l(record);
185
+ } catch {
186
+ }
187
+ }
188
+ const globalListeners = getGlobalListeners();
189
+ for (const gl of globalListeners) {
190
+ if (!this._listeners.has(gl)) {
191
+ try {
192
+ gl(record);
193
+ } catch {
194
+ }
195
+ }
196
+ }
197
+ }
198
+ log(level, nameOrMsg, ...args) {
199
+ const normLevel = normalizeLogLevel(level);
200
+ if (!this.isEnabled(normLevel)) {
201
+ return;
202
+ }
203
+ const elapsed = this._getElapsed();
204
+ const formattedTimeStr = formatTime(elapsed);
205
+ const nowEpoch = Date.now();
206
+ const recordId = `bk_log_${nowEpoch}_${++logCounter}`;
207
+ const record = {
208
+ id: recordId,
209
+ timestamp: nowEpoch,
210
+ elapsedMs: elapsed,
211
+ level: normLevel,
212
+ prefix: this._prefix,
213
+ message: nameOrMsg,
214
+ args,
215
+ data: args.length === 1 ? args[0] : args.length > 1 ? args : void 0
216
+ };
217
+ this._dispatchRecord(record);
218
+ const c = this._getConsole();
219
+ if (!c) return;
220
+ let badgeStyle = COLORS.badge;
221
+ let eventStyle = COLORS.event;
222
+ if (normLevel === LogLevel.WARN) {
223
+ badgeStyle = COLORS.badgeWarn;
224
+ eventStyle = COLORS.eventWarn;
225
+ } else if (normLevel === LogLevel.ERROR) {
226
+ badgeStyle = COLORS.badgeError;
227
+ eventStyle = COLORS.eventError;
228
+ }
229
+ const callArgs = [
230
+ "%c%s%c %s %c%s%c",
231
+ badgeStyle,
232
+ this._prefix,
233
+ COLORS.dim,
234
+ formattedTimeStr,
235
+ eventStyle,
236
+ nameOrMsg,
237
+ COLORS.reset
238
+ ];
239
+ if (args.length > 0) {
240
+ callArgs.push(...args);
241
+ }
242
+ switch (normLevel) {
243
+ case LogLevel.DEBUG:
244
+ if (typeof c.log === "function") {
245
+ c.log(...callArgs);
246
+ } else if (typeof c.debug === "function") {
247
+ c.debug(...callArgs);
248
+ }
249
+ break;
250
+ case LogLevel.INFO:
251
+ if (typeof c.info === "function") {
252
+ c.info(...callArgs);
253
+ } else if (typeof c.log === "function") {
254
+ c.log(...callArgs);
255
+ }
256
+ break;
257
+ case LogLevel.WARN:
258
+ if (typeof c.warn === "function") {
259
+ c.warn(...callArgs);
260
+ } else if (typeof c.log === "function") {
261
+ c.log(...callArgs);
262
+ }
263
+ break;
264
+ case LogLevel.ERROR:
265
+ if (typeof c.error === "function") {
266
+ c.error(...callArgs);
267
+ } else if (typeof c.log === "function") {
268
+ c.log(...callArgs);
269
+ }
270
+ break;
271
+ default:
272
+ if (typeof c.log === "function") {
273
+ c.log(...callArgs);
274
+ }
275
+ break;
276
+ }
277
+ }
278
+ debug(nameOrMsg, ...args) {
279
+ this.log(LogLevel.DEBUG, nameOrMsg, ...args);
280
+ }
281
+ info(nameOrMsg, ...args) {
282
+ this.log(LogLevel.INFO, nameOrMsg, ...args);
283
+ }
284
+ warn(nameOrMsg, ...args) {
285
+ this.log(LogLevel.WARN, nameOrMsg, ...args);
286
+ }
287
+ error(nameOrMsg, ...args) {
288
+ this.log(LogLevel.ERROR, nameOrMsg, ...args);
289
+ }
290
+ logEvent(event) {
291
+ if (!event) return;
292
+ if (event.data !== void 0) {
293
+ this.log(event.level, event.eventName, event.data);
294
+ } else {
295
+ this.log(event.level, event.eventName);
296
+ }
297
+ }
298
+ };
299
+ function createLogger(options) {
300
+ return new Logger(options);
301
+ }
302
+
303
+ // ../../protogen/trace_event.ts
304
+ var import_wire = require("@bufbuild/protobuf/wire");
305
+ var TraceEventType = {
306
+ TRACE_EVENT_TYPE_UNSPECIFIED: 0,
307
+ AUCTION_START: 1,
308
+ AUCTION_END: 2,
309
+ BID_WIN: 4,
310
+ /** IMPRESSION - Ad rendered into DOM */
311
+ IMPRESSION: 5,
312
+ /** VIEWABLE - IAB viewability met (once per render cycle) */
313
+ VIEWABLE: 6,
314
+ /** TIME_IN_VIEW - Accumulated in-viewport duration (fired at render cycle end) */
315
+ TIME_IN_VIEW: 7,
316
+ ERROR: 9,
317
+ SLOT_DEFINED: 10,
318
+ SLOT_DESTROYED: 11,
319
+ /** CLICK - Ad click-through */
320
+ CLICK: 12,
321
+ /** AD_RENDER_FAILED - Prebid failed to render winning ad */
322
+ AD_RENDER_FAILED: 13,
323
+ /**
324
+ * WARN - Non-fatal wrapper condition (e.g. no fitting sizes, video watchdog timeout).
325
+ * Uses custom event_name; gated by tracker.warnings_enabled.
326
+ */
327
+ WARN: 17,
328
+ /**
329
+ * CONSENT - Visitor consent decision (granted or denied). Metadata holds flattened CMP details:
330
+ * regime, action, strings (tc, ac, gpp, usp), vendor/purpose counts, and flags.
331
+ */
332
+ CONSENT: 19,
333
+ /**
334
+ * RECOVERY - Ad block recovery funnel. Metadata: state (detected|shown|allow_click|support_click|dismissed|verified|recovered),
335
+ * first ("1" on first detected/recovered), mode (ask|metered|wall), shown_as (soft|wall on shown),
336
+ * signals (bitmask), sdk_loaded, device (mobile|desktop), browser, forced ("1" on forced show).
337
+ */
338
+ RECOVERY: 20,
339
+ /** PAGEVIEW - Pageview start (once per initial load or SPA navigate()). */
340
+ PAGEVIEW: 21,
341
+ UNRECOGNIZED: -1
342
+ };
343
+ var BidderOutcome = {
344
+ BIDDER_OUTCOME_UNSPECIFIED: 0,
345
+ /** BIDDER_OUTCOME_BID - Returned bid (CPM > 0) */
346
+ BIDDER_OUTCOME_BID: 1,
347
+ BIDDER_OUTCOME_NO_BID: 2,
348
+ BIDDER_OUTCOME_TIMEOUT: 3,
349
+ BIDDER_OUTCOME_ERROR: 4,
350
+ /** BIDDER_OUTCOME_NO_RESPONSE - Requested, but no response before auction end */
351
+ BIDDER_OUTCOME_NO_RESPONSE: 5,
352
+ UNRECOGNIZED: -1
353
+ };
354
+ var FloorSource = {
355
+ /** FLOOR_SOURCE_UNSPECIFIED - Module disabled */
356
+ FLOOR_SOURCE_UNSPECIFIED: 0,
357
+ /** FLOOR_SOURCE_STATIC - Publisher static rule scaled by treatment */
358
+ FLOOR_SOURCE_STATIC: 1,
359
+ /** FLOOR_SOURCE_POOL - Bid pool standing bid plus margin */
360
+ FLOOR_SOURCE_POOL: 2,
361
+ /** FLOOR_SOURCE_NONE - Module active, but neither term applied */
362
+ FLOOR_SOURCE_NONE: 3,
363
+ UNRECOGNIZED: -1
364
+ };
365
+ function createBaseTraceEventBatch() {
366
+ return {
367
+ propertyId: new Uint8Array(0),
368
+ pageviewId: new Uint8Array(0),
369
+ sessionId: new Uint8Array(0),
370
+ pageUrl: "",
371
+ country: "",
372
+ region: "",
373
+ deviceType: "",
374
+ userId: "",
375
+ domain: "",
376
+ events: [],
377
+ browser: "",
378
+ deviceManufacturer: "",
379
+ deviceModel: "",
380
+ city: "",
381
+ postalCode: "",
382
+ sampleRate: void 0,
383
+ automated: false
384
+ };
385
+ }
386
+ var TraceEventBatch = {
387
+ encode(message, writer = new import_wire.BinaryWriter()) {
388
+ if (message.propertyId !== void 0 && message.propertyId.length !== 0) {
389
+ writer.uint32(10).bytes(message.propertyId);
390
+ }
391
+ if (message.pageviewId !== void 0 && message.pageviewId.length !== 0) {
392
+ writer.uint32(18).bytes(message.pageviewId);
393
+ }
394
+ if (message.sessionId !== void 0 && message.sessionId.length !== 0) {
395
+ writer.uint32(26).bytes(message.sessionId);
396
+ }
397
+ if (message.pageUrl !== void 0 && message.pageUrl !== "") {
398
+ writer.uint32(34).string(message.pageUrl);
399
+ }
400
+ if (message.country !== void 0 && message.country !== "") {
401
+ writer.uint32(42).string(message.country);
402
+ }
403
+ if (message.region !== void 0 && message.region !== "") {
404
+ writer.uint32(50).string(message.region);
405
+ }
406
+ if (message.deviceType !== void 0 && message.deviceType !== "") {
407
+ writer.uint32(58).string(message.deviceType);
408
+ }
409
+ if (message.userId !== void 0 && message.userId !== "") {
410
+ writer.uint32(66).string(message.userId);
411
+ }
412
+ if (message.domain !== void 0 && message.domain !== "") {
413
+ writer.uint32(74).string(message.domain);
414
+ }
415
+ if (message.events !== void 0 && message.events.length !== 0) {
416
+ for (const v of message.events) {
417
+ TraceEvent.encode(v, writer.uint32(82).fork()).join();
418
+ }
419
+ }
420
+ if (message.browser !== void 0 && message.browser !== "") {
421
+ writer.uint32(90).string(message.browser);
422
+ }
423
+ if (message.deviceManufacturer !== void 0 && message.deviceManufacturer !== "") {
424
+ writer.uint32(98).string(message.deviceManufacturer);
425
+ }
426
+ if (message.deviceModel !== void 0 && message.deviceModel !== "") {
427
+ writer.uint32(106).string(message.deviceModel);
428
+ }
429
+ if (message.city !== void 0 && message.city !== "") {
430
+ writer.uint32(114).string(message.city);
431
+ }
432
+ if (message.postalCode !== void 0 && message.postalCode !== "") {
433
+ writer.uint32(122).string(message.postalCode);
434
+ }
435
+ if (message.sampleRate !== void 0) {
436
+ writer.uint32(129).double(message.sampleRate);
437
+ }
438
+ if (message.automated !== void 0 && message.automated !== false) {
439
+ writer.uint32(136).bool(message.automated);
440
+ }
441
+ return writer;
442
+ },
443
+ decode(input, length) {
444
+ const reader = input instanceof import_wire.BinaryReader ? input : new import_wire.BinaryReader(input);
445
+ const end = length === void 0 ? reader.len : reader.pos + length;
446
+ const message = createBaseTraceEventBatch();
447
+ while (reader.pos < end) {
448
+ const tag = reader.uint32();
449
+ switch (tag >>> 3) {
450
+ case 1: {
451
+ if (tag !== 10) {
452
+ break;
453
+ }
454
+ message.propertyId = reader.bytes();
455
+ continue;
456
+ }
457
+ case 2: {
458
+ if (tag !== 18) {
459
+ break;
460
+ }
461
+ message.pageviewId = reader.bytes();
462
+ continue;
463
+ }
464
+ case 3: {
465
+ if (tag !== 26) {
466
+ break;
467
+ }
468
+ message.sessionId = reader.bytes();
469
+ continue;
470
+ }
471
+ case 4: {
472
+ if (tag !== 34) {
473
+ break;
474
+ }
475
+ message.pageUrl = reader.string();
476
+ continue;
477
+ }
478
+ case 5: {
479
+ if (tag !== 42) {
480
+ break;
481
+ }
482
+ message.country = reader.string();
483
+ continue;
484
+ }
485
+ case 6: {
486
+ if (tag !== 50) {
487
+ break;
488
+ }
489
+ message.region = reader.string();
490
+ continue;
491
+ }
492
+ case 7: {
493
+ if (tag !== 58) {
494
+ break;
495
+ }
496
+ message.deviceType = reader.string();
497
+ continue;
498
+ }
499
+ case 8: {
500
+ if (tag !== 66) {
501
+ break;
502
+ }
503
+ message.userId = reader.string();
504
+ continue;
505
+ }
506
+ case 9: {
507
+ if (tag !== 74) {
508
+ break;
509
+ }
510
+ message.domain = reader.string();
511
+ continue;
512
+ }
513
+ case 10: {
514
+ if (tag !== 82) {
515
+ break;
516
+ }
517
+ const el = TraceEvent.decode(reader, reader.uint32());
518
+ if (el !== void 0) {
519
+ message.events.push(el);
520
+ }
521
+ continue;
522
+ }
523
+ case 11: {
524
+ if (tag !== 90) {
525
+ break;
526
+ }
527
+ message.browser = reader.string();
528
+ continue;
529
+ }
530
+ case 12: {
531
+ if (tag !== 98) {
532
+ break;
533
+ }
534
+ message.deviceManufacturer = reader.string();
535
+ continue;
536
+ }
537
+ case 13: {
538
+ if (tag !== 106) {
539
+ break;
540
+ }
541
+ message.deviceModel = reader.string();
542
+ continue;
543
+ }
544
+ case 14: {
545
+ if (tag !== 114) {
546
+ break;
547
+ }
548
+ message.city = reader.string();
549
+ continue;
550
+ }
551
+ case 15: {
552
+ if (tag !== 122) {
553
+ break;
554
+ }
555
+ message.postalCode = reader.string();
556
+ continue;
557
+ }
558
+ case 16: {
559
+ if (tag !== 129) {
560
+ break;
561
+ }
562
+ message.sampleRate = reader.double();
563
+ continue;
564
+ }
565
+ case 17: {
566
+ if (tag !== 136) {
567
+ break;
568
+ }
569
+ message.automated = reader.bool();
570
+ continue;
571
+ }
572
+ }
573
+ if ((tag & 7) === 4 || tag === 0) {
574
+ break;
575
+ }
576
+ reader.skip(tag & 7);
577
+ }
578
+ return message;
579
+ }
580
+ };
581
+ function createBaseTraceEvent() {
582
+ return {
583
+ timestampMs: 0,
584
+ type: 0,
585
+ eventName: "",
586
+ auctionId: new Uint8Array(0),
587
+ transactionId: new Uint8Array(0),
588
+ adUnitCode: "",
589
+ bid: void 0,
590
+ namespace: "",
591
+ eventId: new Uint8Array(0),
592
+ metadata: {},
593
+ viewableDurationMs: void 0,
594
+ bidderOutcomes: []
595
+ };
596
+ }
597
+ var TraceEvent = {
598
+ encode(message, writer = new import_wire.BinaryWriter()) {
599
+ if (message.timestampMs !== void 0 && message.timestampMs !== 0) {
600
+ writer.uint32(9).double(message.timestampMs);
601
+ }
602
+ if (message.type !== void 0 && message.type !== 0) {
603
+ writer.uint32(16).int32(message.type);
604
+ }
605
+ if (message.eventName !== void 0 && message.eventName !== "") {
606
+ writer.uint32(26).string(message.eventName);
607
+ }
608
+ if (message.auctionId !== void 0 && message.auctionId.length !== 0) {
609
+ writer.uint32(34).bytes(message.auctionId);
610
+ }
611
+ if (message.transactionId !== void 0 && message.transactionId.length !== 0) {
612
+ writer.uint32(42).bytes(message.transactionId);
613
+ }
614
+ if (message.adUnitCode !== void 0 && message.adUnitCode !== "") {
615
+ writer.uint32(50).string(message.adUnitCode);
616
+ }
617
+ if (message.bid !== void 0) {
618
+ BidTrace.encode(message.bid, writer.uint32(58).fork()).join();
619
+ }
620
+ if (message.namespace !== void 0 && message.namespace !== "") {
621
+ writer.uint32(66).string(message.namespace);
622
+ }
623
+ if (message.eventId !== void 0 && message.eventId.length !== 0) {
624
+ writer.uint32(74).bytes(message.eventId);
625
+ }
626
+ globalThis.Object.entries(message.metadata || {}).forEach(([key, value]) => {
627
+ TraceEvent_MetadataEntry.encode({ key, value }, writer.uint32(82).fork()).join();
628
+ });
629
+ if (message.viewableDurationMs !== void 0) {
630
+ writer.uint32(89).double(message.viewableDurationMs);
631
+ }
632
+ if (message.bidderOutcomes !== void 0 && message.bidderOutcomes.length !== 0) {
633
+ for (const v of message.bidderOutcomes) {
634
+ BidderOutcomeEntry.encode(v, writer.uint32(98).fork()).join();
635
+ }
636
+ }
637
+ return writer;
638
+ },
639
+ decode(input, length) {
640
+ const reader = input instanceof import_wire.BinaryReader ? input : new import_wire.BinaryReader(input);
641
+ const end = length === void 0 ? reader.len : reader.pos + length;
642
+ const message = createBaseTraceEvent();
643
+ while (reader.pos < end) {
644
+ const tag = reader.uint32();
645
+ switch (tag >>> 3) {
646
+ case 1: {
647
+ if (tag !== 9) {
648
+ break;
649
+ }
650
+ message.timestampMs = reader.double();
651
+ continue;
652
+ }
653
+ case 2: {
654
+ if (tag !== 16) {
655
+ break;
656
+ }
657
+ message.type = reader.int32();
658
+ continue;
659
+ }
660
+ case 3: {
661
+ if (tag !== 26) {
662
+ break;
663
+ }
664
+ message.eventName = reader.string();
665
+ continue;
666
+ }
667
+ case 4: {
668
+ if (tag !== 34) {
669
+ break;
670
+ }
671
+ message.auctionId = reader.bytes();
672
+ continue;
673
+ }
674
+ case 5: {
675
+ if (tag !== 42) {
676
+ break;
677
+ }
678
+ message.transactionId = reader.bytes();
679
+ continue;
680
+ }
681
+ case 6: {
682
+ if (tag !== 50) {
683
+ break;
684
+ }
685
+ message.adUnitCode = reader.string();
686
+ continue;
687
+ }
688
+ case 7: {
689
+ if (tag !== 58) {
690
+ break;
691
+ }
692
+ message.bid = BidTrace.decode(reader, reader.uint32());
693
+ continue;
694
+ }
695
+ case 8: {
696
+ if (tag !== 66) {
697
+ break;
698
+ }
699
+ message.namespace = reader.string();
700
+ continue;
701
+ }
702
+ case 9: {
703
+ if (tag !== 74) {
704
+ break;
705
+ }
706
+ message.eventId = reader.bytes();
707
+ continue;
708
+ }
709
+ case 10: {
710
+ if (tag !== 82) {
711
+ break;
712
+ }
713
+ const entry10 = TraceEvent_MetadataEntry.decode(reader, reader.uint32());
714
+ if (entry10.value !== void 0) {
715
+ message.metadata[entry10.key] = entry10.value;
716
+ }
717
+ continue;
718
+ }
719
+ case 11: {
720
+ if (tag !== 89) {
721
+ break;
722
+ }
723
+ message.viewableDurationMs = reader.double();
724
+ continue;
725
+ }
726
+ case 12: {
727
+ if (tag !== 98) {
728
+ break;
729
+ }
730
+ const el = BidderOutcomeEntry.decode(reader, reader.uint32());
731
+ if (el !== void 0) {
732
+ message.bidderOutcomes.push(el);
733
+ }
734
+ continue;
735
+ }
736
+ }
737
+ if ((tag & 7) === 4 || tag === 0) {
738
+ break;
739
+ }
740
+ reader.skip(tag & 7);
741
+ }
742
+ return message;
743
+ }
744
+ };
745
+ function createBaseTraceEvent_MetadataEntry() {
746
+ return { key: "", value: "" };
747
+ }
748
+ var TraceEvent_MetadataEntry = {
749
+ encode(message, writer = new import_wire.BinaryWriter()) {
750
+ if (message.key !== "") {
751
+ writer.uint32(10).string(message.key);
752
+ }
753
+ if (message.value !== "") {
754
+ writer.uint32(18).string(message.value);
755
+ }
756
+ return writer;
757
+ },
758
+ decode(input, length) {
759
+ const reader = input instanceof import_wire.BinaryReader ? input : new import_wire.BinaryReader(input);
760
+ const end = length === void 0 ? reader.len : reader.pos + length;
761
+ const message = createBaseTraceEvent_MetadataEntry();
762
+ while (reader.pos < end) {
763
+ const tag = reader.uint32();
764
+ switch (tag >>> 3) {
765
+ case 1: {
766
+ if (tag !== 10) {
767
+ break;
768
+ }
769
+ message.key = reader.string();
770
+ continue;
771
+ }
772
+ case 2: {
773
+ if (tag !== 18) {
774
+ break;
775
+ }
776
+ message.value = reader.string();
777
+ continue;
778
+ }
779
+ }
780
+ if ((tag & 7) === 4 || tag === 0) {
781
+ break;
782
+ }
783
+ reader.skip(tag & 7);
784
+ }
785
+ return message;
786
+ }
787
+ };
788
+ function createBaseBidderOutcomeEntry() {
789
+ return {
790
+ adUnitCode: "",
791
+ outcome: 0,
792
+ bid: void 0,
793
+ refreshIndex: 0,
794
+ floorCents: void 0,
795
+ floorSource: 0,
796
+ floorTreatmentBp: void 0,
797
+ slot: ""
798
+ };
799
+ }
800
+ var BidderOutcomeEntry = {
801
+ encode(message, writer = new import_wire.BinaryWriter()) {
802
+ if (message.adUnitCode !== void 0 && message.adUnitCode !== "") {
803
+ writer.uint32(18).string(message.adUnitCode);
804
+ }
805
+ if (message.outcome !== void 0 && message.outcome !== 0) {
806
+ writer.uint32(32).int32(message.outcome);
807
+ }
808
+ if (message.bid !== void 0) {
809
+ BidTrace.encode(message.bid, writer.uint32(50).fork()).join();
810
+ }
811
+ if (message.refreshIndex !== void 0 && message.refreshIndex !== 0) {
812
+ writer.uint32(56).int32(message.refreshIndex);
813
+ }
814
+ if (message.floorCents !== void 0) {
815
+ writer.uint32(64).int32(message.floorCents);
816
+ }
817
+ if (message.floorSource !== void 0 && message.floorSource !== 0) {
818
+ writer.uint32(72).int32(message.floorSource);
819
+ }
820
+ if (message.floorTreatmentBp !== void 0) {
821
+ writer.uint32(80).int32(message.floorTreatmentBp);
822
+ }
823
+ if (message.slot !== void 0 && message.slot !== "") {
824
+ writer.uint32(90).string(message.slot);
825
+ }
826
+ return writer;
827
+ },
828
+ decode(input, length) {
829
+ const reader = input instanceof import_wire.BinaryReader ? input : new import_wire.BinaryReader(input);
830
+ const end = length === void 0 ? reader.len : reader.pos + length;
831
+ const message = createBaseBidderOutcomeEntry();
832
+ while (reader.pos < end) {
833
+ const tag = reader.uint32();
834
+ switch (tag >>> 3) {
835
+ case 2: {
836
+ if (tag !== 18) {
837
+ break;
838
+ }
839
+ message.adUnitCode = reader.string();
840
+ continue;
841
+ }
842
+ case 4: {
843
+ if (tag !== 32) {
844
+ break;
845
+ }
846
+ message.outcome = reader.int32();
847
+ continue;
848
+ }
849
+ case 6: {
850
+ if (tag !== 50) {
851
+ break;
852
+ }
853
+ message.bid = BidTrace.decode(reader, reader.uint32());
854
+ continue;
855
+ }
856
+ case 7: {
857
+ if (tag !== 56) {
858
+ break;
859
+ }
860
+ message.refreshIndex = reader.int32();
861
+ continue;
862
+ }
863
+ case 8: {
864
+ if (tag !== 64) {
865
+ break;
866
+ }
867
+ message.floorCents = reader.int32();
868
+ continue;
869
+ }
870
+ case 9: {
871
+ if (tag !== 72) {
872
+ break;
873
+ }
874
+ message.floorSource = reader.int32();
875
+ continue;
876
+ }
877
+ case 10: {
878
+ if (tag !== 80) {
879
+ break;
880
+ }
881
+ message.floorTreatmentBp = reader.int32();
882
+ continue;
883
+ }
884
+ case 11: {
885
+ if (tag !== 90) {
886
+ break;
887
+ }
888
+ message.slot = reader.string();
889
+ continue;
890
+ }
891
+ }
892
+ if ((tag & 7) === 4 || tag === 0) {
893
+ break;
894
+ }
895
+ reader.skip(tag & 7);
896
+ }
897
+ return message;
898
+ }
899
+ };
900
+ function createBaseBidTrace() {
901
+ return {
902
+ bidder: "",
903
+ cpm: 0,
904
+ currency: "",
905
+ width: 0,
906
+ height: 0,
907
+ dealId: "",
908
+ mediaType: "",
909
+ latencyMs: 0,
910
+ advertiserDomain: "",
911
+ creativeId: ""
912
+ };
913
+ }
914
+ var BidTrace = {
915
+ encode(message, writer = new import_wire.BinaryWriter()) {
916
+ if (message.bidder !== void 0 && message.bidder !== "") {
917
+ writer.uint32(10).string(message.bidder);
918
+ }
919
+ if (message.cpm !== void 0 && message.cpm !== 0) {
920
+ writer.uint32(17).double(message.cpm);
921
+ }
922
+ if (message.currency !== void 0 && message.currency !== "") {
923
+ writer.uint32(26).string(message.currency);
924
+ }
925
+ if (message.width !== void 0 && message.width !== 0) {
926
+ writer.uint32(32).int32(message.width);
927
+ }
928
+ if (message.height !== void 0 && message.height !== 0) {
929
+ writer.uint32(40).int32(message.height);
930
+ }
931
+ if (message.dealId !== void 0 && message.dealId !== "") {
932
+ writer.uint32(50).string(message.dealId);
933
+ }
934
+ if (message.mediaType !== void 0 && message.mediaType !== "") {
935
+ writer.uint32(58).string(message.mediaType);
936
+ }
937
+ if (message.latencyMs !== void 0 && message.latencyMs !== 0) {
938
+ writer.uint32(65).double(message.latencyMs);
939
+ }
940
+ if (message.advertiserDomain !== void 0 && message.advertiserDomain !== "") {
941
+ writer.uint32(74).string(message.advertiserDomain);
942
+ }
943
+ if (message.creativeId !== void 0 && message.creativeId !== "") {
944
+ writer.uint32(82).string(message.creativeId);
945
+ }
946
+ return writer;
947
+ },
948
+ decode(input, length) {
949
+ const reader = input instanceof import_wire.BinaryReader ? input : new import_wire.BinaryReader(input);
950
+ const end = length === void 0 ? reader.len : reader.pos + length;
951
+ const message = createBaseBidTrace();
952
+ while (reader.pos < end) {
953
+ const tag = reader.uint32();
954
+ switch (tag >>> 3) {
955
+ case 1: {
956
+ if (tag !== 10) {
957
+ break;
958
+ }
959
+ message.bidder = reader.string();
960
+ continue;
961
+ }
962
+ case 2: {
963
+ if (tag !== 17) {
964
+ break;
965
+ }
966
+ message.cpm = reader.double();
967
+ continue;
968
+ }
969
+ case 3: {
970
+ if (tag !== 26) {
971
+ break;
972
+ }
973
+ message.currency = reader.string();
974
+ continue;
975
+ }
976
+ case 4: {
977
+ if (tag !== 32) {
978
+ break;
979
+ }
980
+ message.width = reader.int32();
981
+ continue;
982
+ }
983
+ case 5: {
984
+ if (tag !== 40) {
985
+ break;
986
+ }
987
+ message.height = reader.int32();
988
+ continue;
989
+ }
990
+ case 6: {
991
+ if (tag !== 50) {
992
+ break;
993
+ }
994
+ message.dealId = reader.string();
995
+ continue;
996
+ }
997
+ case 7: {
998
+ if (tag !== 58) {
999
+ break;
1000
+ }
1001
+ message.mediaType = reader.string();
1002
+ continue;
1003
+ }
1004
+ case 8: {
1005
+ if (tag !== 65) {
1006
+ break;
1007
+ }
1008
+ message.latencyMs = reader.double();
1009
+ continue;
1010
+ }
1011
+ case 9: {
1012
+ if (tag !== 74) {
1013
+ break;
1014
+ }
1015
+ message.advertiserDomain = reader.string();
1016
+ continue;
1017
+ }
1018
+ case 10: {
1019
+ if (tag !== 82) {
1020
+ break;
1021
+ }
1022
+ message.creativeId = reader.string();
1023
+ continue;
1024
+ }
1025
+ }
1026
+ if ((tag & 7) === 4 || tag === 0) {
1027
+ break;
1028
+ }
1029
+ reader.skip(tag & 7);
1030
+ }
1031
+ return message;
1032
+ }
1033
+ };
1034
+
1035
+ // src/ids.ts
1036
+ var CANONICAL_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1037
+ var UUID_BYTES = 16;
1038
+ var utf8Encoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
1039
+ var utf8Decoder = typeof TextDecoder !== "undefined" ? new TextDecoder() : null;
1040
+ function idToBytes(id) {
1041
+ if (!id) return new Uint8Array(0);
1042
+ let clean = id.trim();
1043
+ if (clean.startsWith("{") && clean.endsWith("}")) {
1044
+ clean = clean.slice(1, -1).trim();
1045
+ }
1046
+ const lower = clean.toLowerCase();
1047
+ if (CANONICAL_UUID.test(lower)) {
1048
+ const hex = lower.replace(/-/g, "");
1049
+ const out2 = new Uint8Array(UUID_BYTES);
1050
+ for (let i = 0; i < UUID_BYTES; i++) {
1051
+ out2[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
1052
+ }
1053
+ return out2;
1054
+ }
1055
+ if (utf8Encoder) return utf8Encoder.encode(id);
1056
+ const out = new Uint8Array(id.length);
1057
+ for (let i = 0; i < id.length; i++) out[i] = id.charCodeAt(i) & 255;
1058
+ return out;
1059
+ }
1060
+ function idToString(bytes) {
1061
+ if (!bytes || bytes.length === 0) return "";
1062
+ if (bytes.length === UUID_BYTES) {
1063
+ let hex = "";
1064
+ for (let i = 0; i < UUID_BYTES; i++) hex += bytes[i].toString(16).padStart(2, "0");
1065
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1066
+ }
1067
+ if (utf8Decoder) return utf8Decoder.decode(bytes);
1068
+ let s = "";
1069
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
1070
+ return s;
1071
+ }
1072
+ function normalizeSampleRate(rate) {
1073
+ if (typeof rate !== "number" || !Number.isFinite(rate) || rate <= 0 || rate > 1) {
1074
+ return 1;
1075
+ }
1076
+ return rate;
1077
+ }
1078
+ function isVisitorSampled(visitorKey, sampleRate) {
1079
+ const rate = normalizeSampleRate(sampleRate);
1080
+ if (rate >= 1) return true;
1081
+ if (!visitorKey) return true;
1082
+ let hash = 2166136261;
1083
+ for (let i = 0; i < visitorKey.length; i++) {
1084
+ hash ^= visitorKey.charCodeAt(i);
1085
+ hash = Math.imul(hash, 16777619);
1086
+ }
1087
+ return (hash >>> 0) / 4294967296 < rate;
1088
+ }
1089
+
1090
+ // ../../protogen/usage_event.ts
1091
+ var usage_event_exports = {};
1092
+ __export(usage_event_exports, {
1093
+ UsageBatch: () => UsageBatch,
1094
+ UsageEvent: () => UsageEvent,
1095
+ UsageUnit: () => UsageUnit,
1096
+ protobufPackage: () => protobufPackage
1097
+ });
1098
+ var import_wire2 = require("@bufbuild/protobuf/wire");
1099
+ var protobufPackage = "bidspark";
1100
+ var UsageUnit = { USAGE_UNIT_UNSPECIFIED: 0, AUCTION: 1, SERVER_AUCTION: 2, UNRECOGNIZED: -1 };
1101
+ function createBaseUsageEvent() {
1102
+ return { unit: 0, usageId: new Uint8Array(0), timestampMs: "0", slots: 0 };
1103
+ }
1104
+ var UsageEvent = {
1105
+ encode(message, writer = new import_wire2.BinaryWriter()) {
1106
+ if (message.unit !== void 0 && message.unit !== 0) {
1107
+ writer.uint32(8).int32(message.unit);
1108
+ }
1109
+ if (message.usageId !== void 0 && message.usageId.length !== 0) {
1110
+ writer.uint32(18).bytes(message.usageId);
1111
+ }
1112
+ if (message.timestampMs !== void 0 && message.timestampMs !== "0") {
1113
+ writer.uint32(24).int64(message.timestampMs);
1114
+ }
1115
+ if (message.slots !== void 0 && message.slots !== 0) {
1116
+ writer.uint32(32).uint32(message.slots);
1117
+ }
1118
+ return writer;
1119
+ },
1120
+ decode(input, length) {
1121
+ const reader = input instanceof import_wire2.BinaryReader ? input : new import_wire2.BinaryReader(input);
1122
+ const end = length === void 0 ? reader.len : reader.pos + length;
1123
+ const message = createBaseUsageEvent();
1124
+ while (reader.pos < end) {
1125
+ const tag = reader.uint32();
1126
+ switch (tag >>> 3) {
1127
+ case 1: {
1128
+ if (tag !== 8) {
1129
+ break;
1130
+ }
1131
+ message.unit = reader.int32();
1132
+ continue;
1133
+ }
1134
+ case 2: {
1135
+ if (tag !== 18) {
1136
+ break;
1137
+ }
1138
+ message.usageId = reader.bytes();
1139
+ continue;
1140
+ }
1141
+ case 3: {
1142
+ if (tag !== 24) {
1143
+ break;
1144
+ }
1145
+ message.timestampMs = reader.int64().toString();
1146
+ continue;
1147
+ }
1148
+ case 4: {
1149
+ if (tag !== 32) {
1150
+ break;
1151
+ }
1152
+ message.slots = reader.uint32();
1153
+ continue;
1154
+ }
1155
+ }
1156
+ if ((tag & 7) === 4 || tag === 0) {
1157
+ break;
1158
+ }
1159
+ reader.skip(tag & 7);
1160
+ }
1161
+ return message;
1162
+ }
1163
+ };
1164
+ function createBaseUsageBatch() {
1165
+ return { pageviewId: new Uint8Array(0), events: [] };
1166
+ }
1167
+ var UsageBatch = {
1168
+ encode(message, writer = new import_wire2.BinaryWriter()) {
1169
+ if (message.pageviewId !== void 0 && message.pageviewId.length !== 0) {
1170
+ writer.uint32(10).bytes(message.pageviewId);
1171
+ }
1172
+ if (message.events !== void 0 && message.events.length !== 0) {
1173
+ for (const v of message.events) {
1174
+ UsageEvent.encode(v, writer.uint32(18).fork()).join();
1175
+ }
1176
+ }
1177
+ return writer;
1178
+ },
1179
+ decode(input, length) {
1180
+ const reader = input instanceof import_wire2.BinaryReader ? input : new import_wire2.BinaryReader(input);
1181
+ const end = length === void 0 ? reader.len : reader.pos + length;
1182
+ const message = createBaseUsageBatch();
1183
+ while (reader.pos < end) {
1184
+ const tag = reader.uint32();
1185
+ switch (tag >>> 3) {
1186
+ case 1: {
1187
+ if (tag !== 10) {
1188
+ break;
1189
+ }
1190
+ message.pageviewId = reader.bytes();
1191
+ continue;
1192
+ }
1193
+ case 2: {
1194
+ if (tag !== 18) {
1195
+ break;
1196
+ }
1197
+ const el = UsageEvent.decode(reader, reader.uint32());
1198
+ if (el !== void 0) {
1199
+ message.events.push(el);
1200
+ }
1201
+ continue;
1202
+ }
1203
+ }
1204
+ if ((tag & 7) === 4 || tag === 0) {
1205
+ break;
1206
+ }
1207
+ reader.skip(tag & 7);
1208
+ }
1209
+ return message;
1210
+ }
1211
+ };
1212
+
1213
+ // src/beacon.ts
1214
+ var SAFE_CONTENT_TYPE = "text/plain";
1215
+ function generateUUID() {
1216
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1217
+ return crypto.randomUUID();
1218
+ }
1219
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1220
+ const r = Math.random() * 16 | 0;
1221
+ const v = c === "x" ? r : r & 3 | 8;
1222
+ return v.toString(16);
1223
+ });
1224
+ }
1225
+ function sendEvents(opts) {
1226
+ if (!opts || !opts.endpoint || !opts.propertyId || !opts.events || opts.events.length === 0) {
1227
+ return false;
1228
+ }
1229
+ const pageviewId = opts.pageviewId || generateUUID();
1230
+ const sampleRate = normalizeSampleRate(opts.sampleRate);
1231
+ if (sampleRate < 1 && !isVisitorSampled(opts.userId || pageviewId, sampleRate)) {
1232
+ return false;
1233
+ }
1234
+ const g = typeof globalThis !== "undefined" ? globalThis : void 0;
1235
+ const win = g && "window" in g ? g.window : void 0;
1236
+ const loc = win?.location || g?.location;
1237
+ const pageUrl = loc?.href || "";
1238
+ const domain = loc?.hostname || "";
1239
+ const batchUrl = `${opts.endpoint.replace(/\/+$/, "")}/${opts.propertyId}`;
1240
+ const traceEvents = opts.events.map((e) => ({
1241
+ timestampMs: Date.now(),
1242
+ type: e.type,
1243
+ eventName: "",
1244
+ auctionId: new Uint8Array(0),
1245
+ transactionId: new Uint8Array(0),
1246
+ adUnitCode: "",
1247
+ bid: void 0,
1248
+ namespace: "",
1249
+ eventId: idToBytes(generateUUID()),
1250
+ metadata: e.metadata,
1251
+ viewableDurationMs: void 0,
1252
+ bidderOutcomes: []
1253
+ }));
1254
+ const nav = g && "navigator" in g ? g.navigator : void 0;
1255
+ const automated = Boolean(nav && nav.webdriver === true);
1256
+ const batch = {
1257
+ propertyId: idToBytes(opts.propertyId),
1258
+ pageviewId: idToBytes(pageviewId),
1259
+ sessionId: new Uint8Array(0),
1260
+ userId: "",
1261
+ pageUrl,
1262
+ country: opts.geo?.country,
1263
+ region: opts.geo?.region,
1264
+ deviceType: void 0,
1265
+ domain,
1266
+ events: traceEvents,
1267
+ ...sampleRate < 1 ? { sampleRate } : {},
1268
+ ...automated ? { automated: true } : {}
1269
+ };
1270
+ const encoded = TraceEventBatch.encode(batch).finish();
1271
+ if (nav && typeof nav.sendBeacon === "function") {
1272
+ try {
1273
+ const blob = new Blob([encoded], { type: SAFE_CONTENT_TYPE });
1274
+ if (nav.sendBeacon(batchUrl, blob)) {
1275
+ return true;
1276
+ }
1277
+ } catch {
1278
+ }
1279
+ }
1280
+ if (typeof fetch === "function") {
1281
+ try {
1282
+ const init = {
1283
+ method: "POST",
1284
+ headers: { "Content-Type": SAFE_CONTENT_TYPE },
1285
+ body: encoded
1286
+ };
1287
+ init.keepalive = true;
1288
+ fetch(batchUrl, init).catch(() => {
1289
+ });
1290
+ return true;
1291
+ } catch {
1292
+ return false;
1293
+ }
1294
+ }
1295
+ return false;
1296
+ }
1297
+
1298
+ // src/usage.ts
1299
+ var USAGE_FLUSH_INTERVAL_MS = 1e4;
1300
+ var MAX_USAGE_BATCH_SIZE = 200;
1301
+ var UsageRecorder = class {
1302
+ endpoint;
1303
+ propertyId;
1304
+ pageviewIdStr;
1305
+ pageviewIdBytes;
1306
+ queue = [];
1307
+ flushTimer = null;
1308
+ boundPageHide;
1309
+ boundVisibilityChange;
1310
+ isDestroyed = false;
1311
+ constructor(opts) {
1312
+ this.endpoint = (opts.endpoint || "").replace(/\/+$/, "");
1313
+ this.propertyId = opts.propertyId || "";
1314
+ this.pageviewIdStr = opts.pageviewId || generateUUID();
1315
+ const rawBytes = idToBytes(this.pageviewIdStr);
1316
+ this.pageviewIdBytes = rawBytes.length === 16 ? rawBytes : idToBytes(generateUUID());
1317
+ this.boundPageHide = () => this.flush();
1318
+ this.boundVisibilityChange = () => {
1319
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") {
1320
+ this.flush();
1321
+ }
1322
+ };
1323
+ if (typeof window !== "undefined") {
1324
+ window.addEventListener("pagehide", this.boundPageHide);
1325
+ if (typeof document !== "undefined") {
1326
+ document.addEventListener("visibilitychange", this.boundVisibilityChange);
1327
+ }
1328
+ }
1329
+ }
1330
+ getEndpoint() {
1331
+ return this.endpoint;
1332
+ }
1333
+ setEndpoint(endpoint) {
1334
+ this.endpoint = (endpoint || "").replace(/\/+$/, "");
1335
+ }
1336
+ getPropertyId() {
1337
+ return this.propertyId;
1338
+ }
1339
+ setPropertyId(propertyId) {
1340
+ this.propertyId = propertyId || "";
1341
+ }
1342
+ getPageviewId() {
1343
+ return this.pageviewIdStr;
1344
+ }
1345
+ setPageviewId(pageviewId) {
1346
+ this.pageviewIdStr = pageviewId || generateUUID();
1347
+ this.pageviewIdBytes = idToBytes(this.pageviewIdStr);
1348
+ }
1349
+ getQueueLength() {
1350
+ return this.queue.length;
1351
+ }
1352
+ record(auctionId, slots, unit = UsageUnit.AUCTION) {
1353
+ if (this.isDestroyed || !auctionId) return;
1354
+ let usageId = idToBytes(auctionId);
1355
+ if (usageId.length !== 16) {
1356
+ usageId = idToBytes(generateUUID());
1357
+ }
1358
+ this.queue.push({
1359
+ unit,
1360
+ usageId,
1361
+ timestampMs: String(Date.now()),
1362
+ slots: typeof slots === "number" && slots > 0 ? slots : 0
1363
+ });
1364
+ if (this.queue.length >= MAX_USAGE_BATCH_SIZE) {
1365
+ this.flush();
1366
+ return;
1367
+ }
1368
+ if (!this.flushTimer && typeof setTimeout !== "undefined") {
1369
+ this.flushTimer = setTimeout(() => {
1370
+ this.flushTimer = null;
1371
+ this.flush();
1372
+ }, USAGE_FLUSH_INTERVAL_MS);
1373
+ }
1374
+ }
1375
+ flush() {
1376
+ if (this.flushTimer) {
1377
+ clearTimeout(this.flushTimer);
1378
+ this.flushTimer = null;
1379
+ }
1380
+ if (this.queue.length === 0 || !this.endpoint || !this.propertyId) {
1381
+ return false;
1382
+ }
1383
+ let sentAny = false;
1384
+ while (this.queue.length > 0) {
1385
+ const eventsToFlush = this.queue.splice(0, MAX_USAGE_BATCH_SIZE);
1386
+ const batch = {
1387
+ pageviewId: this.pageviewIdBytes,
1388
+ events: eventsToFlush
1389
+ };
1390
+ const encoded = UsageBatch.encode(batch).finish();
1391
+ const base = this.endpoint.replace(new RegExp(`/${this.propertyId}$`), "");
1392
+ const url = `${base}/${this.propertyId}`;
1393
+ let sent = false;
1394
+ if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
1395
+ try {
1396
+ const blob = new Blob([encoded], { type: SAFE_CONTENT_TYPE });
1397
+ sent = navigator.sendBeacon(url, blob);
1398
+ } catch {
1399
+ sent = false;
1400
+ }
1401
+ }
1402
+ const fetchFn = typeof globalThis !== "undefined" && typeof globalThis.fetch === "function" ? globalThis.fetch : typeof fetch === "function" ? fetch : null;
1403
+ if (!sent && fetchFn) {
1404
+ try {
1405
+ fetchFn(url, {
1406
+ method: "POST",
1407
+ headers: { "Content-Type": SAFE_CONTENT_TYPE },
1408
+ body: encoded,
1409
+ keepalive: true
1410
+ }).catch(() => {
1411
+ });
1412
+ sent = true;
1413
+ } catch {
1414
+ sent = false;
1415
+ }
1416
+ }
1417
+ if (sent) sentAny = true;
1418
+ }
1419
+ return sentAny;
1420
+ }
1421
+ destroy() {
1422
+ if (this.queue.length > 0) {
1423
+ this.flush();
1424
+ }
1425
+ this.isDestroyed = true;
1426
+ if (this.flushTimer) {
1427
+ clearTimeout(this.flushTimer);
1428
+ this.flushTimer = null;
1429
+ }
1430
+ if (typeof window !== "undefined") {
1431
+ window.removeEventListener("pagehide", this.boundPageHide);
1432
+ if (typeof document !== "undefined") {
1433
+ document.removeEventListener("visibilitychange", this.boundVisibilityChange);
1434
+ }
1435
+ }
1436
+ }
1437
+ };
1438
+
1439
+ // src/prebid-analytics.ts
1440
+ var DEFAULT_ALIAS = "ads";
1441
+ var FLUSH_INTERVAL_MS = 1e4;
1442
+ var MAX_ERRORS_PER_SESSION = 50;
1443
+ var MAX_CONSENT_EVENTS_PER_PAGEVIEW = 20;
1444
+ var MAX_QUEUE_SIZE = 200;
1445
+ var MAX_SEND_BACKOFF_MS = 5 * 60 * 1e3;
1446
+ var MAX_CONSECUTIVE_SEND_FAILURES = 10;
1447
+ var MAX_PAYLOAD_BYTES = 32 * 1024;
1448
+ var MAX_METADATA_VALUE_CHARS = 1024;
1449
+ var MAX_METADATA_ENTRIES = 16;
1450
+ var SAFE_CONTENT_TYPE2 = "text/plain";
1451
+ var PENDING_BATCH_KEY_PREFIX = "ads_pending_";
1452
+ var MAX_PENDING_BATCHES = 20;
1453
+ var PENDING_BATCH_MAX_AGE_MS = 2 * 60 * 60 * 1e3;
1454
+ var PENDING_BATCH_CLEANUP_DELAY_MS = 1e4;
1455
+ var EVENT_NAME_TO_TYPE = {
1456
+ auctionStart: TraceEventType.AUCTION_START,
1457
+ auctionEnd: TraceEventType.AUCTION_END,
1458
+ bidWin: TraceEventType.BID_WIN,
1459
+ adRenderFailed: TraceEventType.AD_RENDER_FAILED,
1460
+ click: TraceEventType.CLICK,
1461
+ impression: TraceEventType.IMPRESSION,
1462
+ timeInView: TraceEventType.TIME_IN_VIEW,
1463
+ viewable: TraceEventType.VIEWABLE
1464
+ };
1465
+ var LEVEL_TO_TYPE = {
1466
+ WARN: TraceEventType.WARN,
1467
+ ERROR: TraceEventType.ERROR
1468
+ };
1469
+ var SELF_NAMING_TYPES = /* @__PURE__ */ new Set([
1470
+ TraceEventType.ERROR,
1471
+ TraceEventType.WARN
1472
+ ]);
1473
+ var REVENUE_FLUSH_DELAY_MS = 3e3;
1474
+ var REVENUE_FLUSH_TYPES = /* @__PURE__ */ new Set([
1475
+ TraceEventType.IMPRESSION,
1476
+ TraceEventType.BID_WIN,
1477
+ TraceEventType.CLICK
1478
+ ]);
1479
+ var CACHED_BID_TTL_MS = 30 * 60 * 1e3;
1480
+ var MAX_CACHED_BID_KEYS = 200;
1481
+ var MAX_IMPRESSION_KEYS = 1e3;
1482
+ var MAX_TRACKED_AUCTIONS = 50;
1483
+ var MAX_FLOOR_DECISIONS = 200;
1484
+ var FLOOR_SOURCE_PROTO = {
1485
+ static: FloorSource.FLOOR_SOURCE_STATIC,
1486
+ pool: FloorSource.FLOOR_SOURCE_POOL,
1487
+ none: FloorSource.FLOOR_SOURCE_NONE
1488
+ };
1489
+ var CLICK_DEDUP_MS = 1e3;
1490
+ var SESSION_KEY = "ads_session";
1491
+ var SESSION_TS_KEY = "ads_session_ts";
1492
+ var THIRTY_MINUTES_MS = 30 * 60 * 1e3;
1493
+ var inMemorySessionId = null;
1494
+ var inMemorySessionTs = 0;
1495
+ var sessionStartedHere = false;
1496
+ var storageAllowed = true;
1497
+ function generateUUID2() {
1498
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1499
+ return crypto.randomUUID();
1500
+ }
1501
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1502
+ const r = Math.random() * 16 | 0;
1503
+ const v = c === "x" ? r : r & 3 | 8;
1504
+ return v.toString(16);
1505
+ });
1506
+ }
1507
+ function bytesToBase64(bytes) {
1508
+ let binary = "";
1509
+ const chunk = 8192;
1510
+ for (let i = 0; i < bytes.length; i += chunk) {
1511
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
1512
+ }
1513
+ return btoa(binary);
1514
+ }
1515
+ function base64ToBytes(b64) {
1516
+ const binary = atob(b64);
1517
+ const bytes = new Uint8Array(binary.length);
1518
+ for (let i = 0; i < binary.length; i++) {
1519
+ bytes[i] = binary.charCodeAt(i);
1520
+ }
1521
+ return bytes;
1522
+ }
1523
+ function isTrustedEndpoint(raw) {
1524
+ if (!raw) return false;
1525
+ let url;
1526
+ try {
1527
+ url = new URL(raw);
1528
+ } catch {
1529
+ return false;
1530
+ }
1531
+ if (url.username || url.password) return false;
1532
+ if (url.protocol === "https:") return true;
1533
+ if (url.protocol === "http:") {
1534
+ return url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
1535
+ }
1536
+ return false;
1537
+ }
1538
+ function boundMetadata(metadata) {
1539
+ const bounded = {};
1540
+ let count = 0;
1541
+ for (const key of Object.keys(metadata)) {
1542
+ if (count >= MAX_METADATA_ENTRIES) break;
1543
+ const value = metadata[key];
1544
+ if (value === void 0 || value === null) continue;
1545
+ const str = String(value);
1546
+ bounded[key] = str.length > MAX_METADATA_VALUE_CHARS ? `${str.slice(0, MAX_METADATA_VALUE_CHARS)}...[truncated]` : str;
1547
+ count++;
1548
+ }
1549
+ return bounded;
1550
+ }
1551
+ function sameEndpointOrigin(a, b) {
1552
+ if (!a || !b) return false;
1553
+ try {
1554
+ return new URL(a).origin === new URL(b).origin;
1555
+ } catch {
1556
+ return false;
1557
+ }
1558
+ }
1559
+ var SESSION_PERSIST_INTERVAL_MS = 60 * 1e3;
1560
+ var persistedSessionTs = 0;
1561
+ var ACTIVITY_EVENTS = ["pointerdown", "pointermove", "keydown", "scroll", "wheel", "touchstart"];
1562
+ var activityListenersBound = false;
1563
+ var sessionResumeListeners = /* @__PURE__ */ new Set();
1564
+ function persistSessionTs(ts) {
1565
+ try {
1566
+ if (typeof localStorage !== "undefined") {
1567
+ localStorage.setItem(SESSION_TS_KEY, ts.toString());
1568
+ persistedSessionTs = ts;
1569
+ }
1570
+ } catch {
1571
+ }
1572
+ }
1573
+ function isSessionActive(now = Date.now()) {
1574
+ return inMemorySessionTs > 0 && now - inMemorySessionTs <= THIRTY_MINUTES_MS;
1575
+ }
1576
+ function onSessionResume(listener) {
1577
+ bindActivityListeners();
1578
+ sessionResumeListeners.add(listener);
1579
+ return () => {
1580
+ sessionResumeListeners.delete(listener);
1581
+ };
1582
+ }
1583
+ function recordActivity() {
1584
+ const now = Date.now();
1585
+ const lapsed = !!inMemorySessionId && !isSessionActive(now);
1586
+ inMemorySessionTs = now;
1587
+ if (lapsed) {
1588
+ inMemorySessionId = null;
1589
+ for (const listener of sessionResumeListeners) listener();
1590
+ return;
1591
+ }
1592
+ if (!storageAllowed || !inMemorySessionId || persistedSessionTs === 0) return;
1593
+ if (now - persistedSessionTs < SESSION_PERSIST_INTERVAL_MS) return;
1594
+ persistSessionTs(now);
1595
+ }
1596
+ function sessionNeedsSync() {
1597
+ return !inMemorySessionId || storageAllowed && persistedSessionTs === 0;
1598
+ }
1599
+ function bindActivityListeners() {
1600
+ if (activityListenersBound || typeof window === "undefined") return;
1601
+ activityListenersBound = true;
1602
+ const onActivity = () => recordActivity();
1603
+ for (const name of ACTIVITY_EVENTS) {
1604
+ window.addEventListener(name, onActivity, { passive: true, capture: true });
1605
+ }
1606
+ if (typeof document !== "undefined") {
1607
+ document.addEventListener("visibilitychange", () => {
1608
+ if (document.visibilityState === "visible") recordActivity();
1609
+ });
1610
+ }
1611
+ }
1612
+ function getOrCreateSessionId() {
1613
+ const now = Date.now();
1614
+ const memoryFresh = !!inMemorySessionId && isSessionActive(now);
1615
+ try {
1616
+ if (storageAllowed && typeof localStorage !== "undefined") {
1617
+ const storedId = localStorage.getItem(SESSION_KEY);
1618
+ const tsStr = localStorage.getItem(SESSION_TS_KEY);
1619
+ const storedTs = tsStr ? parseInt(tsStr, 10) || 0 : 0;
1620
+ if (storedId && storedTs && now - storedTs <= THIRTY_MINUTES_MS) {
1621
+ if (inMemorySessionId !== storedId) {
1622
+ sessionStartedHere = false;
1623
+ }
1624
+ if (inMemorySessionId !== storedId || inMemorySessionTs < storedTs) {
1625
+ inMemorySessionId = storedId;
1626
+ inMemorySessionTs = Math.max(inMemorySessionTs, storedTs);
1627
+ }
1628
+ if (persistedSessionTs === 0) persistedSessionTs = storedTs;
1629
+ return storedId;
1630
+ }
1631
+ const newId = memoryFresh ? inMemorySessionId : generateUUID2();
1632
+ if (!memoryFresh) {
1633
+ sessionStartedHere = true;
1634
+ inMemorySessionTs = now;
1635
+ }
1636
+ localStorage.setItem(SESSION_KEY, newId);
1637
+ persistSessionTs(inMemorySessionTs);
1638
+ inMemorySessionId = newId;
1639
+ return newId;
1640
+ }
1641
+ } catch {
1642
+ }
1643
+ if (memoryFresh) return inMemorySessionId;
1644
+ sessionStartedHere = true;
1645
+ inMemorySessionId = generateUUID2();
1646
+ inMemorySessionTs = now;
1647
+ return inMemorySessionId;
1648
+ }
1649
+ function sessionStarted() {
1650
+ return sessionStartedHere;
1651
+ }
1652
+ function clearStoredSession() {
1653
+ persistedSessionTs = 0;
1654
+ try {
1655
+ if (typeof localStorage !== "undefined") {
1656
+ localStorage.removeItem(SESSION_KEY);
1657
+ localStorage.removeItem(SESSION_TS_KEY);
1658
+ }
1659
+ } catch {
1660
+ }
1661
+ }
1662
+ var USER_ID_KEY = "ads_uid";
1663
+ function getOrCreateUserId() {
1664
+ try {
1665
+ if (storageAllowed && typeof localStorage !== "undefined") {
1666
+ const stored = localStorage.getItem(USER_ID_KEY);
1667
+ if (stored) return stored;
1668
+ const newId = generateUUID2();
1669
+ localStorage.setItem(USER_ID_KEY, newId);
1670
+ return newId;
1671
+ }
1672
+ } catch {
1673
+ }
1674
+ return "";
1675
+ }
1676
+ function clearStoredUserId() {
1677
+ try {
1678
+ if (typeof localStorage !== "undefined") {
1679
+ localStorage.removeItem(USER_ID_KEY);
1680
+ }
1681
+ } catch {
1682
+ }
1683
+ }
1684
+ function storageAllowedBy(record) {
1685
+ return record.regime !== "tcf" || Boolean(record.purposesConsented?.includes(1));
1686
+ }
1687
+ function tcDataToConsentRecord(tcData) {
1688
+ const purposes = [];
1689
+ if (tcData?.purpose?.consents) {
1690
+ for (const [k, v] of Object.entries(tcData.purpose.consents)) {
1691
+ if (v) purposes.push(Number(k));
1692
+ }
1693
+ }
1694
+ return {
1695
+ regime: tcData?.gdprApplies === false ? "us" : "tcf",
1696
+ action: "replay",
1697
+ cmpId: tcData?.cmpId ?? 0,
1698
+ cmpVersion: tcData?.cmpVersion ?? 0,
1699
+ purposesConsented: purposes
1700
+ };
1701
+ }
1702
+ function probeTcfStorageAllowed() {
1703
+ if (typeof window === "undefined") return void 0;
1704
+ const win = window;
1705
+ if (typeof win.__tcfapi !== "function") return void 0;
1706
+ let allowed = void 0;
1707
+ try {
1708
+ win.__tcfapi("getTCData", 2, (tcData, success) => {
1709
+ if (success && tcData) {
1710
+ allowed = storageAllowedBy(tcDataToConsentRecord(tcData));
1711
+ }
1712
+ });
1713
+ } catch {
1714
+ }
1715
+ return allowed !== void 0 ? allowed : false;
1716
+ }
1717
+ var tcfListenerAttached = false;
1718
+ function resetTcfListener() {
1719
+ tcfListenerAttached = false;
1720
+ }
1721
+ function attachTcfListener() {
1722
+ if (tcfListenerAttached || typeof window === "undefined") return;
1723
+ const win = window;
1724
+ if (typeof win.__tcfapi !== "function") return;
1725
+ tcfListenerAttached = true;
1726
+ try {
1727
+ win.__tcfapi("addEventListener", 2, (tcData, success) => {
1728
+ if (!success || !tcData) return;
1729
+ BidsparkPrebidAnalytics.setStorageAllowed(storageAllowedBy(tcDataToConsentRecord(tcData)));
1730
+ });
1731
+ } catch {
1732
+ }
1733
+ }
1734
+ function cmpStorageAllowed(alias) {
1735
+ if (typeof window === "undefined") return void 0;
1736
+ const win = window;
1737
+ const record = win[alias]?.consent?.getRecord?.() || null;
1738
+ if (record) return storageAllowedBy(record);
1739
+ return win[`__${alias}_cmp`]?.gdpr ? false : void 0;
1740
+ }
1741
+ function escapeKeyPart(str) {
1742
+ return String(str ?? "").replace(/%/g, "%25").replace(/:/g, "%3A");
1743
+ }
1744
+ function getPrebidEventKey(eventName, data) {
1745
+ switch (eventName) {
1746
+ case "auctionInit":
1747
+ return `auctionInit:${escapeKeyPart(data?.auctionId)}`;
1748
+ case "auctionEnd":
1749
+ return `auctionEnd:${escapeKeyPart(data?.auctionId)}`;
1750
+ case "bidRequested": {
1751
+ const bids = Array.isArray(data?.bids) ? data.bids.map((b) => escapeKeyPart(b?.bidId || b?.transactionId || b?.adUnitCode)).join(",") : "";
1752
+ return `bidRequested:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${bids}`;
1753
+ }
1754
+ case "bidResponse": {
1755
+ const bid = data || {};
1756
+ const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1757
+ const price = bid.originalCpm ?? bid.cpm ?? "";
1758
+ return `bidResponse:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1759
+ }
1760
+ case "bidTimeout": {
1761
+ const items = Array.isArray(data) ? data : data ? [data] : [];
1762
+ return "bidTimeout:" + items.map(
1763
+ (t) => `${escapeKeyPart(t?.auctionId)}:${escapeKeyPart(t?.bidderCode || t?.bidder)}:${escapeKeyPart(t?.bidId || t?.transactionId || t?.adUnitCode)}`
1764
+ ).join(",");
1765
+ }
1766
+ case "bidWon": {
1767
+ const bid = data || {};
1768
+ const uniqueBidId = bid.creativeId || bid.adId || bid.requestId || bid.bidId || "";
1769
+ const price = bid.originalCpm ?? bid.cpm ?? "";
1770
+ return `bidWon:${escapeKeyPart(bid.auctionId)}:${escapeKeyPart(bid.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueBidId)}:${escapeKeyPart(price)}`;
1771
+ }
1772
+ case "noBid":
1773
+ return `noBid:${escapeKeyPart(data?.auctionId)}:${escapeKeyPart(data?.adUnitCode)}:${escapeKeyPart(data?.bidderCode || data?.bidder)}:${escapeKeyPart(data?.bidId || data?.transactionId)}`;
1774
+ case "adRenderFailed": {
1775
+ const bid = data?.bid || {};
1776
+ 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)}`;
1777
+ }
1778
+ case "adRenderSucceeded": {
1779
+ const bid = data?.bid || data || {};
1780
+ const uniqueId = bid.creativeId || bid.adId || data?.adId || "";
1781
+ const price = bid.originalCpm ?? bid.cpm ?? "";
1782
+ return `adRenderSucceeded:${escapeKeyPart(bid.auctionId || data?.auctionId)}:${escapeKeyPart(bid.adUnitCode || data?.adUnitCode)}:${escapeKeyPart(bid.bidderCode || bid.bidder)}:${escapeKeyPart(uniqueId)}:${escapeKeyPart(price)}`;
1783
+ }
1784
+ case "setTargeting":
1785
+ return `setTargeting:${Object.keys(data || {}).sort().map(escapeKeyPart).join(",")}`;
1786
+ case "auctionDebug":
1787
+ return `auctionDebug:${escapeKeyPart(data?.type)}:${escapeKeyPart(String(data?.arguments?.[0] ?? "").slice(0, 50))}`;
1788
+ default:
1789
+ return "";
1790
+ }
1791
+ }
1792
+ var PrebidEventDeduper = class {
1793
+ // Tracks object identity per event name to allow identical bid objects across bidResponse and bidWon.
1794
+ seenObjects = /* @__PURE__ */ new WeakMap();
1795
+ seenKeys = /* @__PURE__ */ new Set();
1796
+ isDuplicate(eventName, data) {
1797
+ if (!data) return false;
1798
+ if (typeof data === "object") {
1799
+ const seenEvents = this.seenObjects.get(data);
1800
+ if (seenEvents) {
1801
+ if (seenEvents.has(eventName)) return true;
1802
+ seenEvents.add(eventName);
1803
+ } else {
1804
+ this.seenObjects.set(data, /* @__PURE__ */ new Set([eventName]));
1805
+ }
1806
+ }
1807
+ const key = getPrebidEventKey(eventName, data);
1808
+ if (key) {
1809
+ if (this.seenKeys.has(key)) return true;
1810
+ if (this.seenKeys.size >= 1e3) {
1811
+ const first = this.seenKeys.values().next().value;
1812
+ if (first !== void 0) this.seenKeys.delete(first);
1813
+ }
1814
+ this.seenKeys.add(key);
1815
+ }
1816
+ return false;
1817
+ }
1818
+ };
1819
+ function parseBidDimensions(bid) {
1820
+ if (Number.isFinite(bid?.width) && Number.isFinite(bid?.height)) {
1821
+ return { width: bid.width, height: bid.height };
1822
+ }
1823
+ if (typeof bid?.size === "string") {
1824
+ const match = bid.size.match(/^(\d+)x(\d+)$/);
1825
+ if (match) {
1826
+ return { width: Number(match[1]), height: Number(match[2]) };
1827
+ }
1828
+ }
1829
+ return {
1830
+ width: Number.isFinite(bid?.width) ? bid.width : 0,
1831
+ height: Number.isFinite(bid?.height) ? bid.height : 0
1832
+ };
1833
+ }
1834
+ function resolveBidPricing(bid, fallback) {
1835
+ if (Number.isFinite(bid?.cpm)) {
1836
+ return {
1837
+ cpm: bid.cpm,
1838
+ currency: bid?.currency || bid?.originalCurrency || fallback?.currency || "USD"
1839
+ };
1840
+ }
1841
+ if (Number.isFinite(bid?.originalCpm)) {
1842
+ return {
1843
+ cpm: bid.originalCpm,
1844
+ currency: bid?.originalCurrency || bid?.currency || fallback?.currency || "USD"
1845
+ };
1846
+ }
1847
+ return {
1848
+ cpm: fallback?.cpm ?? 0,
1849
+ currency: fallback?.currency || bid?.currency || bid?.originalCurrency || "USD"
1850
+ };
1851
+ }
1852
+ var defaultLogger = createLogger({
1853
+ prefix: "[analytics]",
1854
+ logLevel: "INFO"
1855
+ });
1856
+ var BidsparkPrebidAnalytics = class _BidsparkPrebidAnalytics {
1857
+ static activeInstances = /* @__PURE__ */ new Set();
1858
+ static allInstances = /* @__PURE__ */ new Set();
1859
+ static getActiveInstances() {
1860
+ return _BidsparkPrebidAnalytics.activeInstances;
1861
+ }
1862
+ static setLogLevel(level) {
1863
+ const norm = normalizeLogLevel(level);
1864
+ defaultLogger.setLevel(norm);
1865
+ for (const inst of _BidsparkPrebidAnalytics.allInstances) {
1866
+ inst.setLogLevel(norm);
1867
+ }
1868
+ }
1869
+ static getLogLevel() {
1870
+ return defaultLogger.getLevel();
1871
+ }
1872
+ /** Sets page-wide localStorage permission. Telemetry collection and delivery remain active. */
1873
+ static setStorageAllowed(allowed) {
1874
+ storageAllowed = allowed;
1875
+ persistedSessionTs = 0;
1876
+ for (const inst of _BidsparkPrebidAnalytics.allInstances) {
1877
+ inst.config.storageAllowed = allowed;
1878
+ if (!allowed) {
1879
+ inst.config.userId = "";
1880
+ inst.config.visitorId = inst.config.visitorId || inst.config.pageviewId;
1881
+ } else if (!inst.config.userId) {
1882
+ inst.config.userId = getOrCreateUserId();
1883
+ inst.config.visitorId = inst.config.visitorId || inst.config.userId || inst.config.pageviewId;
1884
+ }
1885
+ }
1886
+ }
1887
+ static isStorageAllowed() {
1888
+ return storageAllowed;
1889
+ }
1890
+ config;
1891
+ usageRecorder = null;
1892
+ queue = [];
1893
+ errorCount = 0;
1894
+ flushTimer = null;
1895
+ boundFlushBeacon;
1896
+ boundVisibilityChange;
1897
+ isEnabled = false;
1898
+ boundPbjsHandlers = [];
1899
+ // Captured at enable()/navigate() so queued events flush under origin page URL.
1900
+ pageUrl = "";
1901
+ deduper = new PrebidEventDeduper();
1902
+ consecutiveSendFailures = 0;
1903
+ nextSendAllowedAt = 0;
1904
+ replayedEventCount = 0;
1905
+ revenueFlushTimer = null;
1906
+ // Persisted batch keys tracked to prune stored batches if page survives hide/unload.
1907
+ persistedBatchKeys = [];
1908
+ persistedCleanupTimer = null;
1909
+ // Viewability & refresh tracking
1910
+ intersectionObserver = null;
1911
+ slotViewabilityRecords = /* @__PURE__ */ new Map();
1912
+ elementToSlotId = /* @__PURE__ */ new Map();
1913
+ slotRefreshIndices = /* @__PURE__ */ new Map();
1914
+ /** Configured slot name per ad unit code, stamped on that unit's events. */
1915
+ slotNames = /* @__PURE__ */ new Map();
1916
+ slotAdSessionCounters = /* @__PURE__ */ new Map();
1917
+ slotLastAuctionIds = /* @__PURE__ */ new Map();
1918
+ pendingViewableListeners = /* @__PURE__ */ new Map();
1919
+ // Explicitly registered slot container overrides document.getElementById.
1920
+ slotElements = /* @__PURE__ */ new Map();
1921
+ clickDetachCleanups = /* @__PURE__ */ new Set();
1922
+ lastClickAt = /* @__PURE__ */ new Map();
1923
+ slotEmittedImpressionKeys = /* @__PURE__ */ new Set();
1924
+ cachedWinningBids = /* @__PURE__ */ new Map();
1925
+ videoDetachCleanups = /* @__PURE__ */ new Set();
1926
+ auctionBidderOutcomes = /* @__PURE__ */ new Map();
1927
+ floorDecisions = /* @__PURE__ */ new Map();
1928
+ recordedConsentKeys = /* @__PURE__ */ new Set();
1929
+ consentCount = 0;
1930
+ cmpDetach = null;
1931
+ pageviewEmitted = false;
1932
+ logger;
1933
+ // True when managing session lifecycle internally; false if caller supplied fixed sessionId.
1934
+ managesSessionId;
1935
+ constructor(config) {
1936
+ const tcfStorage = probeTcfStorageAllowed();
1937
+ if (typeof window !== "undefined" && typeof window.__tcfapi === "function") {
1938
+ attachTcfListener();
1939
+ }
1940
+ const storage = config.storageAllowed ?? tcfStorage ?? cmpStorageAllowed(config.alias || DEFAULT_ALIAS);
1941
+ if (storage !== void 0) {
1942
+ _BidsparkPrebidAnalytics.setStorageAllowed(storage);
1943
+ }
1944
+ const isStorageOn = storage !== void 0 ? storage : storageAllowed;
1945
+ const requestedEndpoint = config.endpoint || "";
1946
+ const endpoint = !requestedEndpoint || isTrustedEndpoint(requestedEndpoint) ? requestedEndpoint : "";
1947
+ const pageviewId = config.pageviewId || generateUUID2();
1948
+ let initialUserId = "";
1949
+ let initialVisitorId = "";
1950
+ if (isStorageOn) {
1951
+ initialUserId = config.userId || getOrCreateUserId();
1952
+ if (config.userId) {
1953
+ try {
1954
+ if (typeof localStorage !== "undefined") {
1955
+ localStorage.setItem(USER_ID_KEY, config.userId);
1956
+ }
1957
+ } catch {
1958
+ }
1959
+ }
1960
+ initialVisitorId = config.visitorId || initialUserId || pageviewId;
1961
+ } else {
1962
+ initialUserId = "";
1963
+ initialVisitorId = config.visitorId || pageviewId;
1964
+ }
1965
+ const usageEndpoint = config.usageEndpoint || "";
1966
+ this.config = {
1967
+ endpoint,
1968
+ usageEndpoint,
1969
+ propertyId: config.propertyId || "",
1970
+ pageviewId,
1971
+ sessionId: config.sessionId || "",
1972
+ userId: initialUserId,
1973
+ visitorId: initialVisitorId,
1974
+ deviceType: config.deviceType || "desktop",
1975
+ country: config.country || "",
1976
+ region: config.region || "",
1977
+ auctionEnabled: config.auctionEnabled ?? true,
1978
+ warningsEnabled: config.warningsEnabled ?? true,
1979
+ sampleRate: normalizeSampleRate(config.sampleRate),
1980
+ viewabilityEnabled: config.viewabilityEnabled ?? true,
1981
+ storageAllowed: isStorageOn,
1982
+ logLevel: config.logLevel ? normalizeLogLevel(config.logLevel) : defaultLogger.getLevel(),
1983
+ pbjsGlobalName: config.pbjsGlobalName || "pbjs",
1984
+ attachPbjsListeners: config.attachPbjsListeners ?? true,
1985
+ revenueFlushDelayMs: Number.isFinite(config.revenueFlushDelayMs) && config.revenueFlushDelayMs >= 0 ? config.revenueFlushDelayMs : REVENUE_FLUSH_DELAY_MS,
1986
+ alias: config.alias || DEFAULT_ALIAS
1987
+ };
1988
+ _BidsparkPrebidAnalytics.allInstances.add(this);
1989
+ this.logger = createLogger({
1990
+ prefix: "[analytics]",
1991
+ logLevel: this.config.logLevel
1992
+ });
1993
+ recordActivity();
1994
+ this.managesSessionId = !config.sessionId;
1995
+ if (this.managesSessionId) this.config.sessionId = getOrCreateSessionId();
1996
+ if (requestedEndpoint && !endpoint) {
1997
+ this.log(
1998
+ "ERROR",
1999
+ `Rejected untrusted analytics endpoint ${requestedEndpoint}: must be an absolute https:// URL without embedded credentials. Events will not be transmitted.`
2000
+ );
2001
+ }
2002
+ this.boundFlushBeacon = () => {
2003
+ this.flushAllSlotsTimeInView();
2004
+ this.flushBeacon();
2005
+ };
2006
+ this.boundVisibilityChange = () => this.handleVisibilityChange();
2007
+ }
2008
+ setLogLevel(level) {
2009
+ const norm = normalizeLogLevel(level);
2010
+ this.config.logLevel = norm;
2011
+ this.logger.setLevel(norm);
2012
+ defaultLogger.setLevel(norm);
2013
+ }
2014
+ getLogLevel() {
2015
+ return this.logger.getLevel();
2016
+ }
2017
+ enable() {
2018
+ if (this.isEnabled) return;
2019
+ this.isEnabled = true;
2020
+ _BidsparkPrebidAnalytics.activeInstances.add(this);
2021
+ this.logger.setLevel(this.config.logLevel);
2022
+ if (this.config.attachPbjsListeners && this.config.usageEndpoint && !this.usageRecorder) {
2023
+ this.usageRecorder = new UsageRecorder({
2024
+ endpoint: this.config.usageEndpoint,
2025
+ propertyId: this.config.propertyId,
2026
+ pageviewId: this.config.pageviewId
2027
+ });
2028
+ }
2029
+ if (!this.config.endpoint) {
2030
+ this.log("WARN", "Endpoint is empty. Analytics events will not be transmitted.");
2031
+ }
2032
+ if (this.config.viewabilityEnabled) {
2033
+ if (typeof IntersectionObserver !== "undefined") {
2034
+ this.intersectionObserver = new IntersectionObserver(this.handleIntersection.bind(this), {
2035
+ threshold: [0.5]
2036
+ });
2037
+ for (const record of this.slotViewabilityRecords.values()) {
2038
+ if (record.element) {
2039
+ this.intersectionObserver.observe(record.element);
2040
+ }
2041
+ }
2042
+ }
2043
+ }
2044
+ if (this.config.attachPbjsListeners) {
2045
+ this.attachPbjs();
2046
+ }
2047
+ this.cmpDetach = this.attachCmp();
2048
+ if (typeof window !== "undefined") {
2049
+ if (!this.pageUrl) {
2050
+ try {
2051
+ const u = new URL(window.location.href);
2052
+ this.pageUrl = u.origin + u.pathname;
2053
+ } catch {
2054
+ this.pageUrl = window.location.href;
2055
+ }
2056
+ }
2057
+ window.addEventListener("pagehide", this.boundFlushBeacon);
2058
+ if (typeof document !== "undefined") {
2059
+ document.addEventListener("visibilitychange", this.boundVisibilityChange);
2060
+ }
2061
+ bindActivityListeners();
2062
+ if (!this.pageviewEmitted) {
2063
+ this.pageviewEmitted = true;
2064
+ this.enqueue(TraceEventType.PAGEVIEW, "pageview", {});
2065
+ }
2066
+ this.flushTimer = setInterval(() => this.flush(), FLUSH_INTERVAL_MS);
2067
+ this.resendPersistedBatches();
2068
+ }
2069
+ }
2070
+ /**
2071
+ * Binds Prebid event listeners and replays historical pbjs.getEvents().
2072
+ * Idempotent. Returns true if handlers successfully attached.
2073
+ */
2074
+ attachPbjs() {
2075
+ if (!this.isEnabled) return false;
2076
+ if (this.boundPbjsHandlers.length > 0) return true;
2077
+ const win = typeof window !== "undefined" ? window : {};
2078
+ const pbjs = win[this.config.pbjsGlobalName] || {};
2079
+ if (typeof pbjs.onEvent !== "function") {
2080
+ this.log("WARN", "pbjs.onEvent is not defined. Prebid analytics will not function.");
2081
+ return false;
2082
+ }
2083
+ this.log("DEBUG", "Attaching event listeners to pbjs");
2084
+ const handlerMap = {
2085
+ auctionInit: this.handleAuctionInit.bind(this),
2086
+ auctionEnd: this.handleAuctionEnd.bind(this),
2087
+ bidRequested: this.handleBidRequested.bind(this),
2088
+ bidResponse: this.handleBidResponse.bind(this),
2089
+ bidTimeout: this.handleBidTimeout.bind(this),
2090
+ bidWon: this.handleBidWon.bind(this),
2091
+ noBid: this.handleNoBid.bind(this),
2092
+ adRenderFailed: this.handleAdRenderFailed.bind(this),
2093
+ adRenderSucceeded: this.handleAdRenderSucceeded.bind(this)
2094
+ };
2095
+ for (const [name, fn] of Object.entries(handlerMap)) {
2096
+ pbjs.onEvent(name, fn);
2097
+ this.boundPbjsHandlers.push({ event: name, handler: fn });
2098
+ }
2099
+ if (typeof pbjs.getEvents === "function") {
2100
+ try {
2101
+ const pastEvents = pbjs.getEvents();
2102
+ if (Array.isArray(pastEvents)) {
2103
+ const newPastEvents = pastEvents.slice(this.replayedEventCount);
2104
+ this.replayedEventCount = pastEvents.length;
2105
+ if (newPastEvents.length > 0) {
2106
+ this.log(
2107
+ "DEBUG",
2108
+ `Replaying ${newPastEvents.length} historical events from pbjs.getEvents()`
2109
+ );
2110
+ for (const ev of newPastEvents) {
2111
+ if (!ev) continue;
2112
+ const eventType = ev.eventType || ev.event || ev.name;
2113
+ const args = ev.args !== void 0 ? ev.args : ev.data !== void 0 ? ev.data : ev;
2114
+ const handler = handlerMap[eventType];
2115
+ if (handler) {
2116
+ handler(args);
2117
+ }
2118
+ }
2119
+ }
2120
+ }
2121
+ } catch (e) {
2122
+ this.log("WARN", "Failed to replay historical events from pbjs.getEvents()", e);
2123
+ }
2124
+ }
2125
+ return true;
2126
+ }
2127
+ disable() {
2128
+ if (!this.isEnabled) return;
2129
+ this.flushAllSlotsTimeInView();
2130
+ this.isEnabled = false;
2131
+ _BidsparkPrebidAnalytics.activeInstances.delete(this);
2132
+ _BidsparkPrebidAnalytics.allInstances.delete(this);
2133
+ if (this.usageRecorder) {
2134
+ this.usageRecorder.destroy();
2135
+ this.usageRecorder = null;
2136
+ }
2137
+ for (const record of this.slotViewabilityRecords.values()) {
2138
+ if (record.dwellTimer) {
2139
+ clearTimeout(record.dwellTimer);
2140
+ record.dwellTimer = null;
2141
+ record.dwellStartedAt = null;
2142
+ }
2143
+ }
2144
+ if (this.intersectionObserver) {
2145
+ this.intersectionObserver.disconnect();
2146
+ this.intersectionObserver = null;
2147
+ }
2148
+ this.slotViewabilityRecords.clear();
2149
+ this.elementToSlotId.clear();
2150
+ for (const cleanup of this.videoDetachCleanups) {
2151
+ try {
2152
+ cleanup();
2153
+ } catch {
2154
+ }
2155
+ }
2156
+ this.videoDetachCleanups.clear();
2157
+ for (const cleanup of Array.from(this.clickDetachCleanups)) {
2158
+ try {
2159
+ cleanup();
2160
+ } catch {
2161
+ }
2162
+ }
2163
+ this.clickDetachCleanups.clear();
2164
+ this.slotElements.clear();
2165
+ this.cachedWinningBids.clear();
2166
+ this.slotEmittedImpressionKeys.clear();
2167
+ this.slotLastAuctionIds.clear();
2168
+ this.auctionBidderOutcomes.clear();
2169
+ this.floorDecisions.clear();
2170
+ if (this.flushTimer) {
2171
+ clearInterval(this.flushTimer);
2172
+ this.flushTimer = null;
2173
+ }
2174
+ if (this.revenueFlushTimer) {
2175
+ clearTimeout(this.revenueFlushTimer);
2176
+ this.revenueFlushTimer = null;
2177
+ }
2178
+ if (this.persistedCleanupTimer) {
2179
+ clearTimeout(this.persistedCleanupTimer);
2180
+ this.persistedCleanupTimer = null;
2181
+ }
2182
+ if (typeof window !== "undefined") {
2183
+ window.removeEventListener("pagehide", this.boundFlushBeacon);
2184
+ if (typeof document !== "undefined") {
2185
+ document.removeEventListener("visibilitychange", this.boundVisibilityChange);
2186
+ }
2187
+ }
2188
+ if (this.boundPbjsHandlers.length > 0) {
2189
+ const win = typeof window !== "undefined" ? window : {};
2190
+ const pbjs = win[this.config.pbjsGlobalName] || {};
2191
+ if (typeof pbjs.offEvent === "function") {
2192
+ for (const { event, handler } of this.boundPbjsHandlers) {
2193
+ pbjs.offEvent(event, handler);
2194
+ }
2195
+ }
2196
+ this.boundPbjsHandlers = [];
2197
+ }
2198
+ if (this.cmpDetach) {
2199
+ try {
2200
+ this.cmpDetach();
2201
+ } catch {
2202
+ }
2203
+ this.cmpDetach = null;
2204
+ }
2205
+ this.flush();
2206
+ }
2207
+ handleVisibilityChange() {
2208
+ if (typeof document === "undefined") return;
2209
+ if (document.visibilityState === "hidden") {
2210
+ const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
2211
+ for (const record of this.slotViewabilityRecords.values()) {
2212
+ if (record.inView && record.lastEnteredViewAt !== null) {
2213
+ record.accumulatedTimeInViewMs += Math.max(0, now - record.lastEnteredViewAt);
2214
+ record.lastEnteredViewAt = null;
2215
+ }
2216
+ if (record.dwellTimer) {
2217
+ clearTimeout(record.dwellTimer);
2218
+ record.dwellTimer = null;
2219
+ record.dwellStartedAt = null;
2220
+ }
2221
+ const durationMs = Math.round(record.accumulatedTimeInViewMs);
2222
+ if (durationMs > 0) {
2223
+ this.enqueue(TraceEventType.TIME_IN_VIEW, "timeInView", {
2224
+ auctionId: record.auctionId,
2225
+ transactionId: record.transactionId,
2226
+ adUnitCode: record.adUnitCode,
2227
+ viewableDurationMs: durationMs,
2228
+ bid: record.bidPayload,
2229
+ metadata: {
2230
+ ...record.metadata,
2231
+ refresh_index: String(record.refreshIndex)
2232
+ }
2233
+ });
2234
+ }
2235
+ record.accumulatedTimeInViewMs = 0;
2236
+ }
2237
+ this.flushBeacon();
2238
+ } else if (document.visibilityState === "visible") {
2239
+ const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
2240
+ for (const record of this.slotViewabilityRecords.values()) {
2241
+ if (record.inView) {
2242
+ record.lastEnteredViewAt = now;
2243
+ if (!record.viewableFired && record.dwellTimer === null) {
2244
+ const dwellTarget = record.mediaType === "video" ? 2e3 : 1e3;
2245
+ record.dwellStartedAt = now;
2246
+ record.dwellTimer = setTimeout(() => {
2247
+ this.handleDwellComplete(record);
2248
+ }, dwellTarget);
2249
+ }
2250
+ }
2251
+ }
2252
+ }
2253
+ }
2254
+ handleIntersection(entries) {
2255
+ for (const entry of entries) {
2256
+ let slotId = this.elementToSlotId.get(entry.target);
2257
+ if (!slotId) {
2258
+ for (const instance of _BidsparkPrebidAnalytics.activeInstances) {
2259
+ if (instance !== this && instance.elementToSlotId.has(entry.target)) {
2260
+ instance.handleIntersection([entry]);
2261
+ break;
2262
+ }
2263
+ }
2264
+ continue;
2265
+ }
2266
+ const record = this.slotViewabilityRecords.get(slotId);
2267
+ if (!record) continue;
2268
+ const isViewableRatio = entry.isIntersecting && (entry.intersectionRatio === void 0 || entry.intersectionRatio >= 0.5);
2269
+ const isDocVisible = typeof document === "undefined" || document.visibilityState === "visible";
2270
+ const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
2271
+ if (isViewableRatio) {
2272
+ if (!record.inView) {
2273
+ record.inView = true;
2274
+ if (isDocVisible) {
2275
+ record.lastEnteredViewAt = now;
2276
+ if (!record.viewableFired && record.dwellTimer === null) {
2277
+ const dwellTarget = record.mediaType === "video" ? 2e3 : 1e3;
2278
+ record.dwellStartedAt = now;
2279
+ record.dwellTimer = setTimeout(() => {
2280
+ this.handleDwellComplete(record);
2281
+ }, dwellTarget);
2282
+ }
2283
+ }
2284
+ }
2285
+ } else {
2286
+ if (record.inView) {
2287
+ if (record.lastEnteredViewAt !== null) {
2288
+ record.accumulatedTimeInViewMs += Math.max(0, now - record.lastEnteredViewAt);
2289
+ record.lastEnteredViewAt = null;
2290
+ }
2291
+ record.inView = false;
2292
+ }
2293
+ if (record.dwellTimer !== null) {
2294
+ clearTimeout(record.dwellTimer);
2295
+ record.dwellTimer = null;
2296
+ record.dwellStartedAt = null;
2297
+ }
2298
+ }
2299
+ }
2300
+ }
2301
+ handleDwellComplete(record) {
2302
+ record.dwellTimer = null;
2303
+ record.dwellStartedAt = null;
2304
+ if (!record.inView) return;
2305
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;
2306
+ if (!record.viewableFired) {
2307
+ record.viewableFired = true;
2308
+ this.enqueue(TraceEventType.VIEWABLE, "viewable", {
2309
+ auctionId: record.auctionId,
2310
+ transactionId: record.transactionId,
2311
+ adUnitCode: record.adUnitCode,
2312
+ bid: record.bidPayload,
2313
+ metadata: {
2314
+ ...record.metadata,
2315
+ refresh_index: String(record.refreshIndex)
2316
+ }
2317
+ });
2318
+ }
2319
+ this.notifyViewable(record);
2320
+ }
2321
+ notifyViewable(record) {
2322
+ if (!record.viewableFired) return;
2323
+ for (const listener of record.viewableListeners) {
2324
+ if (listener.firedForIndex === record.refreshIndex) continue;
2325
+ listener.firedForIndex = record.refreshIndex;
2326
+ try {
2327
+ listener.callback(record.slotId);
2328
+ } catch (e) {
2329
+ this.log("ERROR", "Error in viewable listener callback", e);
2330
+ }
2331
+ }
2332
+ }
2333
+ /**
2334
+ * Calls back once per render cycle when the slot has met the IAB viewable
2335
+ * standard this adapter measures (immediately if it already has). Works
2336
+ * before the slot is observed: the listener waits for observeSlot. Returns
2337
+ * an unsubscribe function.
2338
+ */
2339
+ /**
2340
+ * Names the element to measure for a slot when the creative renders
2341
+ * somewhere other than the slot element (a sticky bar, an interstitial).
2342
+ * Applies to the current cycle at once and to every later render.
2343
+ */
2344
+ setSlotElement(slotId, element) {
2345
+ this.slotElements.set(slotId, element);
2346
+ const record = this.slotViewabilityRecords.get(slotId);
2347
+ if (record && record.element !== element) {
2348
+ this.observeSlot(element, slotId, {
2349
+ refreshIndex: record.refreshIndex
2350
+ });
2351
+ }
2352
+ }
2353
+ /**
2354
+ * Records a click on the slot's current creative, attributed to the cached
2355
+ * winning bid. Repeats within one second are one click. Returns whether a
2356
+ * CLICK was recorded.
2357
+ */
2358
+ recordClick(slotId, options) {
2359
+ if (!this.isEnabled || !slotId) return false;
2360
+ const now = Date.now();
2361
+ if (now - (this.lastClickAt.get(slotId) || 0) < CLICK_DEDUP_MS) return false;
2362
+ this.lastClickAt.set(slotId, now);
2363
+ const cached = this.getCachedBid(slotId);
2364
+ this.enqueue(TraceEventType.CLICK, "click", {
2365
+ auctionId: cached?.auctionId || "",
2366
+ transactionId: cached?.transactionId || "",
2367
+ adUnitCode: slotId,
2368
+ bid: cached?.bidTrace,
2369
+ metadata: {
2370
+ ...options?.metadata,
2371
+ refresh_index: String(this.getRefreshIndex(slotId))
2372
+ }
2373
+ });
2374
+ return true;
2375
+ }
2376
+ /**
2377
+ * Detects clicks into a cross-origin creative frame: a click inside an
2378
+ * iframe moves focus into it and blurs the window. Returns a detach
2379
+ * function; every tracker is detached on disable().
2380
+ */
2381
+ attachClickTracker(element, slotId) {
2382
+ if (typeof window === "undefined") return () => {
2383
+ };
2384
+ const onBlur = () => {
2385
+ setTimeout(() => {
2386
+ const active = document.activeElement;
2387
+ if (active && (active === element || element.contains(active))) {
2388
+ this.recordClick(slotId, { metadata: { source: "blur" } });
2389
+ window.focus();
2390
+ }
2391
+ }, 0);
2392
+ };
2393
+ window.addEventListener("blur", onBlur);
2394
+ const cleanup = () => {
2395
+ window.removeEventListener("blur", onBlur);
2396
+ this.clickDetachCleanups.delete(cleanup);
2397
+ };
2398
+ this.clickDetachCleanups.add(cleanup);
2399
+ return cleanup;
2400
+ }
2401
+ onViewable(slotId, callback) {
2402
+ const listener = { callback, firedForIndex: -1 };
2403
+ const record = this.slotViewabilityRecords.get(slotId);
2404
+ if (record) {
2405
+ record.viewableListeners.add(listener);
2406
+ this.notifyViewable(record);
2407
+ } else {
2408
+ if (!this.pendingViewableListeners.has(slotId)) {
2409
+ this.pendingViewableListeners.set(slotId, /* @__PURE__ */ new Set());
2410
+ }
2411
+ this.pendingViewableListeners.get(slotId).add(listener);
2412
+ }
2413
+ return () => {
2414
+ this.slotViewabilityRecords.get(slotId)?.viewableListeners.delete(listener);
2415
+ this.pendingViewableListeners.get(slotId)?.delete(listener);
2416
+ };
2417
+ }
2418
+ getCurrentTimeInView(record) {
2419
+ let total = record.accumulatedTimeInViewMs;
2420
+ if (record.inView && record.lastEnteredViewAt !== null) {
2421
+ const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
2422
+ total += Math.max(0, now - record.lastEnteredViewAt);
2423
+ }
2424
+ return total;
2425
+ }
2426
+ flushSlotTimeInView(slotId) {
2427
+ const record = this.slotViewabilityRecords.get(slotId);
2428
+ if (!record) return;
2429
+ if (record.inView && record.lastEnteredViewAt !== null) {
2430
+ const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
2431
+ record.accumulatedTimeInViewMs += Math.max(0, now - record.lastEnteredViewAt);
2432
+ record.lastEnteredViewAt = null;
2433
+ }
2434
+ const durationMs = Math.round(record.accumulatedTimeInViewMs);
2435
+ if (durationMs > 0) {
2436
+ this.enqueue(TraceEventType.TIME_IN_VIEW, "timeInView", {
2437
+ auctionId: record.auctionId,
2438
+ transactionId: record.transactionId,
2439
+ adUnitCode: record.adUnitCode,
2440
+ viewableDurationMs: durationMs,
2441
+ bid: record.bidPayload,
2442
+ metadata: {
2443
+ ...record.metadata,
2444
+ refresh_index: String(record.refreshIndex)
2445
+ }
2446
+ });
2447
+ }
2448
+ record.accumulatedTimeInViewMs = 0;
2449
+ }
2450
+ flushAllSlotsTimeInView() {
2451
+ for (const slotId of Array.from(this.slotViewabilityRecords.keys())) {
2452
+ this.flushSlotTimeInView(slotId);
2453
+ }
2454
+ }
2455
+ observeSlot(element, slotId, options) {
2456
+ if (!this.config.viewabilityEnabled) return;
2457
+ let el = null;
2458
+ if (typeof element === "string") {
2459
+ if (typeof document !== "undefined") {
2460
+ try {
2461
+ el = document.querySelector(element) || document.getElementById(element);
2462
+ } catch {
2463
+ el = document.getElementById(element);
2464
+ }
2465
+ if (!el) {
2466
+ el = document.getElementById(element);
2467
+ }
2468
+ }
2469
+ } else {
2470
+ el = element;
2471
+ }
2472
+ const resolvedSlotId = slotId || options?.adUnitCode || (el ? el.id : "") || generateUUID2();
2473
+ const existing = this.slotViewabilityRecords.get(resolvedSlotId);
2474
+ if (existing) {
2475
+ const isNewRefreshCycle = Boolean(options?.isRefresh) || options?.refreshIndex === void 0 || options.refreshIndex > existing.refreshIndex || Boolean(
2476
+ options?.auctionId && existing.auctionId && options.auctionId !== existing.auctionId
2477
+ );
2478
+ if (isNewRefreshCycle) {
2479
+ this.flushSlotTimeInView(resolvedSlotId);
2480
+ const nextRefreshIndex = options?.refreshIndex !== void 0 ? options.refreshIndex : (this.slotRefreshIndices.get(resolvedSlotId) ?? existing.refreshIndex) + 1;
2481
+ this.slotRefreshIndices.set(resolvedSlotId, nextRefreshIndex);
2482
+ if (existing.dwellTimer) {
2483
+ clearTimeout(existing.dwellTimer);
2484
+ existing.dwellTimer = null;
2485
+ existing.dwellStartedAt = null;
2486
+ }
2487
+ existing.viewableFired = false;
2488
+ existing.accumulatedTimeInViewMs = 0;
2489
+ const now = typeof performance !== "undefined" && performance.now ? performance.now() : Date.now();
2490
+ existing.lastEnteredViewAt = existing.inView ? now : null;
2491
+ existing.refreshIndex = nextRefreshIndex;
2492
+ existing.auctionId = options?.auctionId || existing.auctionId;
2493
+ existing.transactionId = options?.transactionId || existing.transactionId;
2494
+ existing.mediaType = options?.mediaType || existing.mediaType || "banner";
2495
+ existing.bidPayload = options?.bid !== void 0 ? options.bid : existing.bidPayload;
2496
+ existing.metadata = options?.metadata ?? existing.metadata;
2497
+ if (existing.inView && (typeof document === "undefined" || document.visibilityState === "visible")) {
2498
+ const dwellTarget = existing.mediaType === "video" ? 2e3 : 1e3;
2499
+ existing.dwellStartedAt = now;
2500
+ existing.dwellTimer = setTimeout(() => {
2501
+ this.handleDwellComplete(existing);
2502
+ }, dwellTarget);
2503
+ }
2504
+ } else {
2505
+ existing.auctionId = options?.auctionId || existing.auctionId;
2506
+ existing.transactionId = options?.transactionId || existing.transactionId;
2507
+ existing.mediaType = options?.mediaType || existing.mediaType;
2508
+ if (options?.bid !== void 0) existing.bidPayload = options.bid;
2509
+ if (options?.metadata !== void 0) existing.metadata = options.metadata;
2510
+ }
2511
+ if (options?.auctionId) {
2512
+ this.slotLastAuctionIds.set(resolvedSlotId, options.auctionId);
2513
+ }
2514
+ if (el) {
2515
+ if (existing.element && existing.element !== el && this.intersectionObserver) {
2516
+ this.intersectionObserver.unobserve(existing.element);
2517
+ this.elementToSlotId.delete(existing.element);
2518
+ }
2519
+ existing.element = el;
2520
+ this.elementToSlotId.set(el, resolvedSlotId);
2521
+ this.intersectionObserver?.observe(el);
2522
+ }
2523
+ } else {
2524
+ const initialRefreshIndex = options?.refreshIndex ?? this.slotRefreshIndices.get(resolvedSlotId) ?? 0;
2525
+ this.slotRefreshIndices.set(resolvedSlotId, initialRefreshIndex);
2526
+ if (options?.auctionId) {
2527
+ this.slotLastAuctionIds.set(resolvedSlotId, options.auctionId);
2528
+ }
2529
+ const viewableListeners = this.pendingViewableListeners.get(resolvedSlotId) || /* @__PURE__ */ new Set();
2530
+ this.pendingViewableListeners.delete(resolvedSlotId);
2531
+ const record = {
2532
+ slotId: resolvedSlotId,
2533
+ element: el,
2534
+ adUnitCode: options?.adUnitCode || resolvedSlotId,
2535
+ auctionId: options?.auctionId || "",
2536
+ transactionId: options?.transactionId || "",
2537
+ mediaType: options?.mediaType || "banner",
2538
+ bidPayload: options?.bid,
2539
+ metadata: options?.metadata,
2540
+ refreshIndex: initialRefreshIndex,
2541
+ inView: false,
2542
+ lastEnteredViewAt: null,
2543
+ accumulatedTimeInViewMs: 0,
2544
+ viewableFired: false,
2545
+ dwellTimer: null,
2546
+ dwellStartedAt: null,
2547
+ viewableListeners
2548
+ };
2549
+ this.slotViewabilityRecords.set(resolvedSlotId, record);
2550
+ if (el) {
2551
+ this.elementToSlotId.set(el, resolvedSlotId);
2552
+ this.intersectionObserver?.observe(el);
2553
+ }
2554
+ }
2555
+ }
2556
+ unobserveSlot(slotId) {
2557
+ const record = this.slotViewabilityRecords.get(slotId);
2558
+ if (!record) return;
2559
+ this.flushSlotTimeInView(slotId);
2560
+ if (record.dwellTimer) {
2561
+ clearTimeout(record.dwellTimer);
2562
+ record.dwellTimer = null;
2563
+ record.dwellStartedAt = null;
2564
+ }
2565
+ record.viewableListeners = /* @__PURE__ */ new Set();
2566
+ if (record.element && this.intersectionObserver) {
2567
+ this.intersectionObserver.unobserve(record.element);
2568
+ this.elementToSlotId.delete(record.element);
2569
+ record.element = null;
2570
+ }
2571
+ record.inView = false;
2572
+ record.lastEnteredViewAt = null;
2573
+ }
2574
+ /** Names the configured slot an ad unit code belongs to; an empty name forgets it. */
2575
+ registerSlot(elementId, slot) {
2576
+ if (!elementId) return;
2577
+ if (slot) {
2578
+ this.slotNames.set(elementId, slot);
2579
+ } else {
2580
+ this.slotNames.delete(elementId);
2581
+ }
2582
+ }
2583
+ destroySlot(slotId) {
2584
+ this.unobserveSlot(slotId);
2585
+ this.slotNames.delete(slotId);
2586
+ this.slotViewabilityRecords.delete(slotId);
2587
+ this.slotRefreshIndices.delete(slotId);
2588
+ this.slotAdSessionCounters.delete(slotId);
2589
+ this.slotLastAuctionIds.delete(slotId);
2590
+ this.pendingViewableListeners.delete(slotId);
2591
+ const prefix = `${escapeKeyPart(slotId)}:`;
2592
+ for (const key of Array.from(this.slotEmittedImpressionKeys)) {
2593
+ if (key === slotId || key.startsWith(prefix)) {
2594
+ this.slotEmittedImpressionKeys.delete(key);
2595
+ }
2596
+ }
2597
+ const cached = this.cachedWinningBids.get(slotId);
2598
+ if (cached) this.deleteCachedBidEntry(cached);
2599
+ }
2600
+ // --- Bounded caches -------------------------------------------------------
2601
+ /**
2602
+ * Reads a cached winning bid, treating an entry past CACHED_BID_TTL_MS as
2603
+ * absent and dropping it. Every read goes through here so a stale bid can
2604
+ * never be married to a much later render.
2605
+ */
2606
+ getCachedBid(key) {
2607
+ const entry = this.cachedWinningBids.get(key);
2608
+ if (!entry) return void 0;
2609
+ if (Date.now() - entry.timestamp > CACHED_BID_TTL_MS) {
2610
+ this.deleteCachedBidEntry(entry);
2611
+ return void 0;
2612
+ }
2613
+ return entry;
2614
+ }
2615
+ /** Removes every alias pointing at one entry. Aliases are stored by identity. */
2616
+ deleteCachedBidEntry(entry) {
2617
+ for (const [key, value] of Array.from(this.cachedWinningBids)) {
2618
+ if (value === entry) this.cachedWinningBids.delete(key);
2619
+ }
2620
+ }
2621
+ /**
2622
+ * Drops expired entries, then evicts oldest-first until the key cap holds.
2623
+ * Map iterates in insertion order and one win's aliases are written
2624
+ * consecutively, so eviction takes a whole bid's aliases together.
2625
+ */
2626
+ pruneCachedWinningBids() {
2627
+ const now = Date.now();
2628
+ for (const [key, entry] of Array.from(this.cachedWinningBids)) {
2629
+ if (now - entry.timestamp > CACHED_BID_TTL_MS) this.cachedWinningBids.delete(key);
2630
+ }
2631
+ while (this.cachedWinningBids.size > MAX_CACHED_BID_KEYS) {
2632
+ const oldest = this.cachedWinningBids.keys().next();
2633
+ if (oldest.done) break;
2634
+ this.cachedWinningBids.delete(oldest.value);
2635
+ }
2636
+ }
2637
+ /** Records a dedup key, evicting oldest-first at the cap. */
2638
+ addImpressionKey(key) {
2639
+ if (this.slotEmittedImpressionKeys.has(key)) return;
2640
+ while (this.slotEmittedImpressionKeys.size >= MAX_IMPRESSION_KEYS) {
2641
+ const oldest = this.slotEmittedImpressionKeys.values().next();
2642
+ if (oldest.done) break;
2643
+ this.slotEmittedImpressionKeys.delete(oldest.value);
2644
+ }
2645
+ this.slotEmittedImpressionKeys.add(key);
2646
+ }
2647
+ /**
2648
+ * The bidder-outcome map for an auction, creating it if absent. Evicts the
2649
+ * oldest auction at the cap: without this, any auction whose auctionEnd never
2650
+ * fires (abandoned, navigated away from mid-flight) leaks its map forever.
2651
+ */
2652
+ getOrCreateAuctionOutcomes(auctionId) {
2653
+ let auctionMap = this.auctionBidderOutcomes.get(auctionId);
2654
+ if (!auctionMap) {
2655
+ auctionMap = /* @__PURE__ */ new Map();
2656
+ this.auctionBidderOutcomes.set(auctionId, auctionMap);
2657
+ }
2658
+ while (this.auctionBidderOutcomes.size > MAX_TRACKED_AUCTIONS) {
2659
+ const oldest = this.auctionBidderOutcomes.keys().next();
2660
+ if (oldest.done || oldest.value === auctionId) break;
2661
+ this.auctionBidderOutcomes.delete(oldest.value);
2662
+ }
2663
+ return auctionMap;
2664
+ }
2665
+ nextSlotAdSession(slotId) {
2666
+ const next = (this.slotAdSessionCounters.get(slotId) ?? 0) + 1;
2667
+ this.slotAdSessionCounters.set(slotId, next);
2668
+ return `ad-session-${next}`;
2669
+ }
2670
+ hasImpressionEmitted(slotId, refreshIndex, auctionId, creativeId, adId) {
2671
+ const rIndex = refreshIndex ?? this.slotRefreshIndices.get(slotId) ?? 0;
2672
+ const baseSlotKey = `${escapeKeyPart(slotId)}:${rIndex}`;
2673
+ if (adId) {
2674
+ if (auctionId) {
2675
+ if (this.slotEmittedImpressionKeys.has(
2676
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad:${escapeKeyPart(adId)}`
2677
+ ) || this.slotEmittedImpressionKeys.has(`${baseSlotKey}:ad:${escapeKeyPart(adId)}`)) {
2678
+ return true;
2679
+ }
2680
+ } else if (this.slotEmittedImpressionKeys.has(`${baseSlotKey}:ad:${escapeKeyPart(adId)}`)) {
2681
+ return true;
2682
+ }
2683
+ if (creativeId && creativeId !== adId) {
2684
+ if (auctionId) {
2685
+ if (this.slotEmittedImpressionKeys.has(
2686
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:${escapeKeyPart(creativeId)}`
2687
+ ) || this.slotEmittedImpressionKeys.has(`${baseSlotKey}:${escapeKeyPart(creativeId)}`)) {
2688
+ return true;
2689
+ }
2690
+ } else if (this.slotEmittedImpressionKeys.has(`${baseSlotKey}:${escapeKeyPart(creativeId)}`)) {
2691
+ return true;
2692
+ }
2693
+ }
2694
+ return false;
2695
+ }
2696
+ if (creativeId) {
2697
+ if (auctionId) {
2698
+ return this.slotEmittedImpressionKeys.has(
2699
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:${escapeKeyPart(creativeId)}`
2700
+ ) || this.slotEmittedImpressionKeys.has(`${baseSlotKey}:${escapeKeyPart(creativeId)}`);
2701
+ }
2702
+ return this.slotEmittedImpressionKeys.has(`${baseSlotKey}:${escapeKeyPart(creativeId)}`);
2703
+ }
2704
+ if (auctionId) {
2705
+ return this.slotEmittedImpressionKeys.has(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2706
+ }
2707
+ return this.slotEmittedImpressionKeys.has(baseSlotKey);
2708
+ }
2709
+ markImpressionEmitted(slotId, refreshIndex, auctionId, creativeId, adId) {
2710
+ const baseSlotKey = `${escapeKeyPart(slotId)}:${refreshIndex}`;
2711
+ const hasIdentity = Boolean(adId || creativeId);
2712
+ if (hasIdentity) {
2713
+ if (adId) {
2714
+ this.addImpressionKey(`${baseSlotKey}:ad:${escapeKeyPart(adId)}`);
2715
+ if (auctionId) {
2716
+ this.addImpressionKey(
2717
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:ad:${escapeKeyPart(adId)}`
2718
+ );
2719
+ }
2720
+ }
2721
+ if (creativeId && creativeId !== adId) {
2722
+ this.addImpressionKey(`${baseSlotKey}:${escapeKeyPart(creativeId)}`);
2723
+ if (auctionId) {
2724
+ this.addImpressionKey(
2725
+ `${baseSlotKey}:auc:${escapeKeyPart(auctionId)}:${escapeKeyPart(creativeId)}`
2726
+ );
2727
+ }
2728
+ }
2729
+ if (auctionId) {
2730
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2731
+ }
2732
+ } else {
2733
+ this.addImpressionKey(baseSlotKey);
2734
+ if (auctionId) {
2735
+ this.addImpressionKey(`${baseSlotKey}:auc:${escapeKeyPart(auctionId)}`);
2736
+ }
2737
+ }
2738
+ }
2739
+ recordImpression(slotId, options) {
2740
+ if (!this.isEnabled) return false;
2741
+ const resolvedSlotId = slotId || options?.adUnitCode || "";
2742
+ const adUnitCode = options?.adUnitCode || resolvedSlotId;
2743
+ const cached = (options?.auctionId && resolvedSlotId ? this.getCachedBid(`${options.auctionId}:${resolvedSlotId}`) : void 0) || (options?.auctionId && adUnitCode ? this.getCachedBid(`${options.auctionId}:${adUnitCode}`) : void 0) || (resolvedSlotId ? this.getCachedBid(resolvedSlotId) : void 0) || (adUnitCode ? this.getCachedBid(adUnitCode) : void 0);
2744
+ const rawBid = options?.bid || cached?.rawBid || {};
2745
+ const auctionId = options?.auctionId || rawBid.auctionId || cached?.auctionId || "";
2746
+ const transactionId = options?.transactionId || rawBid.transactionId || cached?.transactionId || "";
2747
+ const creativeId = rawBid.creativeId || cached?.bidTrace?.creativeId || options?.bid?.creativeId || "";
2748
+ const adId = options?.adId || rawBid.adId || options?.bid?.adId || "";
2749
+ const mediaType = options?.mediaType || rawBid.mediaType || cached?.bidTrace?.mediaType || "banner";
2750
+ const targetSlot = resolvedSlotId || adUnitCode;
2751
+ const rec = (resolvedSlotId ? this.slotViewabilityRecords.get(resolvedSlotId) : void 0) || (adUnitCode ? this.slotViewabilityRecords.get(adUnitCode) : void 0);
2752
+ const lastAuctionId = targetSlot ? this.slotLastAuctionIds.get(targetSlot) || (rec ? rec.auctionId : void 0) : void 0;
2753
+ const isDifferentAuction = Boolean(
2754
+ targetSlot && auctionId && lastAuctionId && lastAuctionId !== auctionId && options?.refreshIndex === void 0
2755
+ );
2756
+ const bidTrace = {
2757
+ bidder: rawBid.bidderCode || rawBid.bidder || cached?.bidTrace?.bidder || "",
2758
+ ...resolveBidPricing(rawBid, cached?.bidTrace),
2759
+ ...parseBidDimensions(rawBid).width ? parseBidDimensions(rawBid) : cached?.bidTrace ? { width: cached.bidTrace.width, height: cached.bidTrace.height } : parseBidDimensions(rawBid),
2760
+ dealId: rawBid.dealId || cached?.bidTrace?.dealId || "",
2761
+ mediaType,
2762
+ latencyMs: Number.isFinite(rawBid.timeToRespond) ? rawBid.timeToRespond : cached?.bidTrace?.latencyMs ?? 0,
2763
+ advertiserDomain: rawBid.meta?.advertiserDomains?.[0] || cached?.bidTrace?.advertiserDomain || "",
2764
+ creativeId: rawBid.creativeId || cached?.bidTrace?.creativeId || ""
2765
+ };
2766
+ if (isDifferentAuction && targetSlot) {
2767
+ this.flushSlotTimeInView(targetSlot);
2768
+ const nextRefreshIndex = (this.slotRefreshIndices.get(targetSlot) ?? (rec ? rec.refreshIndex : 0)) + 1;
2769
+ this.slotRefreshIndices.set(targetSlot, nextRefreshIndex);
2770
+ this.slotLastAuctionIds.set(targetSlot, auctionId);
2771
+ if (rec) {
2772
+ rec.refreshIndex = nextRefreshIndex;
2773
+ rec.auctionId = auctionId;
2774
+ rec.transactionId = transactionId;
2775
+ rec.bidPayload = bidTrace;
2776
+ rec.viewableFired = false;
2777
+ rec.accumulatedTimeInViewMs = 0;
2778
+ }
2779
+ } else if (targetSlot) {
2780
+ if (auctionId) {
2781
+ this.slotLastAuctionIds.set(targetSlot, auctionId);
2782
+ }
2783
+ if (!this.slotRefreshIndices.has(targetSlot)) {
2784
+ this.slotRefreshIndices.set(targetSlot, 0);
2785
+ }
2786
+ }
2787
+ const currentRefreshIndex = options?.refreshIndex ?? (resolvedSlotId ? this.slotRefreshIndices.get(resolvedSlotId) ?? (adUnitCode ? this.slotRefreshIndices.get(adUnitCode) : void 0) ?? (rec ? rec.refreshIndex : 0) : 0);
2788
+ const alreadyEmitted = resolvedSlotId && this.hasImpressionEmitted(
2789
+ resolvedSlotId,
2790
+ currentRefreshIndex,
2791
+ auctionId,
2792
+ creativeId,
2793
+ adId
2794
+ ) || adUnitCode && adUnitCode !== resolvedSlotId && this.hasImpressionEmitted(adUnitCode, currentRefreshIndex, auctionId, creativeId, adId);
2795
+ if (alreadyEmitted) {
2796
+ this.log(
2797
+ "DEBUG",
2798
+ `Impression already emitted for slot ${resolvedSlotId || adUnitCode} in cycle ${currentRefreshIndex}`
2799
+ );
2800
+ return false;
2801
+ }
2802
+ if (resolvedSlotId)
2803
+ this.markImpressionEmitted(resolvedSlotId, currentRefreshIndex, auctionId, creativeId, adId);
2804
+ if (adUnitCode && adUnitCode !== resolvedSlotId)
2805
+ this.markImpressionEmitted(adUnitCode, currentRefreshIndex, auctionId, creativeId, adId);
2806
+ this.enqueue(TraceEventType.IMPRESSION, "impression", {
2807
+ auctionId,
2808
+ transactionId,
2809
+ adUnitCode,
2810
+ bid: bidTrace,
2811
+ metadata: {
2812
+ ...options?.metadata,
2813
+ refresh_index: String(currentRefreshIndex)
2814
+ }
2815
+ });
2816
+ if (rec) {
2817
+ if (!rec.bidPayload && bidTrace) rec.bidPayload = bidTrace;
2818
+ if (!rec.auctionId && auctionId) rec.auctionId = auctionId;
2819
+ if (!rec.transactionId && transactionId) rec.transactionId = transactionId;
2820
+ }
2821
+ return true;
2822
+ }
2823
+ getViewabilityState(slotId) {
2824
+ const record = this.slotViewabilityRecords.get(slotId);
2825
+ if (!record) return void 0;
2826
+ const timeInViewMs = Math.round(this.getCurrentTimeInView(record));
2827
+ return {
2828
+ inView: record.inView,
2829
+ viewable: record.viewableFired,
2830
+ timeInViewMs,
2831
+ refreshIndex: record.refreshIndex
2832
+ };
2833
+ }
2834
+ /** The validated ingest endpoint in use, or "" when none passed validation. */
2835
+ getEndpoint() {
2836
+ return this.config.endpoint;
2837
+ }
2838
+ getRefreshIndex(slotId) {
2839
+ return this.slotRefreshIndices.get(slotId) ?? 0;
2840
+ }
2841
+ triggerSlotRefresh(slotId, options) {
2842
+ const record = this.slotViewabilityRecords.get(slotId);
2843
+ if (record && record.element) {
2844
+ this.observeSlot(record.element, slotId, options);
2845
+ }
2846
+ }
2847
+ trackRawEvent(level, eventName, data) {
2848
+ const eventType = LEVEL_TO_TYPE[level] ?? EVENT_NAME_TO_TYPE[eventName];
2849
+ if (eventType === void 0) return;
2850
+ this.enqueue(eventType, eventName, data);
2851
+ }
2852
+ /**
2853
+ * Record the wrapper's Live Floors decision for an auction and ad unit,
2854
+ * before the auction runs. The decision is stamped on the auction's
2855
+ * outcome entries for the ad unit at auction end and on the win and
2856
+ * impression rows that follow, so every outcome can be split by floor,
2857
+ * source and treatment without a join. Integrations without the module
2858
+ * never call this and their rows carry no floor fields.
2859
+ */
2860
+ recordFloorDecision(auctionId, adUnitCode, decision) {
2861
+ if (!auctionId || !adUnitCode) return;
2862
+ const key = `${auctionId}:${adUnitCode}`;
2863
+ this.floorDecisions.delete(key);
2864
+ this.floorDecisions.set(key, {
2865
+ floorCents: decision.floorCents !== void 0 && Number.isFinite(decision.floorCents) ? Math.round(decision.floorCents) : void 0,
2866
+ source: decision.source,
2867
+ treatment: Number.isFinite(decision.treatment) ? decision.treatment : 1
2868
+ });
2869
+ while (this.floorDecisions.size > MAX_FLOOR_DECISIONS) {
2870
+ const oldest = this.floorDecisions.keys().next();
2871
+ if (oldest.done) break;
2872
+ this.floorDecisions.delete(oldest.value);
2873
+ }
2874
+ }
2875
+ floorDecisionFor(auctionId, adUnitCode) {
2876
+ return auctionId && adUnitCode ? this.floorDecisions.get(`${auctionId}:${adUnitCode}`) : void 0;
2877
+ }
2878
+ /**
2879
+ * Enqueues one CONSENT event with the record flattened into metadata under snake_case keys.
2880
+ * Deduped on regime|action|tcString|gppString|uspString per pageview.
2881
+ */
2882
+ recordConsent(record) {
2883
+ if (!this.isEnabled || !record) return false;
2884
+ const dedupeKey = `${record.regime}|${record.action}|${record.tcString ?? ""}|${record.gppString ?? ""}|${record.uspString ?? ""}`;
2885
+ if (this.recordedConsentKeys.has(dedupeKey)) {
2886
+ return false;
2887
+ }
2888
+ this.recordedConsentKeys.add(dedupeKey);
2889
+ const metadata = {};
2890
+ const put = (key, value) => {
2891
+ if (value === void 0 || value === null || value === "") return;
2892
+ if (typeof value === "number") {
2893
+ if (!Number.isFinite(value)) return;
2894
+ metadata[key] = String(value);
2895
+ } else if (typeof value === "boolean") {
2896
+ metadata[key] = value ? "true" : "false";
2897
+ } else if (Array.isArray(value)) {
2898
+ if (value.length === 0) return;
2899
+ metadata[key] = [...value].sort((a, b) => a - b).join(",");
2900
+ } else if (typeof value === "string") {
2901
+ metadata[key] = value;
2902
+ }
2903
+ };
2904
+ put("regime", record.regime);
2905
+ put("action", record.action);
2906
+ put("cmp_id", record.cmpId);
2907
+ put("cmp_version", record.cmpVersion);
2908
+ put("gvl_version", record.gvlVersion);
2909
+ put("tc_string", record.tcString);
2910
+ put("ac_string", record.acString);
2911
+ put("gpp_string", record.gppString);
2912
+ put("usp_string", record.uspString);
2913
+ put("purposes_consented", record.purposesConsented);
2914
+ put("vendors_consented", record.vendorsConsented);
2915
+ put("vendors_total", record.vendorsTotal);
2916
+ put("language", record.language);
2917
+ put("opt_out", record.optOut);
2918
+ put("gpc", record.gpc);
2919
+ this.enqueue(TraceEventType.CONSENT, "consent", { metadata });
2920
+ return true;
2921
+ }
2922
+ /**
2923
+ * Subscribes to ads:consent on document, and replays the current CMP record if one
2924
+ * is available from the configured alias. Returns a detach function.
2925
+ */
2926
+ attachCmp() {
2927
+ if (typeof document === "undefined") {
2928
+ return () => {
2929
+ };
2930
+ }
2931
+ const handler = (evt) => {
2932
+ const detail = evt.detail;
2933
+ if (detail) {
2934
+ this.recordConsent(detail);
2935
+ this.followConsent(detail);
2936
+ }
2937
+ };
2938
+ document.addEventListener("ads:consent", handler);
2939
+ const win = typeof window !== "undefined" ? window : {};
2940
+ const existingRecord = win[this.config.alias]?.consent?.getRecord?.() || null;
2941
+ if (existingRecord) {
2942
+ this.recordConsent(existingRecord);
2943
+ this.followConsent(existingRecord);
2944
+ }
2945
+ let detached = false;
2946
+ return () => {
2947
+ if (detached) return;
2948
+ detached = true;
2949
+ document.removeEventListener("ads:consent", handler);
2950
+ };
2951
+ }
2952
+ /** Device storage follows the decision; a refusal also drops the stored session. */
2953
+ followConsent(record) {
2954
+ const allowed = storageAllowedBy(record);
2955
+ if (!allowed) clearStoredSession();
2956
+ _BidsparkPrebidAnalytics.setStorageAllowed(allowed);
2957
+ }
2958
+ setUserId(userId) {
2959
+ this.config.userId = userId;
2960
+ if (userId) this.config.visitorId = userId;
2961
+ if (this.config.storageAllowed && typeof localStorage !== "undefined") {
2962
+ try {
2963
+ if (userId) {
2964
+ localStorage.setItem(USER_ID_KEY, userId);
2965
+ } else {
2966
+ localStorage.removeItem(USER_ID_KEY);
2967
+ }
2968
+ } catch {
2969
+ }
2970
+ }
2971
+ }
2972
+ setVisitorId(visitorId) {
2973
+ this.config.visitorId = visitorId;
2974
+ }
2975
+ setSampleRate(sampleRate) {
2976
+ this.config.sampleRate = normalizeSampleRate(sampleRate);
2977
+ }
2978
+ setSessionId(sessionId) {
2979
+ this.config.sessionId = sessionId;
2980
+ this.managesSessionId = !sessionId;
2981
+ if (this.managesSessionId) this.config.sessionId = getOrCreateSessionId();
2982
+ }
2983
+ navigate(pageviewId, pageUrl) {
2984
+ this.disable();
2985
+ this.slotRefreshIndices.clear();
2986
+ this.slotNames.clear();
2987
+ this.slotAdSessionCounters.clear();
2988
+ this.floorDecisions.clear();
2989
+ this.recordedConsentKeys.clear();
2990
+ this.consentCount = 0;
2991
+ this.pageviewEmitted = false;
2992
+ this.config.pageviewId = pageviewId || generateUUID2();
2993
+ this.config.visitorId = this.config.userId || this.config.pageviewId;
2994
+ if (pageUrl) {
2995
+ try {
2996
+ const u = new URL(pageUrl);
2997
+ this.pageUrl = u.origin + u.pathname;
2998
+ } catch {
2999
+ this.pageUrl = pageUrl;
3000
+ }
3001
+ } else {
3002
+ this.pageUrl = "";
3003
+ }
3004
+ this.logger.resetTiming();
3005
+ recordActivity();
3006
+ this.enable();
3007
+ }
3008
+ recordAuctionStart(auctionId, adUnitCode = "", bidderCount) {
3009
+ if (!this.isEnabled || !this.config.auctionEnabled) return;
3010
+ this.enqueue(TraceEventType.AUCTION_START, "auctionStart", {
3011
+ auctionId,
3012
+ adUnitCode,
3013
+ ...typeof bidderCount === "number" ? { metadata: { bidderCount: String(bidderCount) } } : {}
3014
+ });
3015
+ }
3016
+ handleAuctionInit(data) {
3017
+ if (this.isDuplicate("auctionInit", data)) return;
3018
+ this.log("DEBUG", "auctionInit", data);
3019
+ const auctionId = data.auctionId || "";
3020
+ if (auctionId) {
3021
+ this.auctionBidderOutcomes.delete(auctionId);
3022
+ this.getOrCreateAuctionOutcomes(auctionId);
3023
+ }
3024
+ const slotCount = Array.isArray(data.adUnitCodes) ? data.adUnitCodes.length : Array.isArray(data.adUnits) ? data.adUnits.length : 1;
3025
+ if (this.config.attachPbjsListeners && this.usageRecorder) {
3026
+ this.usageRecorder.record(auctionId, slotCount);
3027
+ }
3028
+ this.enqueue(TraceEventType.AUCTION_START, "auctionStart", {
3029
+ auctionId,
3030
+ transactionId: data.transactionId || ""
3031
+ });
3032
+ }
3033
+ handleAuctionEnd(data) {
3034
+ if (this.isDuplicate("auctionEnd", data)) return;
3035
+ this.log("DEBUG", "auctionEnd", data);
3036
+ const auctionId = data.auctionId || "";
3037
+ const outcomesMap = auctionId ? this.auctionBidderOutcomes.get(auctionId) : void 0;
3038
+ const bidderOutcomes = outcomesMap ? Array.from(outcomesMap.values()) : [];
3039
+ if (auctionId) {
3040
+ this.auctionBidderOutcomes.delete(auctionId);
3041
+ }
3042
+ this.enqueue(TraceEventType.AUCTION_END, "auctionEnd", {
3043
+ auctionId,
3044
+ transactionId: data.transactionId || "",
3045
+ bidderOutcomes
3046
+ });
3047
+ }
3048
+ /**
3049
+ * The render cycle an auction ending now would fill for an ad unit: 0 for
3050
+ * a slot that has never rendered on this pageview, otherwise one past the
3051
+ * cycle it last rendered. The index only advances when a creative renders,
3052
+ * so two unfilled refresh auctions in a row report the same cycle; both
3053
+ * count as refreshes, which is the point. Stamped on AUCTION_END bidder
3054
+ * outcomes in enqueue; there is no per-refresh event.
3055
+ */
3056
+ auctionCycleIndex(adUnitCode) {
3057
+ if (!adUnitCode) return 0;
3058
+ const last = this.slotRefreshIndices.get(adUnitCode) ?? this.slotViewabilityRecords.get(adUnitCode)?.refreshIndex;
3059
+ return last === void 0 ? 0 : last + 1;
3060
+ }
3061
+ handleBidRequested(data) {
3062
+ if (this.isDuplicate("bidRequested", data)) return;
3063
+ this.log("DEBUG", "bidRequested", data);
3064
+ const auctionId = data.auctionId || "";
3065
+ const bidder = data.bidderCode || data.bidder || "";
3066
+ if (!auctionId || !bidder) return;
3067
+ const auctionMap = this.getOrCreateAuctionOutcomes(auctionId);
3068
+ if (Array.isArray(data.bids)) {
3069
+ data.bids.forEach((bid) => {
3070
+ const adUnitCode = bid.adUnitCode || "";
3071
+ const mediaTypes = Object.keys(bid.mediaTypes || {});
3072
+ const mediaType = mediaTypes.length > 0 ? mediaTypes[0] : bid.mediaType || "banner";
3073
+ const key = `${bidder}:${adUnitCode}`;
3074
+ if (!auctionMap.has(key)) {
3075
+ auctionMap.set(key, {
3076
+ adUnitCode,
3077
+ outcome: BidderOutcome.BIDDER_OUTCOME_NO_RESPONSE,
3078
+ bid: { bidder, mediaType, latencyMs: 0 }
3079
+ });
3080
+ }
3081
+ });
3082
+ }
3083
+ }
3084
+ handleBidResponse(data) {
3085
+ if (this.isDuplicate("bidResponse", data)) return;
3086
+ this.log("DEBUG", "bidResponse", data);
3087
+ const auctionId = data.auctionId || "";
3088
+ const bidder = data.bidderCode || data.bidder || "";
3089
+ const adUnitCode = data.adUnitCode || "";
3090
+ const pricing = resolveBidPricing(data);
3091
+ const cpm = pricing.cpm;
3092
+ const latencyMs = Number.isFinite(data.timeToRespond) ? data.timeToRespond : 0;
3093
+ const resMediaTypes = Object.keys(data.mediaTypes || {});
3094
+ const mediaType = data.mediaType || (data.mediaTypes?.video ? "video" : resMediaTypes.length > 0 ? resMediaTypes[0] : "banner");
3095
+ if (!auctionId || !bidder) return;
3096
+ const bid = cpm > 0 ? {
3097
+ bidder,
3098
+ ...pricing,
3099
+ ...parseBidDimensions(data),
3100
+ dealId: data.dealId || "",
3101
+ mediaType,
3102
+ latencyMs,
3103
+ advertiserDomain: data.meta?.advertiserDomains?.[0] || "",
3104
+ creativeId: data.creativeId || ""
3105
+ } : { bidder, mediaType, latencyMs };
3106
+ this.getOrCreateAuctionOutcomes(auctionId).set(`${bidder}:${adUnitCode}`, {
3107
+ adUnitCode,
3108
+ outcome: cpm > 0 ? BidderOutcome.BIDDER_OUTCOME_BID : BidderOutcome.BIDDER_OUTCOME_NO_BID,
3109
+ bid
3110
+ });
3111
+ }
3112
+ handleBidTimeout(data) {
3113
+ if (this.isDuplicate("bidTimeout", data)) return;
3114
+ this.log("DEBUG", "bidTimeout", data);
3115
+ const items = Array.isArray(data) ? data : data ? [data] : [];
3116
+ for (const t of items) {
3117
+ const auctionId = t.auctionId || "";
3118
+ const bidder = t.bidderCode || t.bidder || "";
3119
+ const adUnitCode = t.adUnitCode || "";
3120
+ const latencyMs = Number.isFinite(t.timeout) ? t.timeout : 0;
3121
+ if (auctionId && bidder) {
3122
+ const auctionMap = this.getOrCreateAuctionOutcomes(auctionId);
3123
+ const key = `${bidder}:${adUnitCode}`;
3124
+ const entry = auctionMap.get(key);
3125
+ if (entry) {
3126
+ entry.outcome = BidderOutcome.BIDDER_OUTCOME_TIMEOUT;
3127
+ if (latencyMs > 0 && entry.bid) entry.bid.latencyMs = latencyMs;
3128
+ } else {
3129
+ auctionMap.set(key, {
3130
+ adUnitCode,
3131
+ outcome: BidderOutcome.BIDDER_OUTCOME_TIMEOUT,
3132
+ bid: { bidder, mediaType: "banner", latencyMs }
3133
+ });
3134
+ }
3135
+ }
3136
+ }
3137
+ }
3138
+ handleBidWon(data) {
3139
+ if (this.isDuplicate("bidWon", data)) return;
3140
+ this.log("DEBUG", "bidWon", data);
3141
+ const auctionId = data.auctionId || "";
3142
+ const transactionId = data.transactionId || "";
3143
+ const adUnitCode = data.adUnitCode || data.adId || "";
3144
+ const wonMediaTypes = Object.keys(data.mediaTypes || {});
3145
+ const resolvedMediaType = data.mediaType || (data.mediaTypes?.video ? "video" : wonMediaTypes.length > 0 ? wonMediaTypes[0] : "banner");
3146
+ const bidTrace = {
3147
+ bidder: data.bidderCode || data.bidder || "",
3148
+ ...resolveBidPricing(data),
3149
+ ...parseBidDimensions(data),
3150
+ dealId: data.dealId || "",
3151
+ mediaType: resolvedMediaType,
3152
+ latencyMs: Number.isFinite(data.timeToRespond) ? data.timeToRespond : 0,
3153
+ advertiserDomain: data.meta?.advertiserDomains?.[0] || "",
3154
+ creativeId: data.creativeId || ""
3155
+ };
3156
+ if (adUnitCode) {
3157
+ const cachedEntry = {
3158
+ bidTrace,
3159
+ auctionId,
3160
+ transactionId,
3161
+ adUnitCode,
3162
+ rawBid: data,
3163
+ timestamp: Date.now()
3164
+ };
3165
+ this.cachedWinningBids.set(adUnitCode, cachedEntry);
3166
+ if (data.adId && data.adId !== adUnitCode) {
3167
+ this.cachedWinningBids.set(data.adId, cachedEntry);
3168
+ }
3169
+ if (auctionId) {
3170
+ this.cachedWinningBids.set(`${auctionId}:${adUnitCode}`, cachedEntry);
3171
+ if (data.adId && data.adId !== adUnitCode) {
3172
+ this.cachedWinningBids.set(`${auctionId}:${data.adId}`, cachedEntry);
3173
+ }
3174
+ }
3175
+ this.pruneCachedWinningBids();
3176
+ }
3177
+ this.enqueue(TraceEventType.BID_WIN, "bidWon", {
3178
+ auctionId,
3179
+ transactionId,
3180
+ adUnitCode,
3181
+ bid: bidTrace
3182
+ });
3183
+ }
3184
+ handleNoBid(data) {
3185
+ if (this.isDuplicate("noBid", data)) return;
3186
+ this.log("DEBUG", "noBid", data);
3187
+ const auctionId = data.auctionId || "";
3188
+ const bidder = data.bidderCode || data.bidder || "";
3189
+ const adUnitCode = data.adUnitCode || "";
3190
+ if (auctionId && bidder) {
3191
+ const auctionMap = this.getOrCreateAuctionOutcomes(auctionId);
3192
+ const key = `${bidder}:${adUnitCode}`;
3193
+ const entry = auctionMap.get(key);
3194
+ if (entry) {
3195
+ if (entry.outcome === BidderOutcome.BIDDER_OUTCOME_NO_RESPONSE) {
3196
+ entry.outcome = BidderOutcome.BIDDER_OUTCOME_NO_BID;
3197
+ }
3198
+ } else {
3199
+ auctionMap.set(key, {
3200
+ adUnitCode,
3201
+ outcome: BidderOutcome.BIDDER_OUTCOME_NO_BID,
3202
+ bid: { bidder, mediaType: "banner", latencyMs: 0 }
3203
+ });
3204
+ }
3205
+ }
3206
+ }
3207
+ handleAdRenderFailed(data) {
3208
+ if (this.isDuplicate("adRenderFailed", data)) return;
3209
+ this.log("DEBUG", "adRenderFailed", data);
3210
+ const bid = data.bid || {};
3211
+ this.enqueue(TraceEventType.AD_RENDER_FAILED, "adRenderFailed", {
3212
+ auctionId: bid.auctionId || data.auctionId || "",
3213
+ transactionId: bid.transactionId || data.transactionId || "",
3214
+ adUnitCode: bid.adUnitCode || data.adUnitCode || "",
3215
+ bid: {
3216
+ bidder: bid.bidderCode || bid.bidder || data.bidderCode || data.bidder || ""
3217
+ },
3218
+ metadata: {
3219
+ reason: String(data.reason || ""),
3220
+ message: String(data.message || data.error?.message || "")
3221
+ },
3222
+ error: data.error || (data.message ? new Error(String(data.message)) : void 0)
3223
+ });
3224
+ }
3225
+ // Prebid's adRenderSucceeded payload is { doc, bid, adId }: the winning bid
3226
+ // lives under data.bid, unlike the flat bidWon payload.
3227
+ handleAdRenderSucceeded(data) {
3228
+ if (this.isDuplicate("adRenderSucceeded", data)) return;
3229
+ this.log("DEBUG", "adRenderSucceeded", data);
3230
+ const bid = data.bid || data || {};
3231
+ const adUnitCode = data.adUnitCode || bid.adUnitCode || data.adId || bid.adId || "";
3232
+ const auctionId = bid.auctionId || data.auctionId || "";
3233
+ const transactionId = bid.transactionId || data.transactionId || "";
3234
+ const mediaType = bid.mediaType || "banner";
3235
+ const slotKey = data.adUnitCode || bid.adUnitCode || "";
3236
+ const altKey = data.adId || bid.adId || "";
3237
+ 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);
3238
+ 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";
3239
+ const resolvedMediaType = isVideo ? "video" : mediaType || cached?.bidTrace?.mediaType || "banner";
3240
+ const bidTrace = {
3241
+ bidder: bid.bidderCode || bid.bidder || cached?.bidTrace?.bidder || "",
3242
+ ...resolveBidPricing(bid, cached?.bidTrace),
3243
+ ...parseBidDimensions(bid).width ? parseBidDimensions(bid) : cached?.bidTrace ? { width: cached.bidTrace.width, height: cached.bidTrace.height } : parseBidDimensions(bid),
3244
+ dealId: bid.dealId || cached?.bidTrace?.dealId || "",
3245
+ mediaType: resolvedMediaType,
3246
+ latencyMs: Number.isFinite(bid.timeToRespond) ? bid.timeToRespond : cached?.bidTrace?.latencyMs ?? 0,
3247
+ advertiserDomain: bid.meta?.advertiserDomains?.[0] || cached?.bidTrace?.advertiserDomain || "",
3248
+ creativeId: bid.creativeId || cached?.bidTrace?.creativeId || ""
3249
+ };
3250
+ const resolvedAuctionId = auctionId || cached?.auctionId || "";
3251
+ const resolvedTransactionId = transactionId || cached?.transactionId || "";
3252
+ const record = adUnitCode ? this.slotViewabilityRecords.get(adUnitCode) : void 0;
3253
+ const isDifferentAuction = record && resolvedAuctionId && record.auctionId && record.auctionId !== resolvedAuctionId;
3254
+ const isRefresh = Boolean(adUnitCode && record && isDifferentAuction);
3255
+ if (isRefresh) {
3256
+ this.flushSlotTimeInView(adUnitCode);
3257
+ const nextRefreshIndex = (this.slotRefreshIndices.get(adUnitCode) ?? (record ? record.refreshIndex : 0)) + 1;
3258
+ this.slotRefreshIndices.set(adUnitCode, nextRefreshIndex);
3259
+ this.slotLastAuctionIds.set(adUnitCode, resolvedAuctionId);
3260
+ if (record) {
3261
+ record.auctionId = resolvedAuctionId;
3262
+ record.transactionId = resolvedTransactionId;
3263
+ record.bidPayload = bidTrace;
3264
+ }
3265
+ } else if (adUnitCode) {
3266
+ if (resolvedAuctionId) {
3267
+ this.slotLastAuctionIds.set(adUnitCode, resolvedAuctionId);
3268
+ }
3269
+ if (!this.slotRefreshIndices.has(adUnitCode)) {
3270
+ this.slotRefreshIndices.set(adUnitCode, 0);
3271
+ }
3272
+ }
3273
+ const currentRefreshIndex = adUnitCode ? this.slotRefreshIndices.get(adUnitCode) ?? (record ? record.refreshIndex : 0) : 0;
3274
+ if (!isVideo) {
3275
+ const alreadyEmitted = adUnitCode ? this.hasImpressionEmitted(
3276
+ adUnitCode,
3277
+ currentRefreshIndex,
3278
+ resolvedAuctionId,
3279
+ bidTrace.creativeId
3280
+ ) : false;
3281
+ if (!alreadyEmitted) {
3282
+ if (adUnitCode) {
3283
+ this.markImpressionEmitted(
3284
+ adUnitCode,
3285
+ currentRefreshIndex,
3286
+ resolvedAuctionId,
3287
+ bidTrace.creativeId
3288
+ );
3289
+ }
3290
+ this.enqueue(TraceEventType.IMPRESSION, "impression", {
3291
+ auctionId: resolvedAuctionId,
3292
+ transactionId: resolvedTransactionId,
3293
+ adUnitCode,
3294
+ bid: bidTrace,
3295
+ metadata: { refresh_index: String(currentRefreshIndex) }
3296
+ });
3297
+ }
3298
+ } else {
3299
+ this.log(
3300
+ "DEBUG",
3301
+ `adRenderSucceeded received for video ad unit ${adUnitCode || "unknown"}: suppressing IMPRESSION until verified video lifecycle event`
3302
+ );
3303
+ }
3304
+ if (this.config.viewabilityEnabled && typeof document !== "undefined") {
3305
+ let el = adUnitCode && this.slotElements.get(adUnitCode) || null;
3306
+ const targetId = adUnitCode || data.adId || bid.adId;
3307
+ if (!el && targetId) {
3308
+ el = document.getElementById(targetId);
3309
+ }
3310
+ if (!el && typeof window !== "undefined" && window.googletag?.pubads) {
3311
+ try {
3312
+ const slots = window.googletag.pubads().getSlots();
3313
+ for (const slot of slots) {
3314
+ if (slot.getAdUnitPath?.() === adUnitCode || slot.getSlotElementId?.() === adUnitCode) {
3315
+ el = document.getElementById(slot.getSlotElementId());
3316
+ if (el) break;
3317
+ }
3318
+ }
3319
+ } catch {
3320
+ }
3321
+ }
3322
+ if (!el && targetId) {
3323
+ try {
3324
+ for (const candidate of Array.from(document.querySelectorAll("[data-ad-slot]"))) {
3325
+ if (candidate.getAttribute("data-ad-slot") === targetId) {
3326
+ el = candidate;
3327
+ break;
3328
+ }
3329
+ }
3330
+ } catch {
3331
+ }
3332
+ }
3333
+ if (el) {
3334
+ this.observeSlot(el, adUnitCode || targetId, {
3335
+ adUnitCode,
3336
+ auctionId: resolvedAuctionId,
3337
+ transactionId: resolvedTransactionId,
3338
+ mediaType: resolvedMediaType,
3339
+ bid: bidTrace,
3340
+ refreshIndex: currentRefreshIndex,
3341
+ isRefresh
3342
+ });
3343
+ } else if (record && isRefresh) {
3344
+ record.refreshIndex = currentRefreshIndex;
3345
+ record.viewableFired = false;
3346
+ record.accumulatedTimeInViewMs = 0;
3347
+ }
3348
+ }
3349
+ }
3350
+ isDuplicate(eventName, data) {
3351
+ return this.deduper.isDuplicate(eventName, data);
3352
+ }
3353
+ enqueue(type, eventName, data) {
3354
+ if (!this.isEnabled) return;
3355
+ if (!this.shouldSample(type)) return;
3356
+ if (this.managesSessionId && sessionNeedsSync()) {
3357
+ this.config.sessionId = getOrCreateSessionId();
3358
+ }
3359
+ const protoEvent = {
3360
+ eventId: idToBytes(generateUUID2()),
3361
+ timestampMs: Date.now(),
3362
+ type,
3363
+ // Typed events have a fixed name that ingest derives from `type`; only
3364
+ // ERROR and WARN carry theirs, which names the failure or condition.
3365
+ eventName: SELF_NAMING_TYPES.has(type) ? eventName : "",
3366
+ auctionId: idToBytes(String(data.auctionId || "")),
3367
+ transactionId: idToBytes(String(data.transactionId || "")),
3368
+ adUnitCode: data.adUnitCode || data.elementId || "",
3369
+ namespace: data.ns || data.namespace || ""
3370
+ };
3371
+ if (data.bid) {
3372
+ protoEvent.bid = {
3373
+ bidder: data.bid.bidder || "",
3374
+ cpm: Number.isFinite(data.bid.cpm) ? data.bid.cpm : 0,
3375
+ // No defaults here: handlers with a priced bid (bidWon, impression)
3376
+ // set currency/mediaType themselves. Defaulting for the rest would
3377
+ // stamp fake "USD"/"banner" on rows that carried no bid.
3378
+ currency: data.bid.currency || "",
3379
+ width: Number.isFinite(data.bid.width) ? data.bid.width : 0,
3380
+ height: Number.isFinite(data.bid.height) ? data.bid.height : 0,
3381
+ dealId: data.bid.dealId || "",
3382
+ mediaType: data.bid.mediaType || "",
3383
+ latencyMs: Number.isFinite(data.bid.latencyMs) ? data.bid.latencyMs : 0,
3384
+ advertiserDomain: data.bid.advertiserDomain || "",
3385
+ creativeId: data.bid.creativeId || ""
3386
+ };
3387
+ }
3388
+ if (data.viewableDurationMs !== void 0) {
3389
+ protoEvent.viewableDurationMs = Number.isFinite(data.viewableDurationMs) ? data.viewableDurationMs : 0;
3390
+ }
3391
+ if (data.bidderOutcomes && Array.isArray(data.bidderOutcomes)) {
3392
+ protoEvent.bidderOutcomes = data.bidderOutcomes.map(
3393
+ (entry) => {
3394
+ const floor = this.floorDecisionFor(String(data.auctionId || ""), entry.adUnitCode || "");
3395
+ const slot2 = entry.slot || this.slotNames.get(entry.adUnitCode || "");
3396
+ return {
3397
+ ...entry,
3398
+ ...slot2 ? { slot: slot2 } : {},
3399
+ refreshIndex: entry.refreshIndex ?? this.auctionCycleIndex(entry.adUnitCode || ""),
3400
+ ...floor ? {
3401
+ floorCents: floor.floorCents,
3402
+ floorSource: FLOOR_SOURCE_PROTO[floor.source],
3403
+ floorTreatmentBp: Math.round(floor.treatment * 1e4)
3404
+ } : {}
3405
+ };
3406
+ }
3407
+ );
3408
+ }
3409
+ const metadata = { ...data.metadata };
3410
+ const slot = protoEvent.adUnitCode ? this.slotNames.get(protoEvent.adUnitCode) : void 0;
3411
+ if (slot && metadata.slot === void 0) metadata.slot = slot;
3412
+ if (type === TraceEventType.BID_WIN || type === TraceEventType.IMPRESSION) {
3413
+ const floor = this.floorDecisionFor(
3414
+ String(data.auctionId || ""),
3415
+ protoEvent.adUnitCode || ""
3416
+ );
3417
+ if (floor) {
3418
+ if (floor.floorCents !== void 0) metadata.floor_cents = String(floor.floorCents);
3419
+ metadata.floor_source = floor.source;
3420
+ metadata.floor_treatment = floor.treatment.toFixed(2);
3421
+ }
3422
+ }
3423
+ if (data.error !== void 0 && data.error !== null) {
3424
+ metadata.error = typeof data.error === "object" && data.error.message ? String(data.error.message) : String(data.error);
3425
+ }
3426
+ if (data.gpid) {
3427
+ metadata.gpid = String(data.gpid);
3428
+ }
3429
+ if (data.refreshIndex !== void 0 && metadata.refresh_index === void 0) {
3430
+ metadata.refresh_index = String(data.refreshIndex);
3431
+ }
3432
+ const boundedMetadata = boundMetadata(metadata);
3433
+ if (Object.keys(boundedMetadata).length > 0) {
3434
+ protoEvent.metadata = boundedMetadata;
3435
+ }
3436
+ this.queue.push(protoEvent);
3437
+ if (this.queue.length >= MAX_QUEUE_SIZE) {
3438
+ this.flush();
3439
+ if (this.queue.length > MAX_QUEUE_SIZE) {
3440
+ this.queue.splice(0, this.queue.length - MAX_QUEUE_SIZE);
3441
+ }
3442
+ } else if (REVENUE_FLUSH_TYPES.has(type) && this.revenueFlushTimer === null) {
3443
+ this.revenueFlushTimer = setTimeout(() => {
3444
+ this.revenueFlushTimer = null;
3445
+ this.flush();
3446
+ }, this.config.revenueFlushDelayMs);
3447
+ }
3448
+ }
3449
+ isSampledVisitor() {
3450
+ const key = this.config.visitorId || this.config.userId || this.config.pageviewId;
3451
+ return isVisitorSampled(key, this.config.sampleRate);
3452
+ }
3453
+ shouldSample(type) {
3454
+ if (!this.isSampledVisitor()) {
3455
+ return false;
3456
+ }
3457
+ if (type === TraceEventType.ERROR) {
3458
+ this.errorCount++;
3459
+ return this.errorCount <= MAX_ERRORS_PER_SESSION;
3460
+ }
3461
+ if (type === TraceEventType.CONSENT) {
3462
+ this.consentCount++;
3463
+ return this.consentCount <= MAX_CONSENT_EVENTS_PER_PAGEVIEW;
3464
+ }
3465
+ if (type === TraceEventType.WARN) {
3466
+ return this.config.warningsEnabled;
3467
+ }
3468
+ return this.config.auctionEnabled;
3469
+ }
3470
+ requeue(events) {
3471
+ if (!events.length) return;
3472
+ this.queue = events.concat(this.queue);
3473
+ if (this.queue.length > MAX_QUEUE_SIZE) {
3474
+ this.queue.splice(0, this.queue.length - MAX_QUEUE_SIZE);
3475
+ }
3476
+ }
3477
+ // Drains a batch (up to MAX_PAYLOAD_BYTES) from the queue.
3478
+ // Shared by flush() and flushBeacon().
3479
+ drainBatch() {
3480
+ if (this.queue.length === 0 || !this.config.endpoint) return null;
3481
+ const domain = typeof window !== "undefined" ? window.location.hostname : "";
3482
+ const sampleRate = normalizeSampleRate(this.config.sampleRate);
3483
+ const automated = typeof navigator !== "undefined" && navigator.webdriver === true;
3484
+ const buildBatch = (evts) => ({
3485
+ propertyId: idToBytes(this.config.propertyId),
3486
+ pageviewId: idToBytes(this.config.pageviewId),
3487
+ sessionId: idToBytes(this.config.sessionId),
3488
+ pageUrl: this.pageUrl,
3489
+ country: this.config.country,
3490
+ region: this.config.region,
3491
+ deviceType: this.config.deviceType,
3492
+ userId: this.config.userId || "",
3493
+ domain,
3494
+ events: evts,
3495
+ ...sampleRate < 1 ? { sampleRate } : {},
3496
+ ...automated ? { automated: true } : {}
3497
+ });
3498
+ const headerBytes = TraceEventBatch.encode(buildBatch([])).finish().byteLength;
3499
+ for (; ; ) {
3500
+ if (this.queue.length === 0) return null;
3501
+ let count = 0;
3502
+ let totalBytes = headerBytes;
3503
+ for (let i = 0; i < this.queue.length; i++) {
3504
+ const ev = this.queue[i];
3505
+ const eventBytes = TraceEvent.encode(ev).finish().byteLength;
3506
+ const entrySize = eventBytes + 6;
3507
+ if (totalBytes + entrySize > MAX_PAYLOAD_BYTES) {
3508
+ if (count === 0) {
3509
+ const [dropped] = this.queue.splice(0, 1);
3510
+ const singleBatchBytes = TraceEventBatch.encode(
3511
+ buildBatch([dropped])
3512
+ ).finish().byteLength;
3513
+ this.log(
3514
+ "WARN",
3515
+ `Dropping oversized event (type ${dropped?.type}, ${singleBatchBytes} bytes exceeds the ${MAX_PAYLOAD_BYTES}-byte cap on its own)`
3516
+ );
3517
+ break;
3518
+ }
3519
+ break;
3520
+ }
3521
+ totalBytes += entrySize;
3522
+ count++;
3523
+ }
3524
+ if (count === 0) {
3525
+ continue;
3526
+ }
3527
+ const events = this.queue.slice(0, count);
3528
+ const encoded = TraceEventBatch.encode(
3529
+ buildBatch(events)
3530
+ ).finish();
3531
+ this.queue = this.queue.slice(events.length);
3532
+ return {
3533
+ url: this.batchUrl(),
3534
+ // protobufjs types finish() as Uint8Array<ArrayBufferLike>; the buffer is
3535
+ // always a plain ArrayBuffer, so narrow for fetch/Blob compatibility.
3536
+ encoded,
3537
+ events
3538
+ };
3539
+ }
3540
+ }
3541
+ sendFetch(payload, useKeepalive = false, onDelivered, isReplay = false) {
3542
+ const fetchOpts = {
3543
+ method: "POST",
3544
+ // Safelisted content type: no CORS preflight (see SAFE_CONTENT_TYPE).
3545
+ headers: { "Content-Type": SAFE_CONTENT_TYPE2 },
3546
+ body: payload.encoded
3547
+ };
3548
+ if (useKeepalive) {
3549
+ fetchOpts.keepalive = true;
3550
+ }
3551
+ fetch(payload.url, fetchOpts).then((res) => {
3552
+ if (!res.ok) {
3553
+ this.log("WARN", `Failed to send batch: HTTP ${res.status}`);
3554
+ if (res.status >= 400 && res.status < 500 && res.status !== 429 && res.status !== 408) {
3555
+ this.log("WARN", `Dropping batch due to non-retryable client error HTTP ${res.status}`);
3556
+ return;
3557
+ }
3558
+ if (!isReplay) this.handleSendFailure(payload.events);
3559
+ } else {
3560
+ if (!isReplay) {
3561
+ this.consecutiveSendFailures = 0;
3562
+ this.nextSendAllowedAt = 0;
3563
+ }
3564
+ if (onDelivered) onDelivered();
3565
+ }
3566
+ }).catch((err) => {
3567
+ this.log("ERROR", "Failed to send batch", err);
3568
+ if (!isReplay) this.handleSendFailure(payload.events);
3569
+ });
3570
+ const proc = typeof globalThis !== "undefined" ? globalThis.process : void 0;
3571
+ if (proc && typeof proc._tickCallback === "function") {
3572
+ try {
3573
+ proc._tickCallback();
3574
+ } catch {
3575
+ }
3576
+ }
3577
+ }
3578
+ handleSendFailure(events) {
3579
+ this.consecutiveSendFailures++;
3580
+ const backoff = Math.min(
3581
+ FLUSH_INTERVAL_MS * 2 ** (this.consecutiveSendFailures - 1),
3582
+ MAX_SEND_BACKOFF_MS
3583
+ );
3584
+ this.nextSendAllowedAt = Date.now() + backoff;
3585
+ if (this.consecutiveSendFailures <= MAX_CONSECUTIVE_SEND_FAILURES) {
3586
+ this.requeue(events);
3587
+ } else {
3588
+ this.log(
3589
+ "WARN",
3590
+ `Dropping ${events.length} events after ${this.consecutiveSendFailures} consecutive send failures`
3591
+ );
3592
+ }
3593
+ }
3594
+ flush() {
3595
+ if (Date.now() < this.nextSendAllowedAt) return;
3596
+ let payload = this.drainBatch();
3597
+ let useKeepalive = true;
3598
+ while (payload) {
3599
+ this.sendFetch(payload, useKeepalive);
3600
+ useKeepalive = false;
3601
+ if (Date.now() < this.nextSendAllowedAt) break;
3602
+ payload = this.drainBatch();
3603
+ }
3604
+ }
3605
+ // The batch URL: the endpoint and the property.
3606
+ batchUrl() {
3607
+ return `${this.config.endpoint}/${this.config.propertyId}`;
3608
+ }
3609
+ flushBeacon() {
3610
+ let payload = this.drainBatch();
3611
+ while (payload) {
3612
+ let sent = false;
3613
+ if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") {
3614
+ try {
3615
+ const blob = new Blob([payload.encoded], { type: SAFE_CONTENT_TYPE2 });
3616
+ sent = navigator.sendBeacon(payload.url, blob);
3617
+ } catch {
3618
+ sent = false;
3619
+ }
3620
+ }
3621
+ if (!sent) {
3622
+ const persistKey = this.persistBatch(payload.encoded);
3623
+ this.sendFetch(payload, true, () => this.removePersistedBatch(persistKey));
3624
+ }
3625
+ payload = this.drainBatch();
3626
+ }
3627
+ this.schedulePersistedCleanup();
3628
+ }
3629
+ // --- Exit-batch persistence -----------------------------------------------
3630
+ // Key prefix for this instance's property. encodeURIComponent keeps the
3631
+ // property segment free of the "_" the timestamp suffix is parsed against,
3632
+ // so a property ID containing one cannot forge another property's prefix.
3633
+ pendingKeyPrefix() {
3634
+ return `${PENDING_BATCH_KEY_PREFIX}${encodeURIComponent(this.config.propertyId)}_`;
3635
+ }
3636
+ persistBatch(encoded) {
3637
+ if (!storageAllowed) return null;
3638
+ try {
3639
+ if (typeof localStorage === "undefined") return null;
3640
+ if (!this.config.propertyId) return null;
3641
+ let pendingCount = 0;
3642
+ for (let i = 0; i < localStorage.length; i++) {
3643
+ const k = localStorage.key(i);
3644
+ if (k && k.startsWith(PENDING_BATCH_KEY_PREFIX)) pendingCount++;
3645
+ }
3646
+ if (pendingCount >= MAX_PENDING_BATCHES) return null;
3647
+ const key = `${this.pendingKeyPrefix()}${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
3648
+ localStorage.setItem(key, bytesToBase64(encoded));
3649
+ this.persistedBatchKeys.push(key);
3650
+ return key;
3651
+ } catch {
3652
+ return null;
3653
+ }
3654
+ }
3655
+ removePersistedBatch(key) {
3656
+ if (!key) return;
3657
+ try {
3658
+ if (typeof localStorage !== "undefined") localStorage.removeItem(key);
3659
+ } catch {
3660
+ }
3661
+ const idx = this.persistedBatchKeys.indexOf(key);
3662
+ if (idx !== -1) this.persistedBatchKeys.splice(idx, 1);
3663
+ }
3664
+ // A page that is still running PENDING_BATCH_CLEANUP_DELAY_MS after an exit
3665
+ // flush was never torn down, so its beacons have long since gone out; drop
3666
+ // the persisted copies rather than letting a later pageview resend them.
3667
+ schedulePersistedCleanup() {
3668
+ if (this.persistedBatchKeys.length === 0) return;
3669
+ if (this.persistedCleanupTimer) clearTimeout(this.persistedCleanupTimer);
3670
+ this.persistedCleanupTimer = setTimeout(() => {
3671
+ this.persistedCleanupTimer = null;
3672
+ for (const key of Array.from(this.persistedBatchKeys)) {
3673
+ this.removePersistedBatch(key);
3674
+ }
3675
+ }, PENDING_BATCH_CLEANUP_DELAY_MS);
3676
+ }
3677
+ // Resend batches a previous pageview persisted at exit but could not
3678
+ // confirm. Only this property's own keys are claimed: batches belonging to
3679
+ // another property sharing this origin are left for that property's next
3680
+ // pageview, since resending them here would file them under this property.
3681
+ // Keys are claimed (removed) before sending so concurrent tabs don't
3682
+ // double-send; the batch bytes carry their original pageview, session, and
3683
+ // event timestamps, so late rows attribute correctly.
3684
+ resendPersistedBatches() {
3685
+ try {
3686
+ if (typeof localStorage === "undefined" || !this.config.endpoint) return;
3687
+ if (!this.config.propertyId) return;
3688
+ const ownPrefix = this.pendingKeyPrefix();
3689
+ const keys = [];
3690
+ for (let i = 0; i < localStorage.length; i++) {
3691
+ const k = localStorage.key(i);
3692
+ if (k && k.startsWith(ownPrefix)) {
3693
+ keys.push(k);
3694
+ }
3695
+ }
3696
+ for (const key of keys) {
3697
+ let value = null;
3698
+ try {
3699
+ value = localStorage.getItem(key);
3700
+ localStorage.removeItem(key);
3701
+ } catch {
3702
+ continue;
3703
+ }
3704
+ if (!value) continue;
3705
+ const ts = parseInt(key.slice(ownPrefix.length), 10);
3706
+ if (!Number.isFinite(ts) || Date.now() - ts > PENDING_BATCH_MAX_AGE_MS) continue;
3707
+ let encoded;
3708
+ try {
3709
+ encoded = base64ToBytes(value);
3710
+ } catch {
3711
+ continue;
3712
+ }
3713
+ if (encoded.byteLength === 0) continue;
3714
+ this.log("DEBUG", `Resending persisted exit batch (${encoded.byteLength} bytes)`);
3715
+ this.sendFetch(
3716
+ {
3717
+ url: `${this.config.endpoint}/${this.config.propertyId}`,
3718
+ encoded,
3719
+ events: []
3720
+ },
3721
+ false,
3722
+ void 0,
3723
+ true
3724
+ );
3725
+ }
3726
+ } catch {
3727
+ }
3728
+ }
3729
+ log(level, msg, ...args) {
3730
+ this.logger.log(level, msg, ...args);
3731
+ }
3732
+ };
3733
+ function extractAnalyticsOptions(config, allowProviderless = true) {
3734
+ if (!config) return null;
3735
+ if (Array.isArray(config)) {
3736
+ const matched = config.find((item) => item?.provider === "bidspark") ?? (allowProviderless ? config.find(
3737
+ (item) => item && typeof item === "object" && item.provider === void 0
3738
+ ) : void 0);
3739
+ return matched ? extractAnalyticsOptions(matched, allowProviderless) : null;
3740
+ }
3741
+ if (typeof config === "object") {
3742
+ if (config.options && typeof config.options === "object") {
3743
+ return config.options;
3744
+ }
3745
+ if (config.config && typeof config.config === "object") {
3746
+ return config.config;
3747
+ }
3748
+ if (config.propertyId || config.endpoint) {
3749
+ return config;
3750
+ }
3751
+ }
3752
+ return null;
3753
+ }
3754
+ function getStashedConfig(win) {
3755
+ if (!win) return null;
3756
+ if (win._bidsparkAnalyticsConfig) {
3757
+ const extracted = extractAnalyticsOptions(win._bidsparkAnalyticsConfig);
3758
+ if (extracted) return extracted;
3759
+ }
3760
+ const bpa = win.bidsparkPrebidAnalytics;
3761
+ if (bpa) {
3762
+ if (bpa.options) {
3763
+ const extracted = extractAnalyticsOptions(bpa.options);
3764
+ if (extracted) return extracted;
3765
+ }
3766
+ if (bpa.config) {
3767
+ const extracted = extractAnalyticsOptions(bpa.config);
3768
+ if (extracted) return extracted;
3769
+ }
3770
+ if (bpa.propertyId) {
3771
+ return extractAnalyticsOptions(bpa);
3772
+ }
3773
+ }
3774
+ return null;
3775
+ }
3776
+ function registerPrebidAnalytics(pbjsGlobalName = "pbjs", defaults) {
3777
+ const win = typeof window !== "undefined" ? window : {};
3778
+ win[pbjsGlobalName] = win[pbjsGlobalName] || {};
3779
+ const pbjs = win[pbjsGlobalName];
3780
+ const enableInstance = (options) => {
3781
+ const previous = win._bidsparkPrebidAnalytics;
3782
+ const pinnedEndpoint = previous?.getEndpoint?.() || "";
3783
+ const defaultUsageEndpoint = defaults?.usageEndpoint || "https://by.bidspark.io/u";
3784
+ const merged = {
3785
+ pbjsGlobalName,
3786
+ ...defaults,
3787
+ ...options
3788
+ };
3789
+ merged.usageEndpoint = defaultUsageEndpoint;
3790
+ if (pinnedEndpoint && !sameEndpointOrigin(merged.endpoint || "", pinnedEndpoint)) {
3791
+ defaultLogger.warn(
3792
+ `Ignoring analytics endpoint change to ${merged.endpoint || "(empty)"}: this page is pinned to ${pinnedEndpoint}. Reload to change the ingest endpoint.`
3793
+ );
3794
+ merged.endpoint = pinnedEndpoint;
3795
+ }
3796
+ if (previous) {
3797
+ try {
3798
+ previous.disable();
3799
+ } catch (e) {
3800
+ defaultLogger.warn("Failed to disable previous analytics instance:", e);
3801
+ }
3802
+ }
3803
+ const analytics = new BidsparkPrebidAnalytics(merged);
3804
+ analytics.enable();
3805
+ win._bidsparkPrebidAnalytics = analytics;
3806
+ return analytics;
3807
+ };
3808
+ const doRegister = () => {
3809
+ try {
3810
+ if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3811
+ const adapter = {
3812
+ enableAnalytics: (config) => {
3813
+ const options = extractAnalyticsOptions(config, !Array.isArray(config));
3814
+ if (options) {
3815
+ enableInstance(options);
3816
+ }
3817
+ },
3818
+ disableAnalytics: () => {
3819
+ if (win._bidsparkPrebidAnalytics) {
3820
+ win._bidsparkPrebidAnalytics.disable();
3821
+ }
3822
+ }
3823
+ };
3824
+ pbjs.adapterManager.registerAnalyticsAdapter({
3825
+ adapter: { ...adapter },
3826
+ code: "bidspark"
3827
+ });
3828
+ }
3829
+ const stashed = getStashedConfig(win);
3830
+ if (stashed && (stashed.propertyId || defaults?.propertyId)) {
3831
+ enableInstance(stashed);
3832
+ }
3833
+ } catch (e) {
3834
+ defaultLogger.warn("Failed to register standard Prebid analytics adapter:", e);
3835
+ }
3836
+ };
3837
+ if (pbjs.adapterManager && typeof pbjs.adapterManager.registerAnalyticsAdapter === "function") {
3838
+ doRegister();
3839
+ } else {
3840
+ pbjs.que = pbjs.que || [];
3841
+ pbjs.que.push(doRegister);
3842
+ }
3843
+ }
3844
+
3845
+ // src/video.ts
3846
+ var internals = (analytics) => analytics;
3847
+ var adsLoaderListenerMap = /* @__PURE__ */ new WeakMap();
3848
+ var adsLoadersWithErrorListener = /* @__PURE__ */ new WeakSet();
3849
+ function describeImaError(event) {
3850
+ const err = typeof event?.getError === "function" ? event.getError() : event?.error || event;
3851
+ const call = (name) => err && typeof err[name] === "function" ? err[name]() : void 0;
3852
+ const message = call("getMessage") || err?.message || String(err || "IMA ad error");
3853
+ const code = call("getErrorCode") ?? err?.code;
3854
+ const vastCode = call("getVastErrorCode");
3855
+ const type = call("getType") ?? err?.type;
3856
+ const metadata = { message };
3857
+ if (code) metadata.error_code = String(code);
3858
+ if (vastCode) metadata.vast_error_code = String(vastCode);
3859
+ if (type) metadata.error_type = String(type);
3860
+ return { err, message, metadata };
3861
+ }
3862
+ function recordImaAdError(analytics, event, ctx) {
3863
+ const self = internals(analytics);
3864
+ const { err, message, metadata } = describeImaError(event);
3865
+ self.log("WARN", "IMA AdErrorEvent received", event);
3866
+ self.enqueue(TraceEventType.AD_RENDER_FAILED, "adRenderFailed", {
3867
+ auctionId: ctx.auctionId,
3868
+ transactionId: ctx.transactionId,
3869
+ adUnitCode: ctx.adUnitCode,
3870
+ bid: ctx.bid,
3871
+ metadata: {
3872
+ ...ctx.metadata,
3873
+ reason: ctx.adStarted ? "ima_playback_error" : "ima_ad_error",
3874
+ playback_phase: ctx.adStarted ? "post_start" : "pre_start",
3875
+ ...metadata
3876
+ },
3877
+ error: typeof err === "object" ? err : new Error(message)
3878
+ });
3879
+ return err;
3880
+ }
3881
+ function ensureAdsLoaderErrorListener(loader, addEventListener) {
3882
+ if (!loader || typeof loader !== "object" || adsLoadersWithErrorListener.has(loader)) return;
3883
+ adsLoadersWithErrorListener.add(loader);
3884
+ const type = typeof window !== "undefined" && window.google?.ima?.AdErrorEvent?.Type?.AD_ERROR || "adError";
3885
+ try {
3886
+ addEventListener.call(loader, type, (event) => {
3887
+ for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
3888
+ try {
3889
+ const cached = findCachedWinningBid(instance, { mediaType: "video" });
3890
+ recordImaAdError(instance, event, {
3891
+ adStarted: false,
3892
+ adUnitCode: cached?.adUnitCode || "video",
3893
+ auctionId: cached?.auctionId,
3894
+ transactionId: cached?.transactionId,
3895
+ bid: cached?.bidTrace
3896
+ });
3897
+ } catch {
3898
+ }
3899
+ }
3900
+ });
3901
+ } catch {
3902
+ }
3903
+ }
3904
+ function hookAdsManagerLoadedEvent(loadedEventCtor) {
3905
+ if (!loadedEventCtor) return;
3906
+ try {
3907
+ const loadedProto = loadedEventCtor.prototype;
3908
+ if (loadedProto && typeof loadedProto.getAdsManager === "function" && !loadedProto.getAdsManager.__bidsparkHooked) {
3909
+ const originalGetAdsManager = loadedProto.getAdsManager;
3910
+ const hookedGetAdsManager = function(...args) {
3911
+ const adsManager = originalGetAdsManager.apply(this, args);
3912
+ if (adsManager) {
3913
+ for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
3914
+ try {
3915
+ instance.attachImaAdsManager(adsManager);
3916
+ } catch {
3917
+ }
3918
+ }
3919
+ }
3920
+ return adsManager;
3921
+ };
3922
+ hookedGetAdsManager.__bidsparkHooked = true;
3923
+ loadedProto.getAdsManager = hookedGetAdsManager;
3924
+ }
3925
+ } catch {
3926
+ }
3927
+ }
3928
+ function hookAdsManagerPrototype(adsManagerCtorOrProto) {
3929
+ if (!adsManagerCtorOrProto) return;
3930
+ try {
3931
+ const proto = adsManagerCtorOrProto.prototype || adsManagerCtorOrProto;
3932
+ if (proto && typeof proto.init === "function" && !proto.init.__bidsparkHooked) {
3933
+ const origInit = proto.init;
3934
+ const hookedInit = function(...args) {
3935
+ for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
3936
+ try {
3937
+ instance.attachImaAdsManager(this);
3938
+ } catch {
3939
+ }
3940
+ }
3941
+ return origInit.apply(this, args);
3942
+ };
3943
+ hookedInit.__bidsparkHooked = true;
3944
+ proto.init = hookedInit;
3945
+ }
3946
+ if (proto && typeof proto.start === "function" && !proto.start.__bidsparkHooked) {
3947
+ const origStart = proto.start;
3948
+ const hookedStart = function(...args) {
3949
+ for (const instance of BidsparkPrebidAnalytics.getActiveInstances()) {
3950
+ try {
3951
+ instance.attachImaAdsManager(this);
3952
+ } catch {
3953
+ }
3954
+ }
3955
+ return origStart.apply(this, args);
3956
+ };
3957
+ hookedStart.__bidsparkHooked = true;
3958
+ proto.start = hookedStart;
3959
+ }
3960
+ } catch {
3961
+ }
3962
+ }
3963
+ function hookAdsLoader(adsLoaderCtor) {
3964
+ if (!adsLoaderCtor) return;
3965
+ try {
3966
+ const proto = adsLoaderCtor.prototype;
3967
+ if (!proto) return;
3968
+ if (typeof proto.addEventListener === "function" && !proto.addEventListener.__bidsparkHooked) {
3969
+ const origAddEventListener = proto.addEventListener;
3970
+ const hookedAddEventListener = function(type, listener, ...rest) {
3971
+ ensureAdsLoaderErrorListener(this, origAddEventListener);
3972
+ if ((type === "adsManagerLoaded" || type === (this?.AdsManagerLoadedEvent?.Type?.ADS_MANAGER_LOADED || "adsManagerLoaded")) && typeof listener === "function") {
3973
+ let wrappedListener = adsLoaderListenerMap.get(listener);
3974
+ if (!wrappedListener) {
3975
+ wrappedListener = function(event) {
3976
+ if (event && typeof event.getAdsManager === "function" && !event.getAdsManager.__bidsparkHooked) {
3977
+ const origGetAdsManager = event.getAdsManager;
3978
+ event.getAdsManager = function(...args) {
3979
+ const adsManager = origGetAdsManager.apply(this, args);
3980
+ if (adsManager) {
3981
+ for (const sdk of BidsparkPrebidAnalytics.getActiveInstances()) {
3982
+ try {
3983
+ sdk.attachImaAdsManager(adsManager);
3984
+ } catch {
3985
+ }
3986
+ }
3987
+ }
3988
+ return adsManager;
3989
+ };
3990
+ event.getAdsManager.__bidsparkHooked = true;
3991
+ }
3992
+ return listener.apply(this, arguments);
3993
+ };
3994
+ adsLoaderListenerMap.set(listener, wrappedListener);
3995
+ }
3996
+ return origAddEventListener.call(this, type, wrappedListener, ...rest);
3997
+ }
3998
+ return origAddEventListener.call(this, type, listener, ...rest);
3999
+ };
4000
+ hookedAddEventListener.__bidsparkHooked = true;
4001
+ proto.addEventListener = hookedAddEventListener;
4002
+ }
4003
+ if (typeof proto.removeEventListener === "function" && !proto.removeEventListener.__bidsparkHooked) {
4004
+ const origRemoveEventListener = proto.removeEventListener;
4005
+ const hookedRemoveEventListener = function(type, listener, ...rest) {
4006
+ const wrapped = typeof listener === "function" ? adsLoaderListenerMap.get(listener) : void 0;
4007
+ return origRemoveEventListener.call(this, type, wrapped || listener, ...rest);
4008
+ };
4009
+ hookedRemoveEventListener.__bidsparkHooked = true;
4010
+ proto.removeEventListener = hookedRemoveEventListener;
4011
+ }
4012
+ } catch {
4013
+ }
4014
+ }
4015
+ function hookImaPrototype(ima) {
4016
+ if (!ima || typeof ima !== "object") return;
4017
+ try {
4018
+ if (ima.AdsManagerLoadedEvent) {
4019
+ hookAdsManagerLoadedEvent(ima.AdsManagerLoadedEvent);
4020
+ }
4021
+ const loadedDesc = Object.getOwnPropertyDescriptor(ima, "AdsManagerLoadedEvent");
4022
+ if (!loadedDesc || loadedDesc.configurable) {
4023
+ let _loadedEvent = ima.AdsManagerLoadedEvent;
4024
+ try {
4025
+ Object.defineProperty(ima, "AdsManagerLoadedEvent", {
4026
+ configurable: true,
4027
+ enumerable: true,
4028
+ get() {
4029
+ return _loadedEvent;
4030
+ },
4031
+ set(val) {
4032
+ _loadedEvent = val;
4033
+ hookAdsManagerLoadedEvent(val);
4034
+ }
4035
+ });
4036
+ } catch {
4037
+ }
4038
+ }
4039
+ if (ima.AdsLoader) {
4040
+ hookAdsLoader(ima.AdsLoader);
4041
+ }
4042
+ const loaderDesc = Object.getOwnPropertyDescriptor(ima, "AdsLoader");
4043
+ if (!loaderDesc || loaderDesc.configurable) {
4044
+ let _loader = ima.AdsLoader;
4045
+ try {
4046
+ Object.defineProperty(ima, "AdsLoader", {
4047
+ configurable: true,
4048
+ enumerable: true,
4049
+ get() {
4050
+ return _loader;
4051
+ },
4052
+ set(val) {
4053
+ _loader = val;
4054
+ hookAdsLoader(val);
4055
+ }
4056
+ });
4057
+ } catch {
4058
+ }
4059
+ }
4060
+ if (ima.AdsManager) {
4061
+ hookAdsManagerPrototype(ima.AdsManager);
4062
+ }
4063
+ const mgrDesc = Object.getOwnPropertyDescriptor(ima, "AdsManager");
4064
+ if (!mgrDesc || mgrDesc.configurable) {
4065
+ let _mgr = ima.AdsManager;
4066
+ try {
4067
+ Object.defineProperty(ima, "AdsManager", {
4068
+ configurable: true,
4069
+ enumerable: true,
4070
+ get() {
4071
+ return _mgr;
4072
+ },
4073
+ set(val) {
4074
+ _mgr = val;
4075
+ hookAdsManagerPrototype(val);
4076
+ }
4077
+ });
4078
+ } catch {
4079
+ }
4080
+ }
4081
+ } catch {
4082
+ }
4083
+ }
4084
+ function initImaInterception() {
4085
+ if (typeof window === "undefined") return;
4086
+ const win = window;
4087
+ if (win.google?.ima) {
4088
+ hookImaPrototype(win.google.ima);
4089
+ }
4090
+ if (win.google && typeof win.google === "object") {
4091
+ const imaDesc = Object.getOwnPropertyDescriptor(win.google, "ima");
4092
+ if (!imaDesc || imaDesc.configurable) {
4093
+ let _ima = win.google.ima;
4094
+ try {
4095
+ Object.defineProperty(win.google, "ima", {
4096
+ configurable: true,
4097
+ enumerable: true,
4098
+ get() {
4099
+ return _ima;
4100
+ },
4101
+ set(val) {
4102
+ _ima = val;
4103
+ hookImaPrototype(val);
4104
+ }
4105
+ });
4106
+ } catch {
4107
+ }
4108
+ }
4109
+ }
4110
+ const googleDesc = Object.getOwnPropertyDescriptor(win, "google");
4111
+ if (!googleDesc || googleDesc.configurable) {
4112
+ let _google = win.google;
4113
+ try {
4114
+ Object.defineProperty(win, "google", {
4115
+ configurable: true,
4116
+ enumerable: true,
4117
+ get() {
4118
+ return _google;
4119
+ },
4120
+ set(val) {
4121
+ _google = val;
4122
+ if (_google && typeof _google === "object") {
4123
+ if (_google.ima) {
4124
+ hookImaPrototype(_google.ima);
4125
+ }
4126
+ const iDesc = Object.getOwnPropertyDescriptor(_google, "ima");
4127
+ if (!iDesc || iDesc.configurable) {
4128
+ let _i = _google.ima;
4129
+ try {
4130
+ Object.defineProperty(_google, "ima", {
4131
+ configurable: true,
4132
+ enumerable: true,
4133
+ get() {
4134
+ return _i;
4135
+ },
4136
+ set(iv) {
4137
+ _i = iv;
4138
+ hookImaPrototype(iv);
4139
+ }
4140
+ });
4141
+ } catch {
4142
+ }
4143
+ }
4144
+ }
4145
+ }
4146
+ });
4147
+ } catch {
4148
+ }
4149
+ }
4150
+ }
4151
+ if (typeof window !== "undefined") {
4152
+ initImaInterception();
4153
+ }
4154
+ function findCachedWinningBid(analytics, filter) {
4155
+ const self = internals(analytics);
4156
+ const now = Date.now();
4157
+ const isConsumed = (entry) => {
4158
+ return self.hasImpressionEmitted(
4159
+ entry.adUnitCode,
4160
+ void 0,
4161
+ entry.auctionId,
4162
+ entry.bidTrace.creativeId
4163
+ );
4164
+ };
4165
+ if (filter?.creativeId || filter?.adId) {
4166
+ for (const entry of Array.from(self.cachedWinningBids.values())) {
4167
+ if (now - entry.timestamp > CACHED_BID_TTL_MS) continue;
4168
+ if (filter.creativeId && (entry.bidTrace.creativeId === filter.creativeId || entry.rawBid?.creativeId === filter.creativeId) || filter.adId && (entry.rawBid?.adId === filter.adId || entry.adUnitCode === filter.adId)) {
4169
+ return entry;
4170
+ }
4171
+ }
4172
+ }
4173
+ let bestUnconsumedMatch;
4174
+ if (filter?.mediaType) {
4175
+ for (const entry of Array.from(self.cachedWinningBids.values())) {
4176
+ if (now - entry.timestamp > CACHED_BID_TTL_MS) continue;
4177
+ const isEntryVideo = entry.bidTrace.mediaType === filter.mediaType || entry.rawBid?.mediaType === filter.mediaType || filter.mediaType === "video" && entry.rawBid?.mediaTypes?.video !== void 0;
4178
+ if (isEntryVideo) {
4179
+ if (!isConsumed(entry)) {
4180
+ if (!bestUnconsumedMatch || entry.timestamp < bestUnconsumedMatch.timestamp) {
4181
+ bestUnconsumedMatch = entry;
4182
+ }
4183
+ }
4184
+ }
4185
+ }
4186
+ if (bestUnconsumedMatch) return bestUnconsumedMatch;
4187
+ let bestFallbackMatch;
4188
+ for (const entry of Array.from(self.cachedWinningBids.values())) {
4189
+ if (now - entry.timestamp > CACHED_BID_TTL_MS) continue;
4190
+ const isEntryVideo = entry.bidTrace.mediaType === filter.mediaType || entry.rawBid?.mediaType === filter.mediaType || filter.mediaType === "video" && entry.rawBid?.mediaTypes?.video !== void 0;
4191
+ if (isEntryVideo) {
4192
+ if (!bestFallbackMatch || entry.timestamp > bestFallbackMatch.timestamp) {
4193
+ bestFallbackMatch = entry;
4194
+ }
4195
+ }
4196
+ }
4197
+ if (bestFallbackMatch) return bestFallbackMatch;
4198
+ }
4199
+ for (const entry of Array.from(self.cachedWinningBids.values())) {
4200
+ if (now - entry.timestamp > CACHED_BID_TTL_MS) continue;
4201
+ if (!isConsumed(entry)) {
4202
+ if (!bestUnconsumedMatch || entry.timestamp > bestUnconsumedMatch.timestamp) {
4203
+ bestUnconsumedMatch = entry;
4204
+ }
4205
+ }
4206
+ }
4207
+ if (bestUnconsumedMatch) return bestUnconsumedMatch;
4208
+ let bestRecent;
4209
+ for (const entry of Array.from(self.cachedWinningBids.values())) {
4210
+ if (now - entry.timestamp > CACHED_BID_TTL_MS) continue;
4211
+ if (!bestRecent || entry.timestamp > bestRecent.timestamp) {
4212
+ bestRecent = entry;
4213
+ }
4214
+ }
4215
+ return bestRecent;
4216
+ }
4217
+ function attachImaAdsManager(analytics, adsManager, options) {
4218
+ const self = internals(analytics);
4219
+ if (!adsManager || typeof adsManager.addEventListener !== "function") {
4220
+ self.log("WARN", "Invalid AdsManager passed to attachImaAdsManager");
4221
+ return () => {
4222
+ };
4223
+ }
4224
+ if (!adsManager.__bidsparkAttachedInstances) {
4225
+ try {
4226
+ Object.defineProperty(adsManager, "__bidsparkAttachedInstances", {
4227
+ value: /* @__PURE__ */ new Map(),
4228
+ configurable: true,
4229
+ writable: true
4230
+ });
4231
+ } catch {
4232
+ adsManager.__bidsparkAttachedInstances = /* @__PURE__ */ new Map();
4233
+ }
4234
+ }
4235
+ const attached = adsManager.__bidsparkAttachedInstances;
4236
+ const previous = attached.get(analytics);
4237
+ if (previous) {
4238
+ if (!options) return () => {
4239
+ };
4240
+ previous();
4241
+ }
4242
+ const slotId = options?.slotId || options?.adUnitCode || "video";
4243
+ const adUnitCode = options?.adUnitCode || slotId;
4244
+ const auctionId = options?.auctionId || "";
4245
+ const transactionId = options?.transactionId || "";
4246
+ const getWinningBid = (adData) => {
4247
+ let cached = (auctionId ? self.getCachedBid(`${auctionId}:${adUnitCode}`) : void 0) || (auctionId && slotId !== adUnitCode ? self.getCachedBid(`${auctionId}:${slotId}`) : void 0) || (adUnitCode !== "video" ? self.getCachedBid(adUnitCode) : void 0) || (slotId !== adUnitCode && slotId !== "video" ? self.getCachedBid(slotId) : void 0);
4248
+ if (!cached) {
4249
+ cached = findCachedWinningBid(analytics, {
4250
+ creativeId: adData?.creativeId,
4251
+ adId: adData?.adId,
4252
+ mediaType: "video"
4253
+ });
4254
+ }
4255
+ return cached;
4256
+ };
4257
+ let adStarted = false;
4258
+ let activeAdSession = null;
4259
+ const mintAdSession = (initialAd) => {
4260
+ const nextSession = typeof self.nextSlotAdSession === "function" ? self.nextSlotAdSession(slotId) : `ad-session-${(self.slotAdSessionCounters?.get(slotId) ?? 0) + 1}`;
4261
+ if (self.slotAdSessionCounters && typeof self.nextSlotAdSession !== "function") {
4262
+ const c = (self.slotAdSessionCounters.get(slotId) ?? 0) + 1;
4263
+ self.slotAdSessionCounters.set(slotId, c);
4264
+ }
4265
+ const adId = (typeof initialAd?.getAdId === "function" ? initialAd.getAdId() : initialAd?.adId ?? initialAd?.id) || "";
4266
+ const creativeId = (typeof initialAd?.getCreativeId === "function" ? initialAd.getCreativeId() : initialAd?.creativeId) || "";
4267
+ activeAdSession = {
4268
+ sessionId: nextSession,
4269
+ adId: adId || void 0,
4270
+ creativeId: creativeId || void 0
4271
+ };
4272
+ return activeAdSession;
4273
+ };
4274
+ const onAdLoaded = (event) => {
4275
+ const ad = typeof event?.getAd === "function" ? event.getAd() : event?.ad;
4276
+ mintAdSession(ad);
4277
+ self.log("DEBUG", "IMA AdEvent.LOADED received", { slotId, activeAdSession });
4278
+ };
4279
+ const onAdStartedOrImpression = (event) => {
4280
+ adStarted = true;
4281
+ const ad = typeof event?.getAd === "function" ? event.getAd() : event?.ad;
4282
+ const adData = {};
4283
+ if (ad) {
4284
+ adData.creativeId = (typeof ad.getCreativeId === "function" ? ad.getCreativeId() : ad.creativeId) || "";
4285
+ adData.adId = (typeof ad.getAdId === "function" ? ad.getAdId() : ad.id) || "";
4286
+ adData.title = (typeof ad.getTitle === "function" ? ad.getTitle() : ad.title) || "";
4287
+ adData.duration = typeof ad.getDuration === "function" ? ad.getDuration() : ad.duration;
4288
+ adData.advertiserName = typeof ad.getAdvertiserName === "function" ? ad.getAdvertiserName() : "";
4289
+ }
4290
+ if (!activeAdSession || adData.adId && activeAdSession.adId && activeAdSession.adId !== adData.adId) {
4291
+ mintAdSession(ad);
4292
+ } else {
4293
+ if (!activeAdSession.adId && adData.adId) {
4294
+ activeAdSession.adId = adData.adId;
4295
+ }
4296
+ if (!activeAdSession.creativeId && adData.creativeId) {
4297
+ activeAdSession.creativeId = adData.creativeId;
4298
+ }
4299
+ }
4300
+ const session = activeAdSession || mintAdSession(ad);
4301
+ const cached = getWinningBid(adData);
4302
+ const resolvedSlotId = options?.slotId && options.slotId !== "video" ? options.slotId : options?.adUnitCode && options.adUnitCode !== "video" ? options.adUnitCode : cached?.adUnitCode || options?.slotId || options?.adUnitCode || "video";
4303
+ const resolvedAdUnitCode = options?.adUnitCode && options.adUnitCode !== "video" ? options.adUnitCode : cached?.adUnitCode || resolvedSlotId;
4304
+ const resolvedAuctionId = auctionId || cached?.auctionId || "";
4305
+ const resolvedTransactionId = transactionId || cached?.transactionId || "";
4306
+ const creativeId = session.creativeId || adData.creativeId || cached?.bidTrace?.creativeId || options?.bid?.creativeId || "";
4307
+ const stableAdIdentity = session.adId || adData.adId || creativeId || session.sessionId;
4308
+ const mergedBid = {
4309
+ ...cached?.rawBid || options?.bid,
4310
+ mediaType: "video",
4311
+ creativeId
4312
+ };
4313
+ const emitted = self.recordImpression(resolvedSlotId, {
4314
+ adUnitCode: resolvedAdUnitCode,
4315
+ auctionId: resolvedAuctionId,
4316
+ transactionId: resolvedTransactionId,
4317
+ mediaType: "video",
4318
+ bid: mergedBid,
4319
+ adId: stableAdIdentity,
4320
+ metadata: {
4321
+ ...options?.metadata,
4322
+ media_type: "video",
4323
+ ...adData.title ? { ad_title: adData.title } : {},
4324
+ ...Number.isFinite(adData.duration) ? { ad_duration_s: String(adData.duration) } : {}
4325
+ }
4326
+ });
4327
+ let rawType = typeof event?.type === "string" ? event.type : typeof event?.getType === "function" ? event.getType() : typeof event === "string" ? event : "";
4328
+ if (rawType.toLowerCase().startsWith("adevent.")) {
4329
+ rawType = rawType.slice(8);
4330
+ }
4331
+ const eventName = rawType ? rawType.toUpperCase() : "STARTED/IMPRESSION";
4332
+ self.log(
4333
+ "DEBUG",
4334
+ `IMA AdEvent.${eventName} received${emitted ? "" : " (second event for this ad, already counted)"}`,
4335
+ event
4336
+ );
4337
+ if (emitted && options?.onImpression) {
4338
+ try {
4339
+ options.onImpression(resolvedSlotId, { ad, bid: mergedBid });
4340
+ } catch (e) {
4341
+ self.log("ERROR", "Error in onImpression callback", e);
4342
+ }
4343
+ }
4344
+ };
4345
+ const onMilestone = (milestone) => {
4346
+ self.log("DEBUG", `IMA AdEvent milestone: ${milestone}`);
4347
+ if (options?.onMilestone) {
4348
+ try {
4349
+ options.onMilestone(milestone, slotId);
4350
+ } catch (e) {
4351
+ self.log("ERROR", "Error in onMilestone callback", e);
4352
+ }
4353
+ }
4354
+ };
4355
+ const onAdClick = (event) => {
4356
+ self.log("DEBUG", "IMA AdEvent.CLICK received", event);
4357
+ const cached = getWinningBid();
4358
+ const resolvedAdUnitCode = options?.adUnitCode && options.adUnitCode !== "video" ? options.adUnitCode : cached?.adUnitCode || slotId;
4359
+ self.enqueue(TraceEventType.CLICK, "click", {
4360
+ auctionId: auctionId || cached?.auctionId,
4361
+ transactionId: transactionId || cached?.transactionId,
4362
+ adUnitCode: resolvedAdUnitCode,
4363
+ bid: cached?.bidTrace || options?.bid,
4364
+ metadata: {
4365
+ ...options?.metadata,
4366
+ media_type: "video"
4367
+ }
4368
+ });
4369
+ };
4370
+ const onAdError = (event) => {
4371
+ activeAdSession = null;
4372
+ const cached = getWinningBid();
4373
+ const resolvedAdUnitCode = options?.adUnitCode && options.adUnitCode !== "video" ? options.adUnitCode : cached?.adUnitCode || slotId;
4374
+ const err = recordImaAdError(analytics, event, {
4375
+ adStarted,
4376
+ adUnitCode: resolvedAdUnitCode,
4377
+ auctionId: auctionId || cached?.auctionId,
4378
+ transactionId: transactionId || cached?.transactionId,
4379
+ bid: cached?.bidTrace || options?.bid,
4380
+ metadata: options?.metadata
4381
+ });
4382
+ if (options?.onError) {
4383
+ try {
4384
+ options.onError(err);
4385
+ } catch (e) {
4386
+ self.log("ERROR", "Error in onError callback", e);
4387
+ }
4388
+ }
4389
+ };
4390
+ const googleIma = typeof window !== "undefined" ? window.google?.ima : void 0;
4391
+ const adEventType = googleIma?.AdEvent?.Type || {};
4392
+ const adErrorEventType = googleIma?.AdErrorEvent?.Type || {};
4393
+ const rawListeners = [
4394
+ { type: adEventType.LOADED || "loaded", handler: onAdLoaded },
4395
+ { type: adEventType.STARTED || "started", handler: onAdStartedOrImpression },
4396
+ { type: adEventType.IMPRESSION || "impression", handler: onAdStartedOrImpression },
4397
+ {
4398
+ type: adEventType.FIRST_QUARTILE || "firstQuartile",
4399
+ handler: () => onMilestone("firstQuartile")
4400
+ },
4401
+ { type: adEventType.MIDPOINT || "midpoint", handler: () => onMilestone("midpoint") },
4402
+ {
4403
+ type: adEventType.THIRD_QUARTILE || "thirdQuartile",
4404
+ handler: () => onMilestone("thirdQuartile")
4405
+ },
4406
+ {
4407
+ type: adEventType.COMPLETE || "complete",
4408
+ handler: () => {
4409
+ activeAdSession = null;
4410
+ onMilestone("complete");
4411
+ }
4412
+ },
4413
+ {
4414
+ type: adEventType.ALL_ADS_COMPLETED || "allAdsCompleted",
4415
+ handler: () => {
4416
+ activeAdSession = null;
4417
+ }
4418
+ },
4419
+ { type: adEventType.CLICK || "click", handler: onAdClick },
4420
+ { type: adErrorEventType.AD_ERROR || "adError", handler: onAdError }
4421
+ ];
4422
+ const seenListenerTypes = /* @__PURE__ */ new Set();
4423
+ const listeners = [];
4424
+ for (const l of rawListeners) {
4425
+ if (!seenListenerTypes.has(l.type)) {
4426
+ seenListenerTypes.add(l.type);
4427
+ listeners.push(l);
4428
+ }
4429
+ }
4430
+ for (const { type, handler } of listeners) {
4431
+ try {
4432
+ adsManager.addEventListener(type, handler);
4433
+ } catch {
4434
+ }
4435
+ }
4436
+ const cleanup = () => {
4437
+ activeAdSession = null;
4438
+ attached.delete(analytics);
4439
+ for (const { type, handler } of listeners) {
4440
+ try {
4441
+ adsManager.removeEventListener(type, handler);
4442
+ } catch {
4443
+ }
4444
+ }
4445
+ self.videoDetachCleanups.delete(cleanup);
4446
+ };
4447
+ attached.set(analytics, cleanup);
4448
+ self.videoDetachCleanups.add(cleanup);
4449
+ return cleanup;
4450
+ }
4451
+ function attachVideoPlayer(analytics, target, options) {
4452
+ const self = internals(analytics);
4453
+ if (!target) {
4454
+ self.log("WARN", "attachVideoPlayer called with null/undefined target");
4455
+ return () => {
4456
+ };
4457
+ }
4458
+ let el = null;
4459
+ if (typeof target === "string") {
4460
+ if (typeof document !== "undefined") {
4461
+ try {
4462
+ el = document.querySelector(target) || document.getElementById(target);
4463
+ } catch {
4464
+ el = document.getElementById(target);
4465
+ }
4466
+ }
4467
+ } else if (typeof HTMLElement !== "undefined" && target instanceof HTMLElement) {
4468
+ el = target;
4469
+ } else if (target && typeof target === "object" && target.nodeType === 1) {
4470
+ el = target;
4471
+ } else if (typeof target.addEventListener === "function" && (typeof target.init === "function" || typeof target.start === "function" || typeof target.getCuePoints === "function" || typeof target.getVolume === "function" || target.__imaAdsManager)) {
4472
+ return attachImaAdsManager(analytics, target, options);
4473
+ } else if (target && typeof target.addEventListener === "function") {
4474
+ el = target;
4475
+ }
4476
+ const slotId = options?.slotId || options?.adUnitCode || (el ? el.id : "") || "video";
4477
+ const adUnitCode = options?.adUnitCode || slotId;
4478
+ const auctionId = options?.auctionId || "";
4479
+ const transactionId = options?.transactionId || "";
4480
+ const getWinningBid = () => {
4481
+ 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);
4482
+ };
4483
+ let videoEl = null;
4484
+ if (el) {
4485
+ if (el.tagName && el.tagName.toLowerCase() === "video") {
4486
+ videoEl = el;
4487
+ } else {
4488
+ videoEl = el.querySelector("video");
4489
+ }
4490
+ }
4491
+ const quartilesFired = {
4492
+ q1: false,
4493
+ q2: false,
4494
+ q3: false,
4495
+ q4: false
4496
+ };
4497
+ const triggerPlaybackImpression = (activeVideo) => {
4498
+ const vEl = activeVideo || videoEl || (el?.querySelector ? el.querySelector("video") : null);
4499
+ const cached = getWinningBid();
4500
+ const mergedBid = {
4501
+ ...cached?.rawBid || options?.bid,
4502
+ mediaType: "video"
4503
+ };
4504
+ const emitted = self.recordImpression(slotId, {
4505
+ adUnitCode,
4506
+ auctionId: auctionId || cached?.auctionId,
4507
+ transactionId: transactionId || cached?.transactionId,
4508
+ mediaType: "video",
4509
+ bid: mergedBid,
4510
+ metadata: {
4511
+ ...options?.metadata,
4512
+ media_type: "video",
4513
+ ...vEl && Number.isFinite(vEl.duration) ? { video_duration_s: String(Math.round(vEl.duration)) } : {}
4514
+ }
4515
+ });
4516
+ if (emitted && options?.onImpression) {
4517
+ try {
4518
+ options.onImpression(slotId, { element: vEl || el, bid: mergedBid });
4519
+ } catch (e) {
4520
+ self.log("ERROR", "Error in onImpression callback", e);
4521
+ }
4522
+ }
4523
+ };
4524
+ const handlePlaying = (e) => {
4525
+ self.log("DEBUG", "HTML5 video playing event received");
4526
+ const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4527
+ triggerPlaybackImpression(targetVideo);
4528
+ };
4529
+ const handleTimeUpdate = (e) => {
4530
+ const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4531
+ if (targetVideo && targetVideo.currentTime > 0) {
4532
+ triggerPlaybackImpression(targetVideo);
4533
+ if (Number.isFinite(targetVideo.duration) && targetVideo.duration > 0) {
4534
+ const progress = targetVideo.currentTime / targetVideo.duration;
4535
+ if (progress >= 0.25 && !quartilesFired.q1) {
4536
+ quartilesFired.q1 = true;
4537
+ options?.onMilestone?.("firstQuartile", slotId);
4538
+ }
4539
+ if (progress >= 0.5 && !quartilesFired.q2) {
4540
+ quartilesFired.q2 = true;
4541
+ options?.onMilestone?.("midpoint", slotId);
4542
+ }
4543
+ if (progress >= 0.75 && !quartilesFired.q3) {
4544
+ quartilesFired.q3 = true;
4545
+ options?.onMilestone?.("thirdQuartile", slotId);
4546
+ }
4547
+ }
4548
+ }
4549
+ };
4550
+ const handleEnded = () => {
4551
+ if (!quartilesFired.q4) {
4552
+ quartilesFired.q4 = true;
4553
+ options?.onMilestone?.("complete", slotId);
4554
+ }
4555
+ };
4556
+ const handleError = (e) => {
4557
+ const targetVideo = e?.target instanceof HTMLVideoElement ? e.target : videoEl;
4558
+ const err = targetVideo?.error || videoEl?.error;
4559
+ const cached = getWinningBid();
4560
+ const msg = err ? `HTML5 video error code ${err.code}: ${err.message}` : "Video playback error";
4561
+ self.log("WARN", msg);
4562
+ self.enqueue(TraceEventType.AD_RENDER_FAILED, "adRenderFailed", {
4563
+ auctionId: auctionId || cached?.auctionId,
4564
+ transactionId: transactionId || cached?.transactionId,
4565
+ adUnitCode,
4566
+ bid: cached?.bidTrace || options?.bid,
4567
+ metadata: {
4568
+ ...options?.metadata,
4569
+ reason: "html5_video_error",
4570
+ message: msg,
4571
+ ...err?.code ? { error_code: String(err.code) } : {}
4572
+ },
4573
+ error: err ? new Error(msg) : void 0
4574
+ });
4575
+ if (options?.onError) {
4576
+ try {
4577
+ options.onError(err);
4578
+ } catch (e2) {
4579
+ self.log("ERROR", "Error in onError callback", e2);
4580
+ }
4581
+ }
4582
+ };
4583
+ const attachListenersToVideo = (targetVideo) => {
4584
+ targetVideo.addEventListener("playing", handlePlaying);
4585
+ targetVideo.addEventListener("play", handlePlaying);
4586
+ targetVideo.addEventListener("timeupdate", handleTimeUpdate);
4587
+ targetVideo.addEventListener("ended", handleEnded);
4588
+ targetVideo.addEventListener("error", handleError);
4589
+ };
4590
+ const removeListenersFromVideo = (targetVideo) => {
4591
+ targetVideo.removeEventListener("playing", handlePlaying);
4592
+ targetVideo.removeEventListener("play", handlePlaying);
4593
+ targetVideo.removeEventListener("timeupdate", handleTimeUpdate);
4594
+ targetVideo.removeEventListener("ended", handleEnded);
4595
+ targetVideo.removeEventListener("error", handleError);
4596
+ };
4597
+ let mutationObserver = null;
4598
+ if (el && el !== videoEl) {
4599
+ el.addEventListener("playing", handlePlaying, true);
4600
+ el.addEventListener("play", handlePlaying, true);
4601
+ el.addEventListener("timeupdate", handleTimeUpdate, true);
4602
+ el.addEventListener("ended", handleEnded, true);
4603
+ el.addEventListener("error", handleError, true);
4604
+ }
4605
+ if (videoEl) {
4606
+ attachListenersToVideo(videoEl);
4607
+ }
4608
+ if (el && el.tagName?.toLowerCase() !== "video" && typeof MutationObserver !== "undefined") {
4609
+ mutationObserver = new MutationObserver(() => {
4610
+ const found = el.querySelector("video");
4611
+ if (found && found !== videoEl) {
4612
+ if (videoEl) removeListenersFromVideo(videoEl);
4613
+ videoEl = found;
4614
+ if (videoEl) attachListenersToVideo(videoEl);
4615
+ }
4616
+ });
4617
+ mutationObserver.observe(el, { childList: true, subtree: true });
4618
+ }
4619
+ const cachedInitial = getWinningBid();
4620
+ if (options?.trackViewability !== false && el) {
4621
+ self.observeSlot(el, slotId, {
4622
+ adUnitCode,
4623
+ auctionId: auctionId || cachedInitial?.auctionId,
4624
+ transactionId: transactionId || cachedInitial?.transactionId,
4625
+ mediaType: "video",
4626
+ bid: cachedInitial?.bidTrace || options?.bid,
4627
+ metadata: options?.metadata
4628
+ });
4629
+ }
4630
+ const cleanup = () => {
4631
+ if (mutationObserver) {
4632
+ mutationObserver.disconnect();
4633
+ mutationObserver = null;
4634
+ }
4635
+ if (el && el !== videoEl) {
4636
+ el.removeEventListener("playing", handlePlaying, true);
4637
+ el.removeEventListener("play", handlePlaying, true);
4638
+ el.removeEventListener("timeupdate", handleTimeUpdate, true);
4639
+ el.removeEventListener("ended", handleEnded, true);
4640
+ el.removeEventListener("error", handleError, true);
4641
+ }
4642
+ if (videoEl) {
4643
+ removeListenersFromVideo(videoEl);
4644
+ }
4645
+ self.videoDetachCleanups.delete(cleanup);
4646
+ };
4647
+ self.videoDetachCleanups.add(cleanup);
4648
+ return cleanup;
4649
+ }
4650
+ BidsparkPrebidAnalytics.prototype.attachImaAdsManager = function(adsManager, options) {
4651
+ return attachImaAdsManager(this, adsManager, options);
4652
+ };
4653
+ BidsparkPrebidAnalytics.prototype.attachVideoPlayer = function(target, options) {
4654
+ return attachVideoPlayer(this, target, options);
4655
+ };
4656
+ var coreEnable = BidsparkPrebidAnalytics.prototype.enable;
4657
+ BidsparkPrebidAnalytics.prototype.enable = function() {
4658
+ coreEnable.call(this);
4659
+ if (typeof window !== "undefined") {
4660
+ initImaInterception();
4661
+ if (window.google?.ima) {
4662
+ hookImaPrototype(window.google.ima);
4663
+ }
4664
+ }
4665
+ };
4666
+ function normalizeImaEventName(name) {
4667
+ if (!name) return "";
4668
+ const lower = name.toLowerCase().replace(/[_-]/g, "");
4669
+ switch (lower) {
4670
+ case "started":
4671
+ case "start":
4672
+ case "impression":
4673
+ return "started";
4674
+ case "firstquartile":
4675
+ return "firstQuartile";
4676
+ case "midpoint":
4677
+ return "midpoint";
4678
+ case "thirdquartile":
4679
+ return "thirdQuartile";
4680
+ case "complete":
4681
+ case "completed":
4682
+ case "ended":
4683
+ return "complete";
4684
+ case "click":
4685
+ case "clicked":
4686
+ return "click";
4687
+ case "pause":
4688
+ case "paused":
4689
+ return "pause";
4690
+ case "resume":
4691
+ case "resumed":
4692
+ return "resume";
4693
+ case "skipped":
4694
+ case "skip":
4695
+ return "skipped";
4696
+ case "volumechanged":
4697
+ case "volumechange":
4698
+ return "volumeChanged";
4699
+ case "loaded":
4700
+ return "loaded";
4701
+ case "alladscompleted":
4702
+ return "allAdsCompleted";
4703
+ case "aderror":
4704
+ case "error":
4705
+ return "adError";
4706
+ default:
4707
+ return name;
4708
+ }
4709
+ }
4710
+ var ImaAdsManagerStub = class {
4711
+ listeners = /* @__PURE__ */ new Map();
4712
+ addEventListener(type, listener) {
4713
+ if (!type || typeof listener !== "function") return;
4714
+ const eventName = normalizeImaEventName(type);
4715
+ let set = this.listeners.get(eventName);
4716
+ if (!set) {
4717
+ set = /* @__PURE__ */ new Set();
4718
+ this.listeners.set(eventName, set);
4719
+ }
4720
+ set.add(listener);
4721
+ }
4722
+ removeEventListener(type, listener) {
4723
+ if (!type || typeof listener !== "function") return;
4724
+ const eventName = normalizeImaEventName(type);
4725
+ const set = this.listeners.get(eventName);
4726
+ if (set) {
4727
+ set.delete(listener);
4728
+ if (set.size === 0) {
4729
+ this.listeners.delete(eventName);
4730
+ }
4731
+ }
4732
+ }
4733
+ dispatch(name, payload) {
4734
+ const eventName = normalizeImaEventName(name);
4735
+ const set = this.listeners.get(eventName);
4736
+ if (!set || set.size === 0) return;
4737
+ const event = this.createImaEvent(eventName, payload);
4738
+ for (const listener of Array.from(set)) {
4739
+ try {
4740
+ listener(event);
4741
+ } catch {
4742
+ }
4743
+ }
4744
+ }
4745
+ destroy() {
4746
+ this.listeners.clear();
4747
+ }
4748
+ createImaEvent(eventName, payload) {
4749
+ const rawAd = typeof payload?.getAd === "function" ? payload.getAd() : payload?.ad !== void 0 ? payload.ad : payload && !payload.error && !payload.class && !payload.error_class && !payload.message && (payload.creativeId !== void 0 || payload.adId !== void 0 || payload.title !== void 0 || payload.duration !== void 0) ? payload : void 0;
4750
+ const adObj = rawAd ? {
4751
+ getAdId: () => typeof rawAd.getAdId === "function" ? rawAd.getAdId() : rawAd.adId ?? rawAd.id ?? "",
4752
+ getCreativeId: () => typeof rawAd.getCreativeId === "function" ? rawAd.getCreativeId() : rawAd.creativeId ?? "",
4753
+ getTitle: () => typeof rawAd.getTitle === "function" ? rawAd.getTitle() : rawAd.title ?? "",
4754
+ getAdvertiserName: () => typeof rawAd.getAdvertiserName === "function" ? rawAd.getAdvertiserName() : rawAd.advertiser ?? rawAd.advertiserName ?? "",
4755
+ getDuration: () => typeof rawAd.getDuration === "function" ? rawAd.getDuration() : rawAd.duration ?? 0,
4756
+ adId: typeof rawAd.getAdId === "function" ? rawAd.getAdId() : rawAd.adId ?? rawAd.id ?? "",
4757
+ creativeId: typeof rawAd.getCreativeId === "function" ? rawAd.getCreativeId() : rawAd.creativeId ?? "",
4758
+ title: typeof rawAd.getTitle === "function" ? rawAd.getTitle() : rawAd.title ?? "",
4759
+ advertiserName: typeof rawAd.getAdvertiserName === "function" ? rawAd.getAdvertiserName() : rawAd.advertiser ?? rawAd.advertiserName ?? "",
4760
+ duration: typeof rawAd.getDuration === "function" ? rawAd.getDuration() : rawAd.duration ?? 0
4761
+ } : null;
4762
+ const rawError = typeof payload?.getError === "function" ? payload.getError() : payload?.error !== void 0 ? payload.error : payload && (payload.class !== void 0 || payload.error_class !== void 0 || payload.vastCode !== void 0 || payload.vast_error_code !== void 0 || payload.code !== void 0 || payload.error_code !== void 0 || payload.message !== void 0) ? payload : void 0;
4763
+ const errorObj = rawError ? {
4764
+ getMessage: () => typeof rawError.getMessage === "function" ? rawError.getMessage() : rawError.message ?? String(rawError),
4765
+ getErrorCode: () => typeof rawError.getErrorCode === "function" ? rawError.getErrorCode() : rawError.code ?? rawError.errorCode ?? rawError.error_code,
4766
+ getVastErrorCode: () => typeof rawError.getVastErrorCode === "function" ? rawError.getVastErrorCode() : rawError.vastCode ?? rawError.vastErrorCode ?? rawError.vast_error_code,
4767
+ getType: () => typeof rawError.getType === "function" ? rawError.getType() : rawError.class ?? rawError.error_class ?? rawError.type ?? rawError.errorType ?? "other",
4768
+ message: typeof rawError.getMessage === "function" ? rawError.getMessage() : rawError.message ?? String(rawError),
4769
+ code: typeof rawError.getErrorCode === "function" ? rawError.getErrorCode() : rawError.code ?? rawError.errorCode ?? rawError.error_code,
4770
+ vastCode: typeof rawError.getVastErrorCode === "function" ? rawError.getVastErrorCode() : rawError.vastCode ?? rawError.vastErrorCode ?? rawError.vast_error_code,
4771
+ type: typeof rawError.getType === "function" ? rawError.getType() : rawError.class ?? rawError.error_class ?? rawError.type ?? rawError.errorType ?? "other"
4772
+ } : null;
4773
+ return {
4774
+ type: eventName,
4775
+ getAd: () => adObj,
4776
+ getError: () => errorObj,
4777
+ ad: adObj,
4778
+ error: errorObj
4779
+ };
4780
+ }
4781
+ };
4782
+
4783
+ // src/index.ts
4784
+ function getAdsGlobal(alias = DEFAULT_ALIAS) {
4785
+ if (typeof window === "undefined") {
4786
+ return { q: [] };
4787
+ }
4788
+ const win = window;
4789
+ win[alias] = win[alias] || { q: [] };
4790
+ const sdk = win[alias];
4791
+ if (!sdk.attachVideoPlayer) {
4792
+ sdk.attachVideoPlayer = (target, options) => {
4793
+ const inst = win._bidsparkPrebidAnalytics;
4794
+ return inst?.attachVideoPlayer ? inst.attachVideoPlayer(target, options) : () => {
4795
+ };
4796
+ };
4797
+ }
4798
+ if (!sdk.attachImaAdsManager) {
4799
+ sdk.attachImaAdsManager = (adsManager, options) => {
4800
+ const inst = win._bidsparkPrebidAnalytics;
4801
+ return inst?.attachImaAdsManager ? inst.attachImaAdsManager(adsManager, options) : () => {
4802
+ };
4803
+ };
4804
+ }
4805
+ if (!sdk.recordImpression) {
4806
+ sdk.recordImpression = (slotId, options) => {
4807
+ const inst = win._bidsparkPrebidAnalytics;
4808
+ return inst?.recordImpression ? inst.recordImpression(slotId, options) : false;
4809
+ };
4810
+ }
4811
+ return sdk;
4812
+ }
4813
+ // Annotate the CommonJS export names for ESM import in node:
4814
+ 0 && (module.exports = {
4815
+ BidsparkPrebidAnalytics,
4816
+ CACHED_BID_TTL_MS,
4817
+ DEFAULT_ALIAS,
4818
+ ImaAdsManagerStub,
4819
+ LogLevel,
4820
+ MAX_USAGE_BATCH_SIZE,
4821
+ PrebidEventDeduper,
4822
+ SAFE_CONTENT_TYPE,
4823
+ USAGE_FLUSH_INTERVAL_MS,
4824
+ UsageProto,
4825
+ UsageRecorder,
4826
+ attachImaAdsManager,
4827
+ attachVideoPlayer,
4828
+ clearStoredSession,
4829
+ clearStoredUserId,
4830
+ generateUUID,
4831
+ getAdsGlobal,
4832
+ getOrCreateSessionId,
4833
+ getOrCreateUserId,
4834
+ getPrebidEventKey,
4835
+ idToBytes,
4836
+ idToString,
4837
+ isSessionActive,
4838
+ isTrustedEndpoint,
4839
+ isVisitorSampled,
4840
+ normalizeLogLevel,
4841
+ normalizeSampleRate,
4842
+ onSessionResume,
4843
+ registerPrebidAnalytics,
4844
+ resetTcfListener,
4845
+ sendEvents,
4846
+ sessionStarted
4847
+ });