@bidkernel/analytics 0.21.0 → 0.23.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.
@@ -1 +1 @@
1
- "use strict";var bidkernelPrebidAnalyticsBundle=(()=>{var _=(i,e)=>()=>(i&&(e=i(i=0)),e);var yt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);function mt(){if(typeof window<"u"){let i=window;return i.__bidkernelLogListeners||(i.__bidkernelLogListeners=new Set),i.__bidkernelLogListeners}return gt}function It(i){if((i<0||!Number.isFinite(i))&&(i=0),i<1e3)return`${i.toFixed(2)}ms`;let e=i/1e3;if(e<60)return`${e.toFixed(2)}s`;let t=Math.floor(e/60);return t<60?`${t}m ${(e%60).toFixed(2)}s`:`${Math.floor(t/60)}h ${t%60}m ${(e%60).toFixed(2)}s`}function Y(i){if(typeof i=="string"){let e=i.toUpperCase();if(e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR")return e}return w.INFO}function re(i){return new ie(i)}var w,Ae,P,bt,gt,ie,Re=_(()=>{"use strict";w={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},Ae={[w.DEBUG]:10,[w.INFO]:20,[w.WARN]:30,[w.ERROR]:40},P={badge:"color: #2dd4bf; font-weight: bold",badgeWarn:"background: #f59e0b; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",badgeError:"background: #ef4444; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",dim:"color: #6b7280",event:"color: #38bdf8; font-weight: bold",eventWarn:"color: #f59e0b; font-weight: bold",eventError:"color: #ef4444; font-weight: bold",reset:"color: inherit"},bt=0,gt=new Set;ie=class i{_prefix;_level;_loadedAt;_now;_console;_customFormatTime;_listeners=new Set;constructor(e={}){this._prefix=e.prefix??"[bidkernel]",this._level=Y(e.logLevel??w.INFO),this._now=e.now,this._console=e.console,this._customFormatTime=e.formatTime,e.onLog&&this._listeners.add(e.onLog),this._loadedAt=e.loadedAt??(this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())}get prefix(){return this._prefix}set prefix(e){this._prefix=e}get logLevel(){return this._level}set logLevel(e){this._level=Y(e)}getLevel(){return this._level}setLevel(e){this._level=Y(e)}getPrefix(){return this._prefix}setPrefix(e){this._prefix=e}resetTiming(e){this._loadedAt=e??(this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())}getLoadedAt(){return this._loadedAt}addListener(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeListener(e){this._listeners.delete(e)}isEnabled(e){let t=Y(e);return(Ae[t]??20)>=(Ae[this._level]??20)}formatTime(e){return this._customFormatTime?this._customFormatTime(e):It(e)}_getConsole(){if(this._console)return this._console;if(typeof console<"u")return console}_getElapsed(){let e=this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();return Math.max(0,e-this._loadedAt)}_dispatchRecord(e){for(let n of this._listeners)try{n(e)}catch{}let t=mt();for(let n of t)if(!this._listeners.has(n))try{n(e)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent("__bidkernel_log__",{detail:e}))}catch{}}log(e,t,...n){let r=Y(e);if(!this.isEnabled(r))return;let o=this._getElapsed(),s=this.formatTime(o),d=Date.now(),l={id:`bk_log_${d}_${++bt}`,timestamp:d,elapsedMs:o,level:r,prefix:this._prefix,message:t,args:n,data:n.length===1?n[0]:n.length>1?n:void 0};this._dispatchRecord(l);let c=this._getConsole();if(!c)return;let b=P.badge,h=P.event;r===w.WARN?(b=P.badgeWarn,h=P.eventWarn):r===w.ERROR&&(b=P.badgeError,h=P.eventError);let m=`%c${this._prefix}%c ${s} %c${t}%c`,A=[b,P.dim,h,P.reset],p=[m,...A];switch(n.length>0&&p.push(...n),r){case w.DEBUG:typeof c.log=="function"?c.log(...p):typeof c.debug=="function"&&c.debug(...p);break;case w.INFO:typeof c.info=="function"?c.info(...p):typeof c.log=="function"&&c.log(...p);break;case w.WARN:typeof c.warn=="function"?c.warn(...p):typeof c.log=="function"&&c.log(...p);break;case w.ERROR:typeof c.error=="function"?c.error(...p):typeof c.log=="function"&&c.log(...p);break;default:typeof c.log=="function"&&c.log(...p);break}}debug(e,...t){this.log(w.DEBUG,e,...t)}info(e,...t){this.log(w.INFO,e,...t)}warn(e,...t){this.log(w.WARN,e,...t)}error(e,...t){this.log(w.ERROR,e,...t)}logEvent(e){e&&(e.data!==void 0?this.log(e.level,e.eventName,e.data):this.log(e.level,e.eventName))}child(e,t={}){let n=this._prefix;if(e){let r=e.startsWith("[")&&e.endsWith("]")?e:`[${e}]`;n=`${this._prefix}${r}`}return new i({prefix:n,logLevel:t.logLevel??this._level,loadedAt:t.loadedAt??this._loadedAt,now:t.now??this._now,console:t.console??this._console,formatTime:t.formatTime??this._customFormatTime,...t})}withPrefix(e){return new i({prefix:e,logLevel:this._level,loadedAt:this._loadedAt,now:this._now,console:this._console,formatTime:this._customFormatTime})}}});function Be(){let i=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(i|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function Z(i,e,t){for(let o=0;o<28;o=o+7){let s=i>>>o,d=!(!(s>>>7)&&e==0),a=(d?s|128:s)&255;if(t.push(a),!d)return}let n=i>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?n|128:n)&255),!!r){for(let o=3;o<31;o=o+7){let s=e>>>o,d=!!(s>>>7),a=(d?s|128:s)&255;if(t.push(a),!d)return}t.push(e>>>31&1)}}function oe(i){let e=i[0]==="-";e&&(i=i.slice(1));let t=1e6,n=0,r=0;function o(s,d){let a=Number(i.slice(s,d));r*=t,n=n*t+a,n>=Q&&(r=r+(n/Q|0),n=n%Q)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?Se(n,r):de(n,r)}function Ce(i,e){let t=de(i,e),n=t.hi&2147483648;n&&(t=Se(t.lo,t.hi));let r=se(t.lo,t.hi);return n?"-"+r:r}function se(i,e){if({lo:i,hi:e}=vt(i,e),e<=2097151)return String(Q*e+i);let t=i&16777215,n=(i>>>24|e<<8)&16777215,r=e>>16&65535,o=t+n*6777216+r*6710656,s=n+r*8147497,d=r*2,a=1e7;return o>=a&&(s+=Math.floor(o/a),o%=a),s>=a&&(d+=Math.floor(s/a),s%=a),d.toString()+_e(s)+_e(o)}function vt(i,e){return{lo:i>>>0,hi:e>>>0}}function de(i,e){return{lo:i|0,hi:e|0}}function Se(i,e){return e=~e,i?i=~i+1:e+=1,de(i,e)}function ae(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function Le(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var Q,_e,ce=_(()=>{"use strict";Q=4294967296;_e=i=>{let e=String(i);return"0000000".slice(e.length)+e}});function Tt(){let i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),r=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let d=typeof s=="bigint"?s:BigInt(s);if(d>n||d<t)throw new Error(`invalid int64: ${s}`);return d},uParse(s){let d=typeof s=="bigint"?s:BigInt(s);if(d>o||d<r)throw new Error(`invalid uint64: ${s}`);return d},enc(s){return i.setBigInt64(0,this.parse(s),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(s){return i.setBigInt64(0,this.uParse(s),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(s,d){return i.setInt32(0,s,!0),i.setInt32(4,d,!0),i.getBigInt64(0,!0)},uDec(s,d){return i.setInt32(0,s,!0),i.setInt32(4,d,!0),i.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(t){return typeof t!="string"&&(t=t.toString()),xe(t),t},uParse(t){return typeof t!="string"&&(t=t.toString()),ke(t),t},enc(t){return typeof t!="string"&&(t=t.toString()),xe(t),oe(t)},uEnc(t){return typeof t!="string"&&(t=t.toString()),ke(t),oe(t)},dec(t,n){return Ce(t,n)},uDec(t,n){return se(t,n)}}}function xe(i){if(!/^-?[0-9]+$/.test(i))throw new Error("invalid int64: "+i)}function ke(i){if(!/^[0-9]+$/.test(i))throw new Error("invalid uint64: "+i)}var O,De=_(()=>{"use strict";ce();O=Tt()});function ue(){if(globalThis[le]==null){let i=new globalThis.TextEncoder,e=new globalThis.TextDecoder;globalThis[le]={encodeUtf8(t){return i.encode(t)},decodeUtf8(t){return e.decode(t)},checkUtf8(t){try{return encodeURIComponent(t),!0}catch{return!1}}}}return globalThis[le]}var le,fe=_(()=>{"use strict";le=Symbol.for("@bufbuild/protobuf/text-encoding")});function he(i){if(typeof i=="string")i=Number(i);else if(typeof i!="number")throw new Error("invalid int32: "+typeof i);if(!Number.isInteger(i)||i>Rt||i<_t)throw new Error("invalid int32: "+i)}function Oe(i){if(typeof i=="string")i=Number(i);else if(typeof i!="number")throw new Error("invalid uint32: "+typeof i);if(!Number.isInteger(i)||i>At||i<0)throw new Error("invalid uint32: "+i)}function Bt(i){if(typeof i=="string"){let e=i;if(i=Number(i),Number.isNaN(i)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof i!="number")throw new Error("invalid float32: "+typeof i);if(Number.isFinite(i)&&(i>Et||i<wt))throw new Error("invalid float32: "+i)}var V,Et,wt,At,Rt,_t,F,B,Me=_(()=>{"use strict";ce();De();fe();(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(V||(V={}));Et=34028234663852886e22,wt=-34028234663852886e22,At=4294967295,Rt=2147483647,_t=-2147483648,F=class{constructor(e=ue().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),n=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],n),n+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Oe(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return he(e),ae(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Bt(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Oe(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){he(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return he(e),e=(e<<1^e>>31)>>>0,ae(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=O.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=O.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=O.enc(e);return Z(t.lo,t.hi,this.buf),this}sint64(e){let t=O.enc(e),n=t.hi>>31,r=t.lo<<1^n,o=(t.hi<<1|t.lo>>>31)^n;return Z(r,o,this.buf),this}uint64(e){let t=O.uEnc(e);return Z(t.lo,t.hi,this.buf),this}},B=class{constructor(e,t=ue().decodeUtf8){this.decodeUtf8=t,this.varint64=Be,this.uint32=Le,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case V.Varint:for(;this.buf[this.pos++]&128;);break;case V.Bit64:this.pos+=4;case V.Bit32:this.pos+=4;break;case V.LengthDelimited:let r=this.uint32();this.pos+=r;break;case V.StartGroup:for(;;){let[o,s]=this.tag();if(s===V.EndGroup){if(t!==void 0&&o!==t)throw new Error("invalid end group tag");break}this.skip(s,o)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return O.dec(...this.varint64())}uint64(){return O.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,O.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return O.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return O.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.decodeUtf8(this.bytes())}}});var Ue=_(()=>{"use strict"});var Ne=_(()=>{"use strict"});var Pe=_(()=>{"use strict"});var Ve=_(()=>{"use strict";Me();Ue();fe();Ne();Pe()});function Ct(){return{propertyId:new Uint8Array(0),pageviewId:new Uint8Array(0),sessionId:new Uint8Array(0),pageUrl:"",country:"",region:"",deviceType:"",userId:new Uint8Array(0),domain:"",events:[],browser:"",deviceManufacturer:"",deviceModel:"",city:"",postalCode:""}}function St(){return{timestampMs:0,type:0,eventName:"",auctionId:new Uint8Array(0),transactionId:new Uint8Array(0),adUnitCode:"",bid:void 0,namespace:"",eventId:new Uint8Array(0),metadata:{},viewableDurationMs:void 0,bidderOutcomes:[]}}function Lt(){return{key:"",value:""}}function xt(){return{adUnitCode:"",outcome:0,bid:void 0,refreshIndex:0}}function kt(){return{bidder:"",cpm:0,currency:"",width:0,height:0,dealId:"",mediaType:"",latencyMs:0,advertiserDomain:"",creativeId:""}}var I,U,pe,Fe,$e,We,J,ye=_(()=>{"use strict";Ve();I={TRACE_EVENT_TYPE_UNSPECIFIED:0,AUCTION_START:1,AUCTION_END:2,BID_WIN:4,IMPRESSION:5,VIEWABLE:6,TIME_IN_VIEW:7,ERROR:9,SLOT_DEFINED:10,SLOT_DESTROYED:11,CLICK:12,AD_RENDER_FAILED:13,UNRECOGNIZED:-1},U={BIDDER_OUTCOME_UNSPECIFIED:0,BIDDER_OUTCOME_BID:1,BIDDER_OUTCOME_NO_BID:2,BIDDER_OUTCOME_TIMEOUT:3,BIDDER_OUTCOME_ERROR:4,BIDDER_OUTCOME_NO_RESPONSE:5,UNRECOGNIZED:-1};pe={encode(i,e=new F){if(i.propertyId!==void 0&&i.propertyId.length!==0&&e.uint32(10).bytes(i.propertyId),i.pageviewId!==void 0&&i.pageviewId.length!==0&&e.uint32(18).bytes(i.pageviewId),i.sessionId!==void 0&&i.sessionId.length!==0&&e.uint32(26).bytes(i.sessionId),i.pageUrl!==void 0&&i.pageUrl!==""&&e.uint32(34).string(i.pageUrl),i.country!==void 0&&i.country!==""&&e.uint32(42).string(i.country),i.region!==void 0&&i.region!==""&&e.uint32(50).string(i.region),i.deviceType!==void 0&&i.deviceType!==""&&e.uint32(58).string(i.deviceType),i.userId!==void 0&&i.userId.length!==0&&e.uint32(66).bytes(i.userId),i.domain!==void 0&&i.domain!==""&&e.uint32(74).string(i.domain),i.events!==void 0&&i.events.length!==0)for(let t of i.events)Fe.encode(t,e.uint32(82).fork()).join();return i.browser!==void 0&&i.browser!==""&&e.uint32(90).string(i.browser),i.deviceManufacturer!==void 0&&i.deviceManufacturer!==""&&e.uint32(98).string(i.deviceManufacturer),i.deviceModel!==void 0&&i.deviceModel!==""&&e.uint32(106).string(i.deviceModel),i.city!==void 0&&i.city!==""&&e.uint32(114).string(i.city),i.postalCode!==void 0&&i.postalCode!==""&&e.uint32(122).string(i.postalCode),e},decode(i,e){let t=i instanceof B?i:new B(i),n=e===void 0?t.len:t.pos+e,r=Ct();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.propertyId=t.bytes();continue}case 2:{if(o!==18)break;r.pageviewId=t.bytes();continue}case 3:{if(o!==26)break;r.sessionId=t.bytes();continue}case 4:{if(o!==34)break;r.pageUrl=t.string();continue}case 5:{if(o!==42)break;r.country=t.string();continue}case 6:{if(o!==50)break;r.region=t.string();continue}case 7:{if(o!==58)break;r.deviceType=t.string();continue}case 8:{if(o!==66)break;r.userId=t.bytes();continue}case 9:{if(o!==74)break;r.domain=t.string();continue}case 10:{if(o!==82)break;let s=Fe.decode(t,t.uint32());s!==void 0&&r.events.push(s);continue}case 11:{if(o!==90)break;r.browser=t.string();continue}case 12:{if(o!==98)break;r.deviceManufacturer=t.string();continue}case 13:{if(o!==106)break;r.deviceModel=t.string();continue}case 14:{if(o!==114)break;r.city=t.string();continue}case 15:{if(o!==122)break;r.postalCode=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};Fe={encode(i,e=new F){if(i.timestampMs!==void 0&&i.timestampMs!==0&&e.uint32(9).double(i.timestampMs),i.type!==void 0&&i.type!==0&&e.uint32(16).int32(i.type),i.eventName!==void 0&&i.eventName!==""&&e.uint32(26).string(i.eventName),i.auctionId!==void 0&&i.auctionId.length!==0&&e.uint32(34).bytes(i.auctionId),i.transactionId!==void 0&&i.transactionId.length!==0&&e.uint32(42).bytes(i.transactionId),i.adUnitCode!==void 0&&i.adUnitCode!==""&&e.uint32(50).string(i.adUnitCode),i.bid!==void 0&&J.encode(i.bid,e.uint32(58).fork()).join(),i.namespace!==void 0&&i.namespace!==""&&e.uint32(66).string(i.namespace),i.eventId!==void 0&&i.eventId.length!==0&&e.uint32(74).bytes(i.eventId),globalThis.Object.entries(i.metadata||{}).forEach(([t,n])=>{$e.encode({key:t,value:n},e.uint32(82).fork()).join()}),i.viewableDurationMs!==void 0&&e.uint32(89).double(i.viewableDurationMs),i.bidderOutcomes!==void 0&&i.bidderOutcomes.length!==0)for(let t of i.bidderOutcomes)We.encode(t,e.uint32(98).fork()).join();return e},decode(i,e){let t=i instanceof B?i:new B(i),n=e===void 0?t.len:t.pos+e,r=St();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==9)break;r.timestampMs=t.double();continue}case 2:{if(o!==16)break;r.type=t.int32();continue}case 3:{if(o!==26)break;r.eventName=t.string();continue}case 4:{if(o!==34)break;r.auctionId=t.bytes();continue}case 5:{if(o!==42)break;r.transactionId=t.bytes();continue}case 6:{if(o!==50)break;r.adUnitCode=t.string();continue}case 7:{if(o!==58)break;r.bid=J.decode(t,t.uint32());continue}case 8:{if(o!==66)break;r.namespace=t.string();continue}case 9:{if(o!==74)break;r.eventId=t.bytes();continue}case 10:{if(o!==82)break;let s=$e.decode(t,t.uint32());s.value!==void 0&&(r.metadata[s.key]=s.value);continue}case 11:{if(o!==89)break;r.viewableDurationMs=t.double();continue}case 12:{if(o!==98)break;let s=We.decode(t,t.uint32());s!==void 0&&r.bidderOutcomes.push(s);continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};$e={encode(i,e=new F){return i.key!==""&&e.uint32(10).string(i.key),i.value!==""&&e.uint32(18).string(i.value),e},decode(i,e){let t=i instanceof B?i:new B(i),n=e===void 0?t.len:t.pos+e,r=Lt();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.key=t.string();continue}case 2:{if(o!==18)break;r.value=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};We={encode(i,e=new F){return i.adUnitCode!==void 0&&i.adUnitCode!==""&&e.uint32(18).string(i.adUnitCode),i.outcome!==void 0&&i.outcome!==0&&e.uint32(32).int32(i.outcome),i.bid!==void 0&&J.encode(i.bid,e.uint32(50).fork()).join(),i.refreshIndex!==void 0&&i.refreshIndex!==0&&e.uint32(56).int32(i.refreshIndex),e},decode(i,e){let t=i instanceof B?i:new B(i),n=e===void 0?t.len:t.pos+e,r=xt();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 2:{if(o!==18)break;r.adUnitCode=t.string();continue}case 4:{if(o!==32)break;r.outcome=t.int32();continue}case 6:{if(o!==50)break;r.bid=J.decode(t,t.uint32());continue}case 7:{if(o!==56)break;r.refreshIndex=t.int32();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};J={encode(i,e=new F){return i.bidder!==void 0&&i.bidder!==""&&e.uint32(10).string(i.bidder),i.cpm!==void 0&&i.cpm!==0&&e.uint32(17).double(i.cpm),i.currency!==void 0&&i.currency!==""&&e.uint32(26).string(i.currency),i.width!==void 0&&i.width!==0&&e.uint32(32).int32(i.width),i.height!==void 0&&i.height!==0&&e.uint32(40).int32(i.height),i.dealId!==void 0&&i.dealId!==""&&e.uint32(50).string(i.dealId),i.mediaType!==void 0&&i.mediaType!==""&&e.uint32(58).string(i.mediaType),i.latencyMs!==void 0&&i.latencyMs!==0&&e.uint32(65).double(i.latencyMs),i.advertiserDomain!==void 0&&i.advertiserDomain!==""&&e.uint32(74).string(i.advertiserDomain),i.creativeId!==void 0&&i.creativeId!==""&&e.uint32(82).string(i.creativeId),e},decode(i,e){let t=i instanceof B?i:new B(i),n=e===void 0?t.len:t.pos+e,r=kt();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.bidder=t.string();continue}case 2:{if(o!==17)break;r.cpm=t.double();continue}case 3:{if(o!==26)break;r.currency=t.string();continue}case 4:{if(o!==32)break;r.width=t.int32();continue}case 5:{if(o!==40)break;r.height=t.int32();continue}case 6:{if(o!==50)break;r.dealId=t.string();continue}case 7:{if(o!==58)break;r.mediaType=t.string();continue}case 8:{if(o!==65)break;r.latencyMs=t.double();continue}case 9:{if(o!==74)break;r.advertiserDomain=t.string();continue}case 10:{if(o!==82)break;r.creativeId=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}}});function $(i){if(!i)return new Uint8Array(0);if(Dt.test(i)){let t=i.replace(/-/g,""),n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}if(qe)return qe.encode(i);let e=new Uint8Array(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t)&255;return e}var Dt,qe,Mn,He=_(()=>{"use strict";Dt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,qe=typeof TextEncoder<"u"?new TextEncoder:null,Mn=typeof TextDecoder<"u"?new TextDecoder:null});function H(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function Yt(i){let e="";for(let n=0;n<i.length;n+=8192)e+=String.fromCharCode(...i.subarray(n,n+8192));return btoa(e)}function zt(i){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function Xt(i){if(!i)return!1;let e;try{e=new URL(i)}catch{return!1}return e.username||e.password?!1:e.protocol==="https:"?!0:e.protocol==="http:"?e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]":!1}function Qt(i){let e={},t=0;for(let n of Object.keys(i)){if(t>=Nt)break;let r=i[n];if(r==null)continue;let o=String(r);e[n]=o.length>Ke?`${o.slice(0,Ke)}...[truncated]`:o,t++}return e}function Zt(i){let e=i.slice(ee.length).split("_");return e.length===2&&/^\d+$/.test(e[0])}function Jt(i,e){if(!i||!e)return!1;try{return new URL(i).origin===new URL(e).origin}catch{return!1}}function Je(i){try{typeof localStorage<"u"&&(localStorage.setItem(Qe,i.toString()),q=i)}catch{}}function et(i=Date.now()){return N>0&&i-N<=Ze}function te(){let i=Date.now(),e=!!D&&!et(i);if(N=i,e){D=null;for(let t of nn)t();return}!K||!D||q===0||i-q<en||Je(i)}function rn(){return!D||K&&q===0}function on(){if(Xe||typeof window>"u")return;Xe=!0;let i=()=>te();for(let e of tn)window.addEventListener(e,i,{passive:!0,capture:!0});typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&te()})}function ge(){let i=Date.now(),e=!!D&&et(i);try{if(K&&typeof localStorage<"u"){let t=localStorage.getItem(ze),n=localStorage.getItem(Qe),r=n&&parseInt(n,10)||0;if(t&&r&&i-r<=Ze)return(D!==t||N<r)&&(D=t,N=Math.max(N,r)),q===0&&(q=r),t;let o=e?D:H();return e||(N=i),localStorage.setItem(ze,o),Je(N),D=o,o}}catch{}return e||(D=H(),N=i),D}function f(i){return String(i??"").replace(/%/g,"%25").replace(/:/g,"%3A")}function sn(i,e){switch(i){case"auctionInit":return`auctionInit:${f(e?.auctionId)}`;case"auctionEnd":return`auctionEnd:${f(e?.auctionId)}`;case"bidRequested":{let t=Array.isArray(e?.bids)?e.bids.map(n=>f(n?.bidId||n?.transactionId||n?.adUnitCode)).join(","):"";return`bidRequested:${f(e?.auctionId)}:${f(e?.bidderCode||e?.bidder)}:${t}`}case"bidResponse":{let t=e||{},n=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidResponse:${f(t.auctionId)}:${f(t.adUnitCode)}:${f(t.bidderCode||t.bidder)}:${f(n)}:${f(r)}`}case"bidTimeout":return"bidTimeout:"+(Array.isArray(e)?e:e?[e]:[]).map(n=>`${f(n?.auctionId)}:${f(n?.bidderCode||n?.bidder)}:${f(n?.bidId||n?.transactionId||n?.adUnitCode)}`).join(",");case"bidWon":{let t=e||{},n=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidWon:${f(t.auctionId)}:${f(t.adUnitCode)}:${f(t.bidderCode||t.bidder)}:${f(n)}:${f(r)}`}case"noBid":return`noBid:${f(e?.auctionId)}:${f(e?.adUnitCode)}:${f(e?.bidderCode||e?.bidder)}:${f(e?.bidId||e?.transactionId)}`;case"adRenderFailed":{let t=e?.bid||{};return`adRenderFailed:${f(t.auctionId||e?.auctionId)}:${f(t.adUnitCode||e?.adUnitCode)}:${f(t.bidderCode||t.bidder||e?.bidderCode||e?.bidder)}:${f(e?.reason)}:${f(e?.message)}`}case"adRenderSucceeded":{let t=e?.bid||e||{},n=t.creativeId||t.adId||e?.adId||"",r=t.originalCpm??t.cpm??"";return`adRenderSucceeded:${f(t.auctionId||e?.auctionId)}:${f(t.adUnitCode||e?.adUnitCode)}:${f(t.bidderCode||t.bidder)}:${f(n)}:${f(r)}`}case"setTargeting":return`setTargeting:${Object.keys(e||{}).sort().map(f).join(",")}`;case"auctionDebug":return`auctionDebug:${f(e?.type)}:${f(String(e?.arguments?.[0]??"").slice(0,50))}`;default:return""}}function W(i){if(Number.isFinite(i?.width)&&Number.isFinite(i?.height))return{width:i.width,height:i.height};if(typeof i?.size=="string"){let e=i.size.match(/^(\d+)x(\d+)$/);if(e)return{width:Number(e[1]),height:Number(e[2])}}return{width:Number.isFinite(i?.width)?i.width:0,height:Number.isFinite(i?.height)?i.height:0}}function G(i,e=!0){if(!i)return null;if(Array.isArray(i)){let t=i.find(n=>n?.provider==="bidkernel")??(e?i.find(n=>n&&typeof n=="object"&&n.provider===void 0):void 0);return t?G(t,e):null}if(typeof i=="object"){if(i.options&&typeof i.options=="object")return i.options;if(i.config&&typeof i.config=="object")return i.config;if(i.propertyId||i.endpoint)return i}return null}function dn(i){if(!i)return null;if(i._bidkernelAnalyticsConfig){let e=G(i._bidkernelAnalyticsConfig);if(e)return e}if(i.bidkernelPrebidAnalytics){let e=i.bidkernelPrebidAnalytics;if(e.options){let t=G(e.options);if(t)return t}if(e.config){let t=G(e.config);if(t)return t}if(e.propertyId)return G(e)}return null}function ve(i="pbjs",e){let t=typeof window<"u"?window:{};t[i]=t[i]||{};let n=t[i],r=s=>{let d=t._bidkernelPrebidAnalytics,a=d?.getEndpoint?.()||"",l={pbjsGlobalName:i,...e,...s};if(a&&!Jt(l.endpoint||"",a)&&(me.warn(`Ignoring analytics endpoint change to ${l.endpoint||"(empty)"}: this page is pinned to ${a}. Reload to change the ingest endpoint.`),l.endpoint=a),d)try{d.disable()}catch(b){me.warn("Failed to disable previous analytics instance:",b)}let c=new C(l);return c.enable(),t._bidkernelPrebidAnalytics=c,c},o=()=>{try{n.adapterManager&&typeof n.adapterManager.registerAnalyticsAdapter=="function"&&n.adapterManager.registerAnalyticsAdapter({adapter:{enableAnalytics:d=>{let a=G(d,!Array.isArray(d));a&&r(a)},disableAnalytics:()=>{t._bidkernelPrebidAnalytics&&t._bidkernelPrebidAnalytics.disable()}},code:"bidkernel"});let s=dn(t);s&&(s.propertyId||e?.propertyId)&&r(s)}catch(s){me.warn("Failed to register standard Prebid analytics adapter:",s)}};n.adapterManager&&typeof n.adapterManager.registerAnalyticsAdapter=="function"?o():(n.que=n.que||[],n.que.push(o))}var Ge,Ot,z,Mt,Ut,be,Ke,Nt,Ye,ee,Pt,Vt,Ft,$t,Wt,jt,j,qt,Ht,Gt,Kt,ze,Qe,Ze,D,N,K,en,q,tn,Xe,nn,Ie,C,me,Te=_(()=>{"use strict";Re();ye();He();Ge=1e4,Ot=50,z=200,Mt=300*1e3,Ut=10,be=32*1024,Ke=1024,Nt=16,Ye="text/plain",ee="_bidkernel_pending_",Pt=20,Vt=7200*1e3,Ft=1e4,$t={auctionStart:I.AUCTION_START,auctionEnd:I.AUCTION_END,bidWin:I.BID_WIN,adRenderFailed:I.AD_RENDER_FAILED,click:I.CLICK,impression:I.IMPRESSION,timeInView:I.TIME_IN_VIEW,viewable:I.VIEWABLE},Wt=3e3,jt=new Set([I.IMPRESSION,I.BID_WIN,I.CLICK]),j=1800*1e3,qt=200,Ht=1e3,Gt=50,Kt=1e3,ze="_bidkernel_session",Qe="_bidkernel_session_ts",Ze=1800*1e3,D=null,N=0,K=!0;en=60*1e3,q=0,tn=["pointerdown","pointermove","keydown","scroll","wheel","touchstart"],Xe=!1,nn=new Set;Ie=class{seenObjects=new WeakMap;seenKeys=new Set;isDuplicate(e,t){if(!t)return!1;if(typeof t=="object"){let r=this.seenObjects.get(t);if(r){if(r.has(e))return!0;r.add(e)}else this.seenObjects.set(t,new Set([e]))}let n=sn(e,t);if(n){if(this.seenKeys.has(n))return!0;if(this.seenKeys.size>=1e3){let r=this.seenKeys.values().next().value;r!==void 0&&this.seenKeys.delete(r)}this.seenKeys.add(n)}return!1}};C=class i{static activeInstances=new Set;static getActiveInstances(){return i.activeInstances}static setStorageAllowed(e){K=e,q=0}static isStorageAllowed(){return K}config;queue=[];errorCount=0;flushTimer=null;boundFlushBeacon;boundVisibilityChange;isEnabled=!1;boundPbjsHandlers=[];pageUrl="";deduper=new Ie;consecutiveSendFailures=0;nextSendAllowedAt=0;replayedEventCount=0;revenueFlushTimer=null;persistedBatchKeys=[];persistedCleanupTimer=null;intersectionObserver=null;slotViewabilityRecords=new Map;elementToSlotId=new Map;slotRefreshIndices=new Map;slotLastAuctionIds=new Map;pendingThresholdListeners=new Map;pendingViewableListeners=new Map;slotElements=new Map;clickDetachCleanups=new Set;lastClickAt=new Map;slotEmittedImpressionKeys=new Set;cachedWinningBids=new Map;videoDetachCleanups=new Set;auctionBidderOutcomes=new Map;logger;managesSessionId;constructor(e){e.storageAllowed!==void 0&&i.setStorageAllowed(e.storageAllowed);let t=e.endpoint||"",n=!t||Xt(t)?t:"";this.config={endpoint:n,propertyId:e.propertyId||"",pageviewId:e.pageviewId||H(),sessionId:e.sessionId||"",userId:e.userId||"",deviceType:e.deviceType||"desktop",country:e.country||"",region:e.region||"",auctionEnabled:e.auctionEnabled??!0,warningsEnabled:e.warningsEnabled??!0,errorsEnabled:e.errorsEnabled??!0,viewabilityEnabled:e.viewabilityEnabled??!0,storageAllowed:e.storageAllowed??!0,logLevel:e.logLevel||"INFO",pbjsGlobalName:e.pbjsGlobalName||"pbjs",attachPbjsListeners:e.attachPbjsListeners??!0,revenueFlushDelayMs:Number.isFinite(e.revenueFlushDelayMs)&&e.revenueFlushDelayMs>=0?e.revenueFlushDelayMs:Wt},this.logger=re({prefix:"[bidkernel][prebid-analytics]",logLevel:this.config.logLevel}),te(),this.managesSessionId=!e.sessionId,this.managesSessionId&&(this.config.sessionId=ge()),t&&!n&&this.log("ERROR",`Rejected untrusted analytics endpoint ${t}: must be an absolute https:// URL without embedded credentials. Events will not be transmitted.`),this.boundFlushBeacon=()=>{this.flushAllSlotsTimeInView(),this.flushBeacon()},this.boundVisibilityChange=()=>this.handleVisibilityChange()}enable(){if(!this.isEnabled){if(this.isEnabled=!0,i.activeInstances.add(this),this.logger.setLevel(this.config.logLevel),this.config.endpoint||this.log("WARN","Endpoint is empty. Analytics events will not be transmitted."),this.config.viewabilityEnabled&&typeof IntersectionObserver<"u"){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:[.5]});for(let e of this.slotViewabilityRecords.values())e.element&&this.intersectionObserver.observe(e.element)}if(this.config.attachPbjsListeners&&this.attachPbjs(),typeof window<"u"){if(!this.pageUrl)try{let e=new URL(window.location.href);this.pageUrl=e.origin+e.pathname}catch{this.pageUrl=window.location.href}window.addEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.addEventListener("visibilitychange",this.boundVisibilityChange),on(),this.flushTimer=setInterval(()=>this.flush(),Ge),this.resendPersistedBatches()}}}attachPbjs(){if(!this.isEnabled)return!1;if(this.boundPbjsHandlers.length>0)return!0;let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.onEvent!="function")return this.log("WARN","pbjs.onEvent is not defined. Prebid analytics will not function."),!1;this.log("DEBUG","Attaching event listeners to pbjs");let n={auctionInit:this.handleAuctionInit.bind(this),auctionEnd:this.handleAuctionEnd.bind(this),bidRequested:this.handleBidRequested.bind(this),bidResponse:this.handleBidResponse.bind(this),bidTimeout:this.handleBidTimeout.bind(this),bidWon:this.handleBidWon.bind(this),noBid:this.handleNoBid.bind(this),adRenderFailed:this.handleAdRenderFailed.bind(this),adRenderSucceeded:this.handleAdRenderSucceeded.bind(this)};for(let[r,o]of Object.entries(n))t.onEvent(r,o),this.boundPbjsHandlers.push({event:r,handler:o});if(typeof t.getEvents=="function")try{let r=t.getEvents();if(Array.isArray(r)){let o=r.slice(this.replayedEventCount);if(this.replayedEventCount=r.length,o.length>0){this.log("DEBUG",`Replaying ${o.length} historical events from pbjs.getEvents()`);for(let s of o){if(!s)continue;let d=s.eventType||s.event||s.name,a=s.args!==void 0?s.args:s.data!==void 0?s.data:s,l=n[d];l&&l(a)}}}}catch(r){this.log("WARN","Failed to replay historical events from pbjs.getEvents()",r)}return!0}disable(){if(this.isEnabled){this.flushAllSlotsTimeInView(),this.isEnabled=!1,i.activeInstances.delete(this);for(let e of this.slotViewabilityRecords.values()){e.dwellTimer&&(clearTimeout(e.dwellTimer),e.dwellTimer=null,e.dwellStartedAt=null);for(let t of e.thresholdListeners)t.timer&&(clearTimeout(t.timer),t.timer=null)}this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.slotViewabilityRecords.clear(),this.elementToSlotId.clear();for(let e of this.videoDetachCleanups)try{e()}catch{}this.videoDetachCleanups.clear();for(let e of Array.from(this.clickDetachCleanups))try{e()}catch{}if(this.clickDetachCleanups.clear(),this.slotElements.clear(),this.cachedWinningBids.clear(),this.slotEmittedImpressionKeys.clear(),this.slotLastAuctionIds.clear(),this.auctionBidderOutcomes.clear(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.revenueFlushTimer&&(clearTimeout(this.revenueFlushTimer),this.revenueFlushTimer=null),this.persistedCleanupTimer&&(clearTimeout(this.persistedCleanupTimer),this.persistedCleanupTimer=null),typeof window<"u"&&(window.removeEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundVisibilityChange)),this.boundPbjsHandlers.length>0){let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.offEvent=="function")for(let{event:n,handler:r}of this.boundPbjsHandlers)t.offEvent(n,r);this.boundPbjsHandlers=[]}this.flush()}}handleVisibilityChange(){if(!(typeof document>"u")){if(document.visibilityState==="hidden"){let e=typeof performance<"u"&&performance.now?performance.now():Date.now();for(let t of this.slotViewabilityRecords.values()){t.inView&&t.lastEnteredViewAt!==null&&(t.accumulatedTimeInViewMs+=Math.max(0,e-t.lastEnteredViewAt),t.lastEnteredViewAt=null,this.checkThresholdListeners(t)),t.dwellTimer&&(clearTimeout(t.dwellTimer),t.dwellTimer=null,t.dwellStartedAt=null);for(let r of t.thresholdListeners)r.timer&&(clearTimeout(r.timer),r.timer=null);let n=Math.round(t.accumulatedTimeInViewMs);n>0&&this.enqueue(I.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:n,bid:t.bidPayload,metadata:{...t.metadata,refresh_index:String(t.refreshIndex)}})}this.flushBeacon()}else if(document.visibilityState==="visible"){let e=typeof performance<"u"&&performance.now?performance.now():Date.now();for(let t of this.slotViewabilityRecords.values())if(t.inView){if(t.lastEnteredViewAt=e,!t.viewableFired&&t.dwellTimer===null){let n=t.mediaType==="video"?2e3:1e3;t.dwellStartedAt=e,t.dwellTimer=setTimeout(()=>{this.handleDwellComplete(t)},n)}this.scheduleThresholdTimers(t)}}}}handleIntersection(e){for(let t of e){let n=this.elementToSlotId.get(t.target);if(!n){for(let a of i.activeInstances)if(a!==this&&a.elementToSlotId.has(t.target)){a.handleIntersection([t]);break}continue}let r=this.slotViewabilityRecords.get(n);if(!r)continue;let o=t.isIntersecting&&(t.intersectionRatio===void 0||t.intersectionRatio>=.5),s=typeof document>"u"||document.visibilityState==="visible",d=typeof performance<"u"&&performance.now?performance.now():Date.now();if(o){if(!r.inView&&(r.inView=!0,s)){if(r.lastEnteredViewAt=d,!r.viewableFired&&r.dwellTimer===null){let a=r.mediaType==="video"?2e3:1e3;r.dwellStartedAt=d,r.dwellTimer=setTimeout(()=>{this.handleDwellComplete(r)},a)}this.scheduleThresholdTimers(r)}}else{r.inView&&(r.lastEnteredViewAt!==null&&(r.accumulatedTimeInViewMs+=Math.max(0,d-r.lastEnteredViewAt),r.lastEnteredViewAt=null),r.inView=!1,this.checkThresholdListeners(r)),r.dwellTimer!==null&&(clearTimeout(r.dwellTimer),r.dwellTimer=null,r.dwellStartedAt=null);for(let a of r.thresholdListeners)a.timer&&(clearTimeout(a.timer),a.timer=null)}}}handleDwellComplete(e){e.dwellTimer=null,e.dwellStartedAt=null,e.inView&&(typeof document<"u"&&document.visibilityState==="hidden"||(e.viewableFired||(e.viewableFired=!0,this.enqueue(I.VIEWABLE,"viewable",{auctionId:e.auctionId,transactionId:e.transactionId,adUnitCode:e.adUnitCode,bid:e.bidPayload,metadata:{...e.metadata,refresh_index:String(e.refreshIndex)}})),this.notifyViewable(e)))}notifyViewable(e){if(e.viewableFired){for(let t of e.viewableListeners)if(t.firedForIndex!==e.refreshIndex){t.firedForIndex=e.refreshIndex;try{t.callback(e.slotId)}catch(n){this.log("ERROR","Error in viewable listener callback",n)}}}}setSlotElement(e,t){this.slotElements.set(e,t);let n=this.slotViewabilityRecords.get(e);n&&n.element!==t&&this.observeSlot(t,e,{refreshIndex:n.refreshIndex})}recordClick(e,t){if(!this.isEnabled||!e)return!1;let n=Date.now();if(n-(this.lastClickAt.get(e)||0)<Kt)return!1;this.lastClickAt.set(e,n);let r=this.getCachedBid(e);return this.enqueue(I.CLICK,"click",{auctionId:r?.auctionId||"",transactionId:r?.transactionId||"",adUnitCode:e,bid:r?.bidTrace,metadata:{...t?.metadata,refresh_index:String(this.getRefreshIndex(e))}}),!0}attachClickTracker(e,t){if(typeof window>"u")return()=>{};let n=()=>{setTimeout(()=>{let o=document.activeElement;o&&(o===e||e.contains(o))&&(this.recordClick(t,{metadata:{source:"blur"}}),window.focus())},0)};window.addEventListener("blur",n);let r=()=>{window.removeEventListener("blur",n),this.clickDetachCleanups.delete(r)};return this.clickDetachCleanups.add(r),r}onViewable(e,t){let n={callback:t,firedForIndex:-1},r=this.slotViewabilityRecords.get(e);return r?(r.viewableListeners.add(n),this.notifyViewable(r)):(this.pendingViewableListeners.has(e)||this.pendingViewableListeners.set(e,new Set),this.pendingViewableListeners.get(e).add(n)),()=>{this.slotViewabilityRecords.get(e)?.viewableListeners.delete(n),this.pendingViewableListeners.get(e)?.delete(n)}}scheduleThresholdTimers(e){if(!e.inView||typeof document<"u"&&document.visibilityState==="hidden")return;let t=this.getCurrentTimeInView(e);for(let n of e.thresholdListeners)if(!n.fired)if(t>=n.thresholdMs){n.fired=!0,n.timer&&(clearTimeout(n.timer),n.timer=null);try{n.callback(e.slotId,t)}catch(r){this.log("ERROR","Error in threshold listener callback",r)}}else{n.timer&&clearTimeout(n.timer);let r=n.thresholdMs-t;n.timer=setTimeout(()=>{if(n.timer=null,!n.fired&&e.inView&&(typeof document>"u"||document.visibilityState==="visible")){let o=this.getCurrentTimeInView(e);if(o>=n.thresholdMs){n.fired=!0;try{n.callback(e.slotId,o)}catch(s){this.log("ERROR","Error in threshold listener callback",s)}}}},r)}}checkThresholdListeners(e){let t=this.getCurrentTimeInView(e);for(let n of e.thresholdListeners)if(!n.fired&&t>=n.thresholdMs){n.fired=!0,n.timer&&(clearTimeout(n.timer),n.timer=null);try{n.callback(e.slotId,t)}catch(r){this.log("ERROR","Error in threshold listener callback",r)}}}getCurrentTimeInView(e){let t=e.accumulatedTimeInViewMs;if(e.inView&&e.lastEnteredViewAt!==null){let n=typeof performance<"u"&&performance.now?performance.now():Date.now();t+=Math.max(0,n-e.lastEnteredViewAt)}return t}flushSlotTimeInView(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;if(t.inView&&t.lastEnteredViewAt!==null){let r=typeof performance<"u"&&performance.now?performance.now():Date.now();t.accumulatedTimeInViewMs+=Math.max(0,r-t.lastEnteredViewAt),t.lastEnteredViewAt=null}let n=Math.round(t.accumulatedTimeInViewMs);n>0&&this.enqueue(I.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:n,bid:t.bidPayload,metadata:{...t.metadata,refresh_index:String(t.refreshIndex)}}),t.accumulatedTimeInViewMs=0}flushAllSlotsTimeInView(){for(let e of Array.from(this.slotViewabilityRecords.keys()))this.flushSlotTimeInView(e)}observeSlot(e,t,n){if(!this.config.viewabilityEnabled)return;let r=null;if(typeof e=="string"){if(typeof document<"u"){try{r=document.querySelector(e)||document.getElementById(e)}catch{r=document.getElementById(e)}r||(r=document.getElementById(e))}}else r=e;let o=t||n?.adUnitCode||(r?r.id:"")||H(),s=this.slotViewabilityRecords.get(o);if(s){if(n?.refreshIndex===void 0||n.refreshIndex>s.refreshIndex){this.flushSlotTimeInView(o);let a=n?.refreshIndex!==void 0?n.refreshIndex:(this.slotRefreshIndices.get(o)??s.refreshIndex)+1;this.slotRefreshIndices.set(o,a),s.dwellTimer&&(clearTimeout(s.dwellTimer),s.dwellTimer=null,s.dwellStartedAt=null);for(let c of s.thresholdListeners)c.fired=!1,c.timer&&(clearTimeout(c.timer),c.timer=null);s.viewableFired=!1,s.accumulatedTimeInViewMs=0;let l=typeof performance<"u"&&performance.now?performance.now():Date.now();if(s.lastEnteredViewAt=s.inView?l:null,s.refreshIndex=a,s.auctionId=n?.auctionId||s.auctionId,s.transactionId=n?.transactionId||s.transactionId,s.mediaType=n?.mediaType||s.mediaType||"banner",s.bidPayload=n?.bid!==void 0?n.bid:s.bidPayload,s.metadata=n?.metadata??s.metadata,s.inView&&(typeof document>"u"||document.visibilityState==="visible")){let c=s.mediaType==="video"?2e3:1e3;s.dwellStartedAt=l,s.dwellTimer=setTimeout(()=>{this.handleDwellComplete(s)},c),this.scheduleThresholdTimers(s)}}else s.auctionId=n?.auctionId||s.auctionId,s.transactionId=n?.transactionId||s.transactionId,s.mediaType=n?.mediaType||s.mediaType,n?.bid!==void 0&&(s.bidPayload=n.bid),n?.metadata!==void 0&&(s.metadata=n.metadata);n?.auctionId&&this.slotLastAuctionIds.set(o,n.auctionId),r&&(s.element&&s.element!==r&&this.intersectionObserver&&(this.intersectionObserver.unobserve(s.element),this.elementToSlotId.delete(s.element)),s.element=r,this.elementToSlotId.set(r,o),this.intersectionObserver?.observe(r))}else{let d=n?.refreshIndex??this.slotRefreshIndices.get(o)??0;this.slotRefreshIndices.set(o,d),n?.auctionId&&this.slotLastAuctionIds.set(o,n.auctionId);let a=this.pendingThresholdListeners.get(o)||new Set;this.pendingThresholdListeners.delete(o);let l=this.pendingViewableListeners.get(o)||new Set;this.pendingViewableListeners.delete(o);let c={slotId:o,element:r,adUnitCode:n?.adUnitCode||o,auctionId:n?.auctionId||"",transactionId:n?.transactionId||"",mediaType:n?.mediaType||"banner",bidPayload:n?.bid,metadata:n?.metadata,refreshIndex:d,inView:!1,lastEnteredViewAt:null,accumulatedTimeInViewMs:0,viewableFired:!1,dwellTimer:null,dwellStartedAt:null,thresholdListeners:a,viewableListeners:l};this.slotViewabilityRecords.set(o,c),r&&(this.elementToSlotId.set(r,o),this.intersectionObserver?.observe(r))}}unobserveSlot(e){let t=this.slotViewabilityRecords.get(e);if(t){this.flushSlotTimeInView(e),t.dwellTimer&&(clearTimeout(t.dwellTimer),t.dwellTimer=null,t.dwellStartedAt=null);for(let n of t.thresholdListeners)n.timer&&(clearTimeout(n.timer),n.timer=null);t.thresholdListeners=new Set,t.viewableListeners=new Set,t.element&&this.intersectionObserver&&(this.intersectionObserver.unobserve(t.element),this.elementToSlotId.delete(t.element),t.element=null),t.inView=!1,t.lastEnteredViewAt=null}}destroySlot(e){this.unobserveSlot(e),this.slotViewabilityRecords.delete(e),this.slotRefreshIndices.delete(e),this.slotLastAuctionIds.delete(e),this.pendingThresholdListeners.delete(e),this.pendingViewableListeners.delete(e);let t=`${f(e)}:`;for(let r of Array.from(this.slotEmittedImpressionKeys))(r===e||r.startsWith(t))&&this.slotEmittedImpressionKeys.delete(r);let n=this.cachedWinningBids.get(e);n&&this.deleteCachedBidEntry(n)}getCachedBid(e){let t=this.cachedWinningBids.get(e);if(t){if(Date.now()-t.timestamp>j){this.deleteCachedBidEntry(t);return}return t}}deleteCachedBidEntry(e){for(let[t,n]of Array.from(this.cachedWinningBids))n===e&&this.cachedWinningBids.delete(t)}pruneCachedWinningBids(){let e=Date.now();for(let[t,n]of Array.from(this.cachedWinningBids))e-n.timestamp>j&&this.cachedWinningBids.delete(t);for(;this.cachedWinningBids.size>qt;){let t=this.cachedWinningBids.keys().next();if(t.done)break;this.cachedWinningBids.delete(t.value)}}addImpressionKey(e){if(!this.slotEmittedImpressionKeys.has(e)){for(;this.slotEmittedImpressionKeys.size>=Ht;){let t=this.slotEmittedImpressionKeys.values().next();if(t.done)break;this.slotEmittedImpressionKeys.delete(t.value)}this.slotEmittedImpressionKeys.add(e)}}getOrCreateAuctionOutcomes(e){let t=this.auctionBidderOutcomes.get(e);for(t||(t=new Map,this.auctionBidderOutcomes.set(e,t));this.auctionBidderOutcomes.size>Gt;){let n=this.auctionBidderOutcomes.keys().next();if(n.done||n.value===e)break;this.auctionBidderOutcomes.delete(n.value)}return t}hasImpressionEmitted(e,t,n,r){let o=t??this.slotRefreshIndices.get(e)??0,s=`${f(e)}:${o}`;return r?n?this.slotEmittedImpressionKeys.has(`${s}:auc:${f(n)}:${f(r)}`)||this.slotEmittedImpressionKeys.has(`${s}:${f(r)}`):this.slotEmittedImpressionKeys.has(`${s}:${f(r)}`):n?this.slotEmittedImpressionKeys.has(`${s}:auc:${f(n)}`):this.slotEmittedImpressionKeys.has(s)}markImpressionEmitted(e,t,n,r){let o=`${f(e)}:${t}`;this.addImpressionKey(o),r&&this.addImpressionKey(`${o}:${f(r)}`),n&&(this.addImpressionKey(`${o}:auc:${f(n)}`),r&&this.addImpressionKey(`${o}:auc:${f(n)}:${f(r)}`))}recordImpression(e,t){if(!this.isEnabled)return!1;let n=e||t?.adUnitCode||"",r=t?.adUnitCode||n,o=(t?.auctionId&&n?this.getCachedBid(`${t.auctionId}:${n}`):void 0)||(t?.auctionId&&r?this.getCachedBid(`${t.auctionId}:${r}`):void 0)||(n?this.getCachedBid(n):void 0)||(r?this.getCachedBid(r):void 0),s=t?.bid||o?.rawBid||{},d=t?.auctionId||s.auctionId||o?.auctionId||"",a=t?.transactionId||s.transactionId||o?.transactionId||"",l=s.creativeId||o?.bidTrace?.creativeId||t?.bid?.creativeId||"",c=t?.mediaType||s.mediaType||o?.bidTrace?.mediaType||"banner",b=n||r,h=(n?this.slotViewabilityRecords.get(n):void 0)||(r?this.slotViewabilityRecords.get(r):void 0),m=b?this.slotLastAuctionIds.get(b)||(h?h.auctionId:void 0):void 0,A=!!(b&&d&&m&&m!==d&&t?.refreshIndex===void 0),p={bidder:s.bidderCode||s.bidder||o?.bidTrace?.bidder||"",cpm:Number.isFinite(s.originalCpm)?s.originalCpm:Number.isFinite(s.cpm)?s.cpm:o?.bidTrace?.cpm??0,currency:s.originalCurrency??s.currency??o?.bidTrace?.currency??"USD",...W(s).width?W(s):o?.bidTrace?{width:o.bidTrace.width,height:o.bidTrace.height}:W(s),dealId:s.dealId||o?.bidTrace?.dealId||"",mediaType:c,latencyMs:Number.isFinite(s.timeToRespond)?s.timeToRespond:o?.bidTrace?.latencyMs??0,advertiserDomain:s.meta?.advertiserDomains?.[0]||o?.bidTrace?.advertiserDomain||"",creativeId:s.creativeId||o?.bidTrace?.creativeId||""};if(A&&b){this.flushSlotTimeInView(b);let L=(this.slotRefreshIndices.get(b)??(h?h.refreshIndex:0))+1;this.slotRefreshIndices.set(b,L),this.slotLastAuctionIds.set(b,d),h&&(h.refreshIndex=L,h.auctionId=d,h.transactionId=a,h.bidPayload=p,h.viewableFired=!1,h.accumulatedTimeInViewMs=0)}else b&&(d&&this.slotLastAuctionIds.set(b,d),this.slotRefreshIndices.has(b)||this.slotRefreshIndices.set(b,0));let E=t?.refreshIndex??(n?this.slotRefreshIndices.get(n)??(r?this.slotRefreshIndices.get(r):void 0)??(h?h.refreshIndex:0):0);return n&&this.hasImpressionEmitted(n,E,d,l)||r&&r!==n&&this.hasImpressionEmitted(r,E,d,l)?(this.log("DEBUG",`Impression already emitted for slot ${n||r} in cycle ${E}`),!1):(n&&this.markImpressionEmitted(n,E,d,l),r&&r!==n&&this.markImpressionEmitted(r,E,d,l),this.enqueue(I.IMPRESSION,"impression",{auctionId:d,transactionId:a,adUnitCode:r,bid:p,metadata:{...t?.metadata,refresh_index:String(E)}}),h&&(!h.bidPayload&&p&&(h.bidPayload=p),!h.auctionId&&d&&(h.auctionId=d),!h.transactionId&&a&&(h.transactionId=a)),!0)}onTimeInViewThreshold(e,t,n){let r={thresholdMs:t,callback:n,timer:null,fired:!1},o=this.slotViewabilityRecords.get(e);if(o){o.thresholdListeners.add(r);let s=this.getCurrentTimeInView(o);if(s>=t){r.fired=!0;try{n(e,s)}catch(d){this.log("ERROR","Error in threshold callback",d)}}else if(o.inView&&(typeof document>"u"||document.visibilityState==="visible")){let d=t-s;r.timer=setTimeout(()=>{if(r.timer=null,!r.fired&&o.inView&&(typeof document>"u"||document.visibilityState==="visible")){let a=this.getCurrentTimeInView(o);if(a>=t){r.fired=!0;try{n(e,a)}catch(l){this.log("ERROR","Error in threshold callback",l)}}}},d)}}else this.pendingThresholdListeners.has(e)||this.pendingThresholdListeners.set(e,new Set),this.pendingThresholdListeners.get(e).add(r);return()=>{r.timer&&(clearTimeout(r.timer),r.timer=null),o&&o.thresholdListeners.delete(r);let s=this.pendingThresholdListeners.get(e);s&&s.delete(r)}}getViewabilityState(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;let n=Math.round(this.getCurrentTimeInView(t));return{inView:t.inView,viewable:t.viewableFired,timeInViewMs:n,refreshIndex:t.refreshIndex}}getEndpoint(){return this.config.endpoint}getRefreshIndex(e){return this.slotRefreshIndices.get(e)??0}triggerSlotRefresh(e,t){let n=this.slotViewabilityRecords.get(e);n&&n.element&&this.observeSlot(n.element,e,t)}trackRawEvent(e,t,n){let r=$t[t]??(e==="ERROR"?I.ERROR:void 0);r!==void 0&&this.enqueue(r,t,n,e)}setUserId(e){this.config.userId=e}setSessionId(e){this.config.sessionId=e,this.managesSessionId=!e,this.managesSessionId&&(this.config.sessionId=ge())}navigate(e,t){if(this.disable(),this.slotRefreshIndices.clear(),this.pendingThresholdListeners.clear(),this.config.pageviewId=e||H(),t)try{let n=new URL(t);this.pageUrl=n.origin+n.pathname}catch{this.pageUrl=t}else this.pageUrl="";this.logger.resetTiming(),te(),this.enable()}handleAuctionInit(e){if(this.isDuplicate("auctionInit",e))return;this.log("DEBUG","auctionInit",e);let t=e.auctionId||"";t&&(this.auctionBidderOutcomes.delete(t),this.getOrCreateAuctionOutcomes(t)),this.enqueue(I.AUCTION_START,"auctionStart",{auctionId:t,transactionId:e.transactionId||""})}handleAuctionEnd(e){if(this.isDuplicate("auctionEnd",e))return;this.log("DEBUG","auctionEnd",e);let t=e.auctionId||"",n=t?this.auctionBidderOutcomes.get(t):void 0,r=n?Array.from(n.values()):[];t&&this.auctionBidderOutcomes.delete(t),this.enqueue(I.AUCTION_END,"auctionEnd",{auctionId:t,transactionId:e.transactionId||"",bidderOutcomes:r})}auctionCycleIndex(e){if(!e)return 0;let t=this.slotRefreshIndices.get(e)??this.slotViewabilityRecords.get(e)?.refreshIndex;return t===void 0?0:t+1}handleBidRequested(e){if(this.isDuplicate("bidRequested",e))return;this.log("DEBUG","bidRequested",e);let t=e.auctionId||"",n=e.bidderCode||e.bidder||"";if(!t||!n)return;let r=this.getOrCreateAuctionOutcomes(t);Array.isArray(e.bids)&&e.bids.forEach(o=>{let s=o.adUnitCode||"",d=Object.keys(o.mediaTypes||{}),a=d.length>0?d[0]:o.mediaType||"banner",l=`${n}:${s}`;r.has(l)||r.set(l,{adUnitCode:s,outcome:U.BIDDER_OUTCOME_NO_RESPONSE,bid:{bidder:n,mediaType:a,latencyMs:0}})})}handleBidResponse(e){if(this.isDuplicate("bidResponse",e))return;this.log("DEBUG","bidResponse",e);let t=e.auctionId||"",n=e.bidderCode||e.bidder||"",r=e.adUnitCode||"",o=Number.isFinite(e.originalCpm)?e.originalCpm:Number.isFinite(e.cpm)?e.cpm:0,s=Number.isFinite(e.timeToRespond)?e.timeToRespond:0,d=Object.keys(e.mediaTypes||{}),a=e.mediaType||(e.mediaTypes?.video?"video":d.length>0?d[0]:"banner");if(!t||!n)return;let l=o>0?{bidder:n,cpm:o,currency:e.originalCurrency??e.currency??"USD",...W(e),dealId:e.dealId||"",mediaType:a,latencyMs:s,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""}:{bidder:n,mediaType:a,latencyMs:s};this.getOrCreateAuctionOutcomes(t).set(`${n}:${r}`,{adUnitCode:r,outcome:o>0?U.BIDDER_OUTCOME_BID:U.BIDDER_OUTCOME_NO_BID,bid:l})}handleBidTimeout(e){if(this.isDuplicate("bidTimeout",e))return;this.log("DEBUG","bidTimeout",e);let t=Array.isArray(e)?e:e?[e]:[];for(let n of t){let r=n.auctionId||"",o=n.bidderCode||n.bidder||"",s=n.adUnitCode||"",d=Number.isFinite(n.timeout)?n.timeout:0;if(r&&o){let a=this.getOrCreateAuctionOutcomes(r),l=`${o}:${s}`,c=a.get(l);c?(c.outcome=U.BIDDER_OUTCOME_TIMEOUT,d>0&&c.bid&&(c.bid.latencyMs=d)):a.set(l,{adUnitCode:s,outcome:U.BIDDER_OUTCOME_TIMEOUT,bid:{bidder:o,mediaType:"banner",latencyMs:d}})}}}handleBidWon(e){if(this.isDuplicate("bidWon",e))return;this.log("DEBUG","bidWon",e);let t=e.auctionId||"",n=e.transactionId||"",r=e.adUnitCode||e.adId||"",o=Object.keys(e.mediaTypes||{}),s=e.mediaType||(e.mediaTypes?.video?"video":o.length>0?o[0]:"banner"),d={bidder:e.bidderCode||e.bidder||"",cpm:Number.isFinite(e.originalCpm)?e.originalCpm:Number.isFinite(e.cpm)?e.cpm:0,currency:e.originalCurrency??e.currency??"USD",...W(e),dealId:e.dealId||"",mediaType:s,latencyMs:Number.isFinite(e.timeToRespond)?e.timeToRespond:0,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""};if(r){let a={bidTrace:d,auctionId:t,transactionId:n,adUnitCode:r,rawBid:e,timestamp:Date.now()};this.cachedWinningBids.set(r,a),e.adId&&e.adId!==r&&this.cachedWinningBids.set(e.adId,a),t&&(this.cachedWinningBids.set(`${t}:${r}`,a),e.adId&&e.adId!==r&&this.cachedWinningBids.set(`${t}:${e.adId}`,a)),this.pruneCachedWinningBids()}this.enqueue(I.BID_WIN,"bidWon",{auctionId:t,transactionId:n,adUnitCode:r,bid:d})}handleNoBid(e){if(this.isDuplicate("noBid",e))return;this.log("DEBUG","noBid",e);let t=e.auctionId||"",n=e.bidderCode||e.bidder||"",r=e.adUnitCode||"";if(t&&n){let o=this.getOrCreateAuctionOutcomes(t),s=`${n}:${r}`,d=o.get(s);d?d.outcome===U.BIDDER_OUTCOME_NO_RESPONSE&&(d.outcome=U.BIDDER_OUTCOME_NO_BID):o.set(s,{adUnitCode:r,outcome:U.BIDDER_OUTCOME_NO_BID,bid:{bidder:n,mediaType:"banner",latencyMs:0}})}}handleAdRenderFailed(e){if(this.isDuplicate("adRenderFailed",e))return;this.log("DEBUG","adRenderFailed",e);let t=e.bid||{};this.enqueue(I.AD_RENDER_FAILED,"adRenderFailed",{auctionId:t.auctionId||e.auctionId||"",transactionId:t.transactionId||e.transactionId||"",adUnitCode:t.adUnitCode||e.adUnitCode||"",bid:{bidder:t.bidderCode||t.bidder||e.bidderCode||e.bidder||""},metadata:{reason:String(e.reason||""),message:String(e.message||e.error?.message||"")},error:e.error||(e.message?new Error(String(e.message)):void 0)})}handleAdRenderSucceeded(e){if(this.isDuplicate("adRenderSucceeded",e))return;this.log("DEBUG","adRenderSucceeded",e);let t=e.bid||e||{},n=e.adUnitCode||t.adUnitCode||e.adId||t.adId||"",r=t.auctionId||e.auctionId||"",o=t.transactionId||e.transactionId||"",s=t.mediaType||"banner",d=e.adUnitCode||t.adUnitCode||"",a=e.adId||t.adId||"",l=(r&&d?this.getCachedBid(`${r}:${d}`):void 0)||(r&&a?this.getCachedBid(`${r}:${a}`):void 0)||(d?this.getCachedBid(d):void 0)||(a?this.getCachedBid(a):void 0),c=s==="video"||t.mediaType==="video"||t.mediaTypes?.video!==void 0||l?.bidTrace?.mediaType==="video"||l?.rawBid?.mediaType==="video"||n&&this.slotViewabilityRecords.get(n)?.mediaType==="video",b=c?"video":s||l?.bidTrace?.mediaType||"banner",h={bidder:t.bidderCode||t.bidder||l?.bidTrace?.bidder||"",cpm:Number.isFinite(t.originalCpm)?t.originalCpm:Number.isFinite(t.cpm)?t.cpm:l?.bidTrace?.cpm??0,currency:t.originalCurrency??t.currency??l?.bidTrace?.currency??"USD",...W(t).width?W(t):l?.bidTrace?{width:l.bidTrace.width,height:l.bidTrace.height}:W(t),dealId:t.dealId||l?.bidTrace?.dealId||"",mediaType:b,latencyMs:Number.isFinite(t.timeToRespond)?t.timeToRespond:l?.bidTrace?.latencyMs??0,advertiserDomain:t.meta?.advertiserDomains?.[0]||l?.bidTrace?.advertiserDomain||"",creativeId:t.creativeId||l?.bidTrace?.creativeId||""},m=r||l?.auctionId||"",A=o||l?.transactionId||"",p=n?this.slotViewabilityRecords.get(n):void 0,E=p&&m&&p.auctionId&&p.auctionId!==m;if(!!(n&&p&&E)){this.flushSlotTimeInView(n);let T=(this.slotRefreshIndices.get(n)??(p?p.refreshIndex:0))+1;this.slotRefreshIndices.set(n,T),this.slotLastAuctionIds.set(n,m),p&&(p.refreshIndex=T,p.auctionId=m,p.transactionId=A,p.bidPayload=h,p.viewableFired=!1,p.accumulatedTimeInViewMs=0)}else n&&(m&&this.slotLastAuctionIds.set(n,m),this.slotRefreshIndices.has(n)||this.slotRefreshIndices.set(n,0));let L=n?this.slotRefreshIndices.get(n)??(p?p.refreshIndex:0):0;if(c?this.log("DEBUG",`adRenderSucceeded received for video ad unit ${n||"unknown"}: suppressing IMPRESSION until verified video lifecycle event`):n&&this.hasImpressionEmitted(n,L,m,h.creativeId)||(n&&this.markImpressionEmitted(n,L,m,h.creativeId),this.enqueue(I.IMPRESSION,"impression",{auctionId:m,transactionId:A,adUnitCode:n,bid:h,metadata:{refresh_index:String(L)}})),this.config.viewabilityEnabled&&typeof document<"u"){let T=n&&this.slotElements.get(n)||null,x=n||e.adId||t.adId;if(!T&&x&&(T=document.getElementById(x)),!T&&typeof window<"u"&&window.googletag?.pubads)try{let k=window.googletag.pubads().getSlots();for(let g of k)if((g.getAdUnitPath?.()===n||g.getSlotElementId?.()===n)&&(T=document.getElementById(g.getSlotElementId()),T))break}catch{}if(!T&&x)try{for(let k of Array.from(document.querySelectorAll("[data-ad-slot]")))if(k.getAttribute("data-ad-slot")===x){T=k;break}}catch{}T&&this.observeSlot(T,n||x,{adUnitCode:n,auctionId:m,transactionId:A,mediaType:b,bid:h,refreshIndex:L})}}isDuplicate(e,t){return this.deduper.isDuplicate(e,t)}enqueue(e,t,n,r){if(!this.isEnabled||!this.shouldSample(e,r))return;this.managesSessionId&&rn()&&(this.config.sessionId=ge());let o={eventId:$(H()),timestampMs:Date.now(),type:e,eventName:e===I.ERROR?t:"",auctionId:$(String(n.auctionId||"")),transactionId:$(String(n.transactionId||"")),adUnitCode:n.adUnitCode||n.elementId||"",namespace:n.ns||n.namespace||""};n.bid&&(o.bid={bidder:n.bid.bidder||"",cpm:Number.isFinite(n.bid.cpm)?n.bid.cpm:0,currency:n.bid.currency||"",width:Number.isFinite(n.bid.width)?n.bid.width:0,height:Number.isFinite(n.bid.height)?n.bid.height:0,dealId:n.bid.dealId||"",mediaType:n.bid.mediaType||"",latencyMs:Number.isFinite(n.bid.latencyMs)?n.bid.latencyMs:0,advertiserDomain:n.bid.advertiserDomain||"",creativeId:n.bid.creativeId||""}),n.viewableDurationMs!==void 0&&(o.viewableDurationMs=Number.isFinite(n.viewableDurationMs)?n.viewableDurationMs:0),n.bidderOutcomes&&Array.isArray(n.bidderOutcomes)&&(o.bidderOutcomes=n.bidderOutcomes.map(a=>({...a,refreshIndex:a.refreshIndex??this.auctionCycleIndex(a.adUnitCode||"")})));let s={...n.metadata};n.error!==void 0&&n.error!==null&&(s.error=typeof n.error=="object"&&n.error.message?String(n.error.message):String(n.error)),n.gpid&&(s.gpid=String(n.gpid)),n.refreshIndex!==void 0&&s.refresh_index===void 0&&(s.refresh_index=String(n.refreshIndex));let d=Qt(s);Object.keys(d).length>0&&(o.metadata=d),this.queue.push(o),this.queue.length>=z?(this.flush(),this.queue.length>z&&this.queue.splice(0,this.queue.length-z)):jt.has(e)&&this.revenueFlushTimer===null&&(this.revenueFlushTimer=setTimeout(()=>{this.revenueFlushTimer=null,this.flush()},this.config.revenueFlushDelayMs))}shouldSample(e,t){return e===I.ERROR?(this.errorCount++,this.errorCount>Ot?!1:this.config.errorsEnabled):t==="WARN"?this.config.warningsEnabled:this.config.auctionEnabled}requeue(e){e.length&&(this.queue=e.concat(this.queue),this.queue.length>z&&this.queue.splice(0,this.queue.length-z))}drainBatch(){if(this.queue.length===0||!this.config.endpoint)return null;let e=typeof window<"u"?window.location.hostname:"",t=n=>({propertyId:$(this.config.propertyId),pageviewId:$(this.config.pageviewId),sessionId:$(this.config.sessionId),pageUrl:this.pageUrl,country:this.config.country,region:this.config.region,deviceType:this.config.deviceType,userId:$(this.config.userId),domain:e,events:n});for(;;){if(this.queue.length===0)return null;let n=this.queue,r=pe.encode(t(n)).finish();for(;n.length>1&&r.byteLength>be;)n=n.slice(0,Math.floor(n.length/2)),r=pe.encode(t(n)).finish();if(r.byteLength>be){let[o]=this.queue.splice(0,1);this.log("WARN",`Dropping oversized event (type ${o?.type}, ${r.byteLength} bytes exceeds the ${be}-byte cap on its own)`);continue}return this.queue=this.queue.slice(n.length),{url:`${this.config.endpoint}/${this.config.propertyId}`,encoded:r,events:n}}}sendFetch(e,t=!1,n,r=!1){let o={method:"POST",headers:{"Content-Type":Ye},body:e.encoded};t&&(o.keepalive=!0),fetch(e.url,o).then(d=>{if(d.ok)r||(this.consecutiveSendFailures=0,this.nextSendAllowedAt=0),n&&n();else{if(this.log("WARN",`Failed to send batch: HTTP ${d.status}`),d.status>=400&&d.status<500&&d.status!==429&&d.status!==408){this.log("WARN",`Dropping batch due to non-retryable client error HTTP ${d.status}`);return}r||this.handleSendFailure(e.events)}}).catch(d=>{this.log("ERROR","Failed to send batch",d),r||this.handleSendFailure(e.events)});let s=typeof globalThis<"u"?globalThis.process:void 0;if(s&&typeof s._tickCallback=="function")try{s._tickCallback()}catch{}}handleSendFailure(e){this.consecutiveSendFailures++;let t=Math.min(Ge*2**(this.consecutiveSendFailures-1),Mt);this.nextSendAllowedAt=Date.now()+t,this.consecutiveSendFailures<=Ut?this.requeue(e):this.log("WARN",`Dropping ${e.length} events after ${this.consecutiveSendFailures} consecutive send failures`)}flush(){if(Date.now()<this.nextSendAllowedAt)return;let e=this.drainBatch();for(;e&&(this.sendFetch(e,!1),!(Date.now()<this.nextSendAllowedAt));)e=this.drainBatch()}flushBeacon(){let e=this.drainBatch();for(;e;){let t=!1;if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{let n=new Blob([e.encoded],{type:Ye});t=navigator.sendBeacon(e.url,n)}catch{t=!1}if(!t){let n=this.persistBatch(e.encoded);this.sendFetch(e,!0,()=>this.removePersistedBatch(n))}e=this.drainBatch()}this.schedulePersistedCleanup()}pendingKeyPrefix(){return`${ee}${encodeURIComponent(this.config.propertyId)}_`}persistBatch(e){if(!K)return null;try{if(typeof localStorage>"u"||!this.config.propertyId)return null;let t=0;for(let r=0;r<localStorage.length;r++){let o=localStorage.key(r);o&&o.startsWith(ee)&&t++}if(t>=Pt)return null;let n=`${this.pendingKeyPrefix()}${Date.now()}_${Math.floor(Math.random()*1e6)}`;return localStorage.setItem(n,Yt(e)),this.persistedBatchKeys.push(n),n}catch{return null}}removePersistedBatch(e){if(!e)return;try{typeof localStorage<"u"&&localStorage.removeItem(e)}catch{}let t=this.persistedBatchKeys.indexOf(e);t!==-1&&this.persistedBatchKeys.splice(t,1)}schedulePersistedCleanup(){this.persistedBatchKeys.length!==0&&(this.persistedCleanupTimer&&clearTimeout(this.persistedCleanupTimer),this.persistedCleanupTimer=setTimeout(()=>{this.persistedCleanupTimer=null;for(let e of Array.from(this.persistedBatchKeys))this.removePersistedBatch(e)},Ft))}resendPersistedBatches(){try{if(typeof localStorage>"u"||!this.config.endpoint||!this.config.propertyId)return;let e=this.pendingKeyPrefix(),t=[],n=[];for(let r=0;r<localStorage.length;r++){let o=localStorage.key(r);!o||!o.startsWith(ee)||(o.startsWith(e)?t.push(o):Zt(o)&&n.push(o))}for(let r of n)try{localStorage.removeItem(r)}catch{}for(let r of t){let o=null;try{o=localStorage.getItem(r),localStorage.removeItem(r)}catch{continue}if(!o)continue;let s=parseInt(r.slice(e.length),10);if(!Number.isFinite(s)||Date.now()-s>Vt)continue;let d;try{d=zt(o)}catch{continue}d.byteLength!==0&&(this.log("DEBUG",`Resending persisted exit batch (${d.byteLength} bytes)`),this.sendFetch({url:`${this.config.endpoint}/${this.config.propertyId}`,encoded:d,events:[]},!1,void 0,!0))}}catch{}}log(e,t,...n){this.logger.log(e,t,...n)}},me=re({prefix:"[bidkernel]",logLevel:"INFO"})});function an(i){let e=typeof i?.getError=="function"?i.getError():i?.error||i,t=a=>e&&typeof e[a]=="function"?e[a]():void 0,n=t("getMessage")||e?.message||String(e||"IMA ad error"),r=t("getErrorCode")??e?.code,o=t("getVastErrorCode"),s=t("getType")??e?.type,d={message:n};return r&&(d.error_code=String(r)),o&&(d.vast_error_code=String(o)),s&&(d.error_type=String(s)),{err:e,message:n,metadata:d}}function ot(i,e,t){let n=ne(i),{err:r,message:o,metadata:s}=an(e);return n.log("WARN","IMA AdErrorEvent received",e),n.enqueue(I.AD_RENDER_FAILED,"adRenderFailed",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,bid:t.bid,metadata:{...t.metadata,reason:t.adStarted?"ima_playback_error":"ima_ad_error",playback_phase:t.adStarted?"post_start":"pre_start",...s},error:typeof r=="object"?r:new Error(o)}),r}function cn(i,e){if(!i||typeof i!="object"||tt.has(i))return;tt.add(i);let t=typeof window<"u"&&window.google?.ima?.AdErrorEvent?.Type?.AD_ERROR||"adError";try{e.call(i,t,n=>{for(let r of C.getActiveInstances())try{let o=dt(r,{mediaType:"video"});ot(r,n,{adStarted:!1,adUnitCode:o?.adUnitCode||"video",auctionId:o?.auctionId,transactionId:o?.transactionId,bid:o?.bidTrace})}catch{}})}catch{}}function nt(i){if(i)try{let e=i.prototype;if(e&&typeof e.getAdsManager=="function"&&!e.getAdsManager.__bidkernelHooked){let t=e.getAdsManager,n=function(...r){let o=t.apply(this,r);if(o)for(let s of C.getActiveInstances())try{s.attachImaAdsManager(o)}catch{}return o};n.__bidkernelHooked=!0,e.getAdsManager=n}}catch{}}function it(i){if(i)try{let e=i.prototype||i;if(e&&typeof e.init=="function"&&!e.init.__bidkernelHooked){let t=e.init,n=function(...r){for(let o of C.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};n.__bidkernelHooked=!0,e.init=n}if(e&&typeof e.start=="function"&&!e.start.__bidkernelHooked){let t=e.start,n=function(...r){for(let o of C.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};n.__bidkernelHooked=!0,e.start=n}}catch{}}function rt(i){if(i)try{let e=i.prototype;if(!e)return;if(typeof e.addEventListener=="function"&&!e.addEventListener.__bidkernelHooked){let t=e.addEventListener,n=function(r,o,...s){if(cn(this,t),(r==="adsManagerLoaded"||r===(this?.AdsManagerLoadedEvent?.Type?.ADS_MANAGER_LOADED||"adsManagerLoaded"))&&typeof o=="function"){let d=Ee.get(o);return d||(d=function(a){if(a&&typeof a.getAdsManager=="function"&&!a.getAdsManager.__bidkernelHooked){let l=a.getAdsManager;a.getAdsManager=function(...c){let b=l.apply(this,c);if(b)for(let h of C.getActiveInstances())try{h.attachImaAdsManager(b)}catch{}return b},a.getAdsManager.__bidkernelHooked=!0}return o.apply(this,arguments)},Ee.set(o,d)),t.call(this,r,d,...s)}return t.call(this,r,o,...s)};n.__bidkernelHooked=!0,e.addEventListener=n}if(typeof e.removeEventListener=="function"&&!e.removeEventListener.__bidkernelHooked){let t=e.removeEventListener,n=function(r,o,...s){let d=typeof o=="function"?Ee.get(o):void 0;return t.call(this,r,d||o,...s)};n.__bidkernelHooked=!0,e.removeEventListener=n}}catch{}}function X(i){if(!(!i||typeof i!="object"))try{i.AdsManagerLoadedEvent&&nt(i.AdsManagerLoadedEvent);let e=Object.getOwnPropertyDescriptor(i,"AdsManagerLoadedEvent");if(!e||e.configurable){let r=i.AdsManagerLoadedEvent;try{Object.defineProperty(i,"AdsManagerLoadedEvent",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,nt(o)}})}catch{}}i.AdsLoader&&rt(i.AdsLoader);let t=Object.getOwnPropertyDescriptor(i,"AdsLoader");if(!t||t.configurable){let r=i.AdsLoader;try{Object.defineProperty(i,"AdsLoader",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,rt(o)}})}catch{}}i.AdsManager&&it(i.AdsManager);let n=Object.getOwnPropertyDescriptor(i,"AdsManager");if(!n||n.configurable){let r=i.AdsManager;try{Object.defineProperty(i,"AdsManager",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,it(o)}})}catch{}}}catch{}}function st(){if(typeof window>"u")return;let i=window;if(i.google?.ima&&X(i.google.ima),i.google&&typeof i.google=="object"){let t=Object.getOwnPropertyDescriptor(i.google,"ima");if(!t||t.configurable){let n=i.google.ima;try{Object.defineProperty(i.google,"ima",{configurable:!0,enumerable:!0,get(){return n},set(r){n=r,X(r)}})}catch{}}}let e=Object.getOwnPropertyDescriptor(i,"google");if(!e||e.configurable){let t=i.google;try{Object.defineProperty(i,"google",{configurable:!0,enumerable:!0,get(){return t},set(n){if(t=n,t&&typeof t=="object"){t.ima&&X(t.ima);let r=Object.getOwnPropertyDescriptor(t,"ima");if(!r||r.configurable){let o=t.ima;try{Object.defineProperty(t,"ima",{configurable:!0,enumerable:!0,get(){return o},set(s){o=s,X(s)}})}catch{}}}}})}catch{}}}function dt(i,e){let t=ne(i),n=Date.now(),r=d=>t.hasImpressionEmitted(d.adUnitCode,void 0,d.auctionId,d.bidTrace.creativeId);if(e?.creativeId||e?.adId){for(let d of Array.from(t.cachedWinningBids.values()))if(!(n-d.timestamp>j)&&(e.creativeId&&(d.bidTrace.creativeId===e.creativeId||d.rawBid?.creativeId===e.creativeId)||e.adId&&(d.rawBid?.adId===e.adId||d.adUnitCode===e.adId)))return d}let o;if(e?.mediaType){for(let a of Array.from(t.cachedWinningBids.values())){if(n-a.timestamp>j)continue;(a.bidTrace.mediaType===e.mediaType||a.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&a.rawBid?.mediaTypes?.video!==void 0)&&(r(a)||(!o||a.timestamp<o.timestamp)&&(o=a))}if(o)return o;let d;for(let a of Array.from(t.cachedWinningBids.values())){if(n-a.timestamp>j)continue;(a.bidTrace.mediaType===e.mediaType||a.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&a.rawBid?.mediaTypes?.video!==void 0)&&(!d||a.timestamp>d.timestamp)&&(d=a)}if(d)return d}for(let d of Array.from(t.cachedWinningBids.values()))n-d.timestamp>j||r(d)||(!o||d.timestamp>o.timestamp)&&(o=d);if(o)return o;let s;for(let d of Array.from(t.cachedWinningBids.values()))n-d.timestamp>j||(!s||d.timestamp>s.timestamp)&&(s=d);return s}function at(i,e,t){let n=ne(i);if(!e||typeof e.addEventListener!="function")return n.log("WARN","Invalid AdsManager passed to attachImaAdsManager"),()=>{};if(!e.__bidkernelAttachedInstances)try{Object.defineProperty(e,"__bidkernelAttachedInstances",{value:new Map,configurable:!0,writable:!0})}catch{e.__bidkernelAttachedInstances=new Map}let r=e.__bidkernelAttachedInstances,o=r.get(i);if(o){if(!t)return()=>{};o()}let s=t?.slotId||t?.adUnitCode||"video",d=t?.adUnitCode||s,a=t?.auctionId||"",l=t?.transactionId||"",c=y=>{let u=(a?n.getCachedBid(`${a}:${d}`):void 0)||(a&&s!==d?n.getCachedBid(`${a}:${s}`):void 0)||(d!=="video"?n.getCachedBid(d):void 0)||(s!==d&&s!=="video"?n.getCachedBid(s):void 0);return u||(u=dt(i,{creativeId:y?.creativeId,adId:y?.adId,mediaType:"video"})),u},b=!1,h=y=>{b=!0,n.log("DEBUG","IMA AdEvent.STARTED / IMPRESSION received",y);let u=typeof y?.getAd=="function"?y.getAd():y?.ad,v={};u&&(v.creativeId=(typeof u.getCreativeId=="function"?u.getCreativeId():u.creativeId)||"",v.adId=(typeof u.getAdId=="function"?u.getAdId():u.id)||"",v.title=(typeof u.getTitle=="function"?u.getTitle():u.title)||"",v.duration=typeof u.getDuration=="function"?u.getDuration():u.duration,v.advertiserName=typeof u.getAdvertiserName=="function"?u.getAdvertiserName():"");let R=c(v),M=t?.slotId&&t.slotId!=="video"?t.slotId:t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:R?.adUnitCode||t?.slotId||t?.adUnitCode||"video",ut=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:R?.adUnitCode||M,ft=a||R?.auctionId||"",ht=l||R?.transactionId||"",we={...R?.rawBid||t?.bid,mediaType:"video",creativeId:v.creativeId||R?.bidTrace?.creativeId||t?.bid?.creativeId||""};if(n.recordImpression(M,{adUnitCode:ut,auctionId:ft,transactionId:ht,mediaType:"video",bid:we,metadata:{...t?.metadata,media_type:"video",...v.title?{ad_title:v.title}:{},...Number.isFinite(v.duration)?{ad_duration_s:String(v.duration)}:{}}})&&t?.onImpression)try{t.onImpression(M,{ad:u,bid:we})}catch(pt){n.log("ERROR","Error in onImpression callback",pt)}},m=y=>{if(n.log("DEBUG",`IMA AdEvent milestone: ${y}`),t?.onMilestone)try{t.onMilestone(y,s)}catch(u){n.log("ERROR","Error in onMilestone callback",u)}},A=y=>{n.log("DEBUG","IMA AdEvent.CLICK received",y);let u=c(),v=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:u?.adUnitCode||s;n.enqueue(I.CLICK,"click",{auctionId:a||u?.auctionId,transactionId:l||u?.transactionId,adUnitCode:v,bid:u?.bidTrace||t?.bid,metadata:{...t?.metadata,media_type:"video"}})},p=y=>{let u=c(),v=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:u?.adUnitCode||s,R=ot(i,y,{adStarted:b,adUnitCode:v,auctionId:a||u?.auctionId,transactionId:l||u?.transactionId,bid:u?.bidTrace||t?.bid,metadata:t?.metadata});if(t?.onError)try{t.onError(R)}catch(M){n.log("ERROR","Error in onError callback",M)}},E=typeof window<"u"?window.google?.ima:void 0,S=E?.AdEvent?.Type||{},L=E?.AdErrorEvent?.Type||{},T=[{type:S.STARTED||"started",handler:h},{type:S.IMPRESSION||"impression",handler:h},{type:S.FIRST_QUARTILE||"firstQuartile",handler:()=>m("firstQuartile")},{type:S.MIDPOINT||"midpoint",handler:()=>m("midpoint")},{type:S.THIRD_QUARTILE||"thirdQuartile",handler:()=>m("thirdQuartile")},{type:S.COMPLETE||"complete",handler:()=>m("complete")},{type:S.CLICK||"click",handler:A},{type:L.AD_ERROR||"adError",handler:p}],x=new Set,k=[];for(let y of T)x.has(y.type)||(x.add(y.type),k.push(y));for(let{type:y,handler:u}of k)try{e.addEventListener(y,u)}catch{}let g=()=>{r.delete(i);for(let{type:y,handler:u}of k)try{e.removeEventListener(y,u)}catch{}n.videoDetachCleanups.delete(g)};return r.set(i,g),n.videoDetachCleanups.add(g),g}function ln(i,e,t){let n=ne(i);if(!e)return n.log("WARN","attachVideoPlayer called with null/undefined target"),()=>{};let r=null;if(typeof e=="string"){if(typeof document<"u")try{r=document.querySelector(e)||document.getElementById(e)}catch{r=document.getElementById(e)}}else if(typeof HTMLElement<"u"&&e instanceof HTMLElement)r=e;else if(e&&typeof e=="object"&&e.nodeType===1)r=e;else{if(typeof e.addEventListener=="function"&&(typeof e.init=="function"||typeof e.start=="function"||typeof e.getCuePoints=="function"||typeof e.getVolume=="function"||e.__imaAdsManager))return at(i,e,t);e&&typeof e.addEventListener=="function"&&(r=e)}let o=t?.slotId||t?.adUnitCode||(r?r.id:"")||"video",s=t?.adUnitCode||o,d=t?.auctionId||"",a=t?.transactionId||"",l=()=>(d?n.getCachedBid(`${d}:${s}`):void 0)||(d&&o!==s?n.getCachedBid(`${d}:${o}`):void 0)||n.getCachedBid(s)||(o!==s?n.getCachedBid(o):void 0),c=null;r&&(r.tagName&&r.tagName.toLowerCase()==="video"?c=r:c=r.querySelector("video"));let b={q1:!1,q2:!1,q3:!1,q4:!1},h=g=>{let y=g||c||(r?.querySelector?r.querySelector("video"):null),u=l(),v={...u?.rawBid||t?.bid,mediaType:"video"};if(n.recordImpression(o,{adUnitCode:s,auctionId:d||u?.auctionId,transactionId:a||u?.transactionId,mediaType:"video",bid:v,metadata:{...t?.metadata,media_type:"video",...y&&Number.isFinite(y.duration)?{video_duration_s:String(Math.round(y.duration))}:{}}})&&t?.onImpression)try{t.onImpression(o,{element:y||r,bid:v})}catch(M){n.log("ERROR","Error in onImpression callback",M)}},m=g=>{n.log("DEBUG","HTML5 video playing event received");let y=g?.target instanceof HTMLVideoElement?g.target:c;h(y)},A=g=>{let y=g?.target instanceof HTMLVideoElement?g.target:c;if(y&&y.currentTime>0&&(h(y),Number.isFinite(y.duration)&&y.duration>0)){let u=y.currentTime/y.duration;u>=.25&&!b.q1&&(b.q1=!0,t?.onMilestone?.("firstQuartile",o)),u>=.5&&!b.q2&&(b.q2=!0,t?.onMilestone?.("midpoint",o)),u>=.75&&!b.q3&&(b.q3=!0,t?.onMilestone?.("thirdQuartile",o))}},p=()=>{b.q4||(b.q4=!0,t?.onMilestone?.("complete",o))},E=g=>{let u=(g?.target instanceof HTMLVideoElement?g.target:c)?.error||c?.error,v=l(),R=u?`HTML5 video error code ${u.code}: ${u.message}`:"Video playback error";if(n.log("WARN",R),n.enqueue(I.AD_RENDER_FAILED,"adRenderFailed",{auctionId:d||v?.auctionId,transactionId:a||v?.transactionId,adUnitCode:s,bid:v?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"html5_video_error",message:R,...u?.code?{error_code:String(u.code)}:{}},error:u?new Error(R):void 0}),t?.onError)try{t.onError(u)}catch(M){n.log("ERROR","Error in onError callback",M)}},S=g=>{g.addEventListener("playing",m),g.addEventListener("play",m),g.addEventListener("timeupdate",A),g.addEventListener("ended",p),g.addEventListener("error",E)},L=g=>{g.removeEventListener("playing",m),g.removeEventListener("play",m),g.removeEventListener("timeupdate",A),g.removeEventListener("ended",p),g.removeEventListener("error",E)},T=null;r&&r!==c&&(r.addEventListener("playing",m,!0),r.addEventListener("play",m,!0),r.addEventListener("timeupdate",A,!0),r.addEventListener("ended",p,!0),r.addEventListener("error",E,!0)),c&&S(c),r&&r.tagName?.toLowerCase()!=="video"&&typeof MutationObserver<"u"&&(T=new MutationObserver(()=>{let g=r.querySelector("video");g&&g!==c&&(c&&L(c),c=g,c&&S(c))}),T.observe(r,{childList:!0,subtree:!0}));let x=l();t?.trackViewability!==!1&&r&&n.observeSlot(r,o,{adUnitCode:s,auctionId:d||x?.auctionId,transactionId:a||x?.transactionId,mediaType:"video",bid:x?.bidTrace||t?.bid,metadata:t?.metadata});let k=()=>{T&&(T.disconnect(),T=null),r&&r!==c&&(r.removeEventListener("playing",m,!0),r.removeEventListener("play",m,!0),r.removeEventListener("timeupdate",A,!0),r.removeEventListener("ended",p,!0),r.removeEventListener("error",E,!0)),c&&L(c),n.videoDetachCleanups.delete(k)};return n.videoDetachCleanups.add(k),k}var ne,Ee,tt,un,ct=_(()=>{"use strict";Te();ye();ne=i=>i,Ee=new WeakMap,tt=new WeakSet;typeof window<"u"&&st();C.prototype.attachImaAdsManager=function(i,e){return at(this,i,e)};C.prototype.attachVideoPlayer=function(i,e){return ln(this,i,e)};un=C.prototype.enable;C.prototype.enable=function(){un.call(this),typeof window<"u"&&(st(),window.google?.ima&&X(window.google.ima))}});var hn=yt(()=>{Te();ct();var lt="https://by.bidkernel.io/t",fn=window._bidkernelPbjsGlobal||"pbjs";ve(fn,{endpoint:lt});window.bidkernelPrebidAnalytics={...window.bidkernelPrebidAnalytics,register:(i,e)=>ve(i,{endpoint:lt,...e}),attachVideoPlayer:(i,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.attachVideoPlayer?t.attachVideoPlayer(i,e):()=>{}},attachImaAdsManager:(i,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.attachImaAdsManager?t.attachImaAdsManager(i,e):()=>{}},recordImpression:(i,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.recordImpression?t.recordImpression(i,e):!1}}});return hn();})();
1
+ "use strict";var bidkernelPrebidAnalyticsBundle=(()=>{var C=(i,e)=>()=>(i&&(e=i(i=0)),e);var gt=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);function It(){if(typeof window<"u"){let i=window;return i.__bidkernelLogListeners||(i.__bidkernelLogListeners=new Set),i.__bidkernelLogListeners}return mt}function vt(i){if((i<0||!Number.isFinite(i))&&(i=0),i<1e3)return`${i.toFixed(2)}ms`;let e=i/1e3;if(e<60)return`${e.toFixed(2)}s`;let t=Math.floor(e/60);return t<60?`${t}m ${(e%60).toFixed(2)}s`:`${Math.floor(t/60)}h ${t%60}m ${(e%60).toFixed(2)}s`}function Y(i){if(typeof i=="string"){let e=i.toUpperCase();if(e==="DEBUG"||e==="INFO"||e==="WARN"||e==="ERROR")return e}return w.INFO}function oe(i){return new re(i)}var w,_e,P,bt,mt,re,Ce=C(()=>{"use strict";w={DEBUG:"DEBUG",INFO:"INFO",WARN:"WARN",ERROR:"ERROR"},_e={[w.DEBUG]:10,[w.INFO]:20,[w.WARN]:30,[w.ERROR]:40},P={badge:"color: #2dd4bf; font-weight: bold",badgeWarn:"background: #f59e0b; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",badgeError:"background: #ef4444; color: #fff; padding: 2px 4px; border-radius: 3px; font-weight: bold",dim:"color: #6b7280",event:"color: #38bdf8; font-weight: bold",eventWarn:"color: #f59e0b; font-weight: bold",eventError:"color: #ef4444; font-weight: bold",reset:"color: inherit"},bt=0,mt=new Set;re=class i{_prefix;_level;_loadedAt;_now;_console;_customFormatTime;_listeners=new Set;constructor(e={}){this._prefix=e.prefix??"[bidkernel]",this._level=Y(e.logLevel??w.INFO),this._now=e.now,this._console=e.console,this._customFormatTime=e.formatTime,e.onLog&&this._listeners.add(e.onLog),this._loadedAt=e.loadedAt??(this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())}get prefix(){return this._prefix}set prefix(e){this._prefix=e}get logLevel(){return this._level}set logLevel(e){this._level=Y(e)}getLevel(){return this._level}setLevel(e){this._level=Y(e)}getPrefix(){return this._prefix}setPrefix(e){this._prefix=e}resetTiming(e){this._loadedAt=e??(this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now())}getLoadedAt(){return this._loadedAt}addListener(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}removeListener(e){this._listeners.delete(e)}isEnabled(e){let t=Y(e);return(_e[t]??20)>=(_e[this._level]??20)}formatTime(e){return this._customFormatTime?this._customFormatTime(e):vt(e)}_getConsole(){if(this._console)return this._console;if(typeof console<"u")return console}_getElapsed(){let e=this._now?this._now():typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();return Math.max(0,e-this._loadedAt)}_dispatchRecord(e){for(let n of this._listeners)try{n(e)}catch{}let t=It();for(let n of t)if(!this._listeners.has(n))try{n(e)}catch{}if(typeof window<"u"&&typeof window.dispatchEvent=="function")try{window.dispatchEvent(new CustomEvent("__bidkernel_log__",{detail:e}))}catch{}}log(e,t,...n){let r=Y(e);if(!this.isEnabled(r))return;let o=this._getElapsed(),s=this.formatTime(o),d=Date.now(),l={id:`bk_log_${d}_${++bt}`,timestamp:d,elapsedMs:o,level:r,prefix:this._prefix,message:t,args:n,data:n.length===1?n[0]:n.length>1?n:void 0};this._dispatchRecord(l);let c=this._getConsole();if(!c)return;let g=P.badge,h=P.event;r===w.WARN?(g=P.badgeWarn,h=P.eventWarn):r===w.ERROR&&(g=P.badgeError,h=P.eventError);let I=`%c${this._prefix}%c ${s} %c${t}%c`,A=[g,P.dim,h,P.reset],p=[I,...A];switch(n.length>0&&p.push(...n),r){case w.DEBUG:typeof c.log=="function"?c.log(...p):typeof c.debug=="function"&&c.debug(...p);break;case w.INFO:typeof c.info=="function"?c.info(...p):typeof c.log=="function"&&c.log(...p);break;case w.WARN:typeof c.warn=="function"?c.warn(...p):typeof c.log=="function"&&c.log(...p);break;case w.ERROR:typeof c.error=="function"?c.error(...p):typeof c.log=="function"&&c.log(...p);break;default:typeof c.log=="function"&&c.log(...p);break}}debug(e,...t){this.log(w.DEBUG,e,...t)}info(e,...t){this.log(w.INFO,e,...t)}warn(e,...t){this.log(w.WARN,e,...t)}error(e,...t){this.log(w.ERROR,e,...t)}logEvent(e){e&&(e.data!==void 0?this.log(e.level,e.eventName,e.data):this.log(e.level,e.eventName))}child(e,t={}){let n=this._prefix;if(e){let r=e.startsWith("[")&&e.endsWith("]")?e:`[${e}]`;n=`${this._prefix}${r}`}return new i({prefix:n,logLevel:t.logLevel??this._level,loadedAt:t.loadedAt??this._loadedAt,now:t.now??this._now,console:t.console??this._console,formatTime:t.formatTime??this._customFormatTime,...t})}withPrefix(e){return new i({prefix:e,logLevel:this._level,loadedAt:this._loadedAt,now:this._now,console:this._console,formatTime:this._customFormatTime})}}});function Se(){let i=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(i|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function Z(i,e,t){for(let o=0;o<28;o=o+7){let s=i>>>o,d=!(!(s>>>7)&&e==0),a=(d?s|128:s)&255;if(t.push(a),!d)return}let n=i>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?n|128:n)&255),!!r){for(let o=3;o<31;o=o+7){let s=e>>>o,d=!!(s>>>7),a=(d?s|128:s)&255;if(t.push(a),!d)return}t.push(e>>>31&1)}}function se(i){let e=i[0]==="-";e&&(i=i.slice(1));let t=1e6,n=0,r=0;function o(s,d){let a=Number(i.slice(s,d));r*=t,n=n*t+a,n>=Q&&(r=r+(n/Q|0),n=n%Q)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?Be(n,r):ae(n,r)}function Oe(i,e){let t=ae(i,e),n=t.hi&2147483648;n&&(t=Be(t.lo,t.hi));let r=de(t.lo,t.hi);return n?"-"+r:r}function de(i,e){if({lo:i,hi:e}=Et(i,e),e<=2097151)return String(Q*e+i);let t=i&16777215,n=(i>>>24|e<<8)&16777215,r=e>>16&65535,o=t+n*6777216+r*6710656,s=n+r*8147497,d=r*2,a=1e7;return o>=a&&(s+=Math.floor(o/a),o%=a),s>=a&&(d+=Math.floor(s/a),s%=a),d.toString()+Re(s)+Re(o)}function Et(i,e){return{lo:i>>>0,hi:e>>>0}}function ae(i,e){return{lo:i|0,hi:e|0}}function Be(i,e){return e=~e,i?i=~i+1:e+=1,ae(i,e)}function ce(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function Le(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var Q,Re,le=C(()=>{"use strict";Q=4294967296;Re=i=>{let e=String(i);return"0000000".slice(e.length)+e}});function Tt(){let i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),r=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let d=typeof s=="bigint"?s:BigInt(s);if(d>n||d<t)throw new Error(`invalid int64: ${s}`);return d},uParse(s){let d=typeof s=="bigint"?s:BigInt(s);if(d>o||d<r)throw new Error(`invalid uint64: ${s}`);return d},enc(s){return i.setBigInt64(0,this.parse(s),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(s){return i.setBigInt64(0,this.uParse(s),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(s,d){return i.setInt32(0,s,!0),i.setInt32(4,d,!0),i.getBigInt64(0,!0)},uDec(s,d){return i.setInt32(0,s,!0),i.setInt32(4,d,!0),i.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(t){return typeof t!="string"&&(t=t.toString()),De(t),t},uParse(t){return typeof t!="string"&&(t=t.toString()),xe(t),t},enc(t){return typeof t!="string"&&(t=t.toString()),De(t),se(t)},uEnc(t){return typeof t!="string"&&(t=t.toString()),xe(t),se(t)},dec(t,n){return Oe(t,n)},uDec(t,n){return de(t,n)}}}function De(i){if(!/^-?[0-9]+$/.test(i))throw new Error("invalid int64: "+i)}function xe(i){if(!/^[0-9]+$/.test(i))throw new Error("invalid uint64: "+i)}var k,ke=C(()=>{"use strict";le();k=Tt()});function fe(){if(globalThis[ue]==null){let i=new globalThis.TextEncoder,e=new globalThis.TextDecoder;globalThis[ue]={encodeUtf8(t){return i.encode(t)},decodeUtf8(t){return e.decode(t)},checkUtf8(t){try{return encodeURIComponent(t),!0}catch{return!1}}}}return globalThis[ue]}var ue,he=C(()=>{"use strict";ue=Symbol.for("@bufbuild/protobuf/text-encoding")});function pe(i){if(typeof i=="string")i=Number(i);else if(typeof i!="number")throw new Error("invalid int32: "+typeof i);if(!Number.isInteger(i)||i>Ct||i<Rt)throw new Error("invalid int32: "+i)}function Ue(i){if(typeof i=="string")i=Number(i);else if(typeof i!="number")throw new Error("invalid uint32: "+typeof i);if(!Number.isInteger(i)||i>_t||i<0)throw new Error("invalid uint32: "+i)}function St(i){if(typeof i=="string"){let e=i;if(i=Number(i),Number.isNaN(i)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof i!="number")throw new Error("invalid float32: "+typeof i);if(Number.isFinite(i)&&(i>wt||i<At))throw new Error("invalid float32: "+i)}var F,wt,At,_t,Ct,Rt,V,R,Me=C(()=>{"use strict";le();ke();he();(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(F||(F={}));wt=34028234663852886e22,At=-34028234663852886e22,_t=4294967295,Ct=2147483647,Rt=-2147483648,V=class{constructor(e=fe().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let r=0;r<this.chunks.length;r++)e+=this.chunks[r].length;let t=new Uint8Array(e),n=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],n),n+=this.chunks[r].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ue(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return pe(e),ce(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){St(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ue(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){pe(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return pe(e),e=(e<<1^e>>31)>>>0,ce(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=k.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=k.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=k.enc(e);return Z(t.lo,t.hi,this.buf),this}sint64(e){let t=k.enc(e),n=t.hi>>31,r=t.lo<<1^n,o=(t.hi<<1|t.lo>>>31)^n;return Z(r,o,this.buf),this}uint64(e){let t=k.uEnc(e);return Z(t.lo,t.hi,this.buf),this}},R=class{constructor(e,t=fe().decodeUtf8){this.decodeUtf8=t,this.varint64=Se,this.uint32=Le,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case F.Varint:for(;this.buf[this.pos++]&128;);break;case F.Bit64:this.pos+=4;case F.Bit32:this.pos+=4;break;case F.LengthDelimited:let r=this.uint32();this.pos+=r;break;case F.StartGroup:for(;;){let[o,s]=this.tag();if(s===F.EndGroup){if(t!==void 0&&o!==t)throw new Error("invalid end group tag");break}this.skip(s,o)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return k.dec(...this.varint64())}uint64(){return k.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,k.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return k.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return k.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.decodeUtf8(this.bytes())}}});var Ne=C(()=>{"use strict"});var Pe=C(()=>{"use strict"});var Fe=C(()=>{"use strict"});var Ve=C(()=>{"use strict";Me();Ne();he();Pe();Fe()});function Ot(){return{propertyId:new Uint8Array(0),pageviewId:new Uint8Array(0),sessionId:new Uint8Array(0),pageUrl:"",country:"",region:"",deviceType:"",userId:new Uint8Array(0),domain:"",events:[],browser:"",deviceManufacturer:"",deviceModel:"",city:"",postalCode:""}}function Bt(){return{timestampMs:0,type:0,eventName:"",auctionId:new Uint8Array(0),transactionId:new Uint8Array(0),adUnitCode:"",bid:void 0,namespace:"",eventId:new Uint8Array(0),metadata:{},viewableDurationMs:void 0,bidderOutcomes:[]}}function Lt(){return{key:"",value:""}}function Dt(){return{adUnitCode:"",outcome:0,bid:void 0,refreshIndex:0,floorCents:void 0,floorSource:0,floorTreatmentBp:void 0}}function xt(){return{bidder:"",cpm:0,currency:"",width:0,height:0,dealId:"",mediaType:"",latencyMs:0,advertiserDomain:"",creativeId:""}}var m,M,ee,ye,$e,We,je,J,ge=C(()=>{"use strict";Ve();m={TRACE_EVENT_TYPE_UNSPECIFIED:0,AUCTION_START:1,AUCTION_END:2,BID_WIN:4,IMPRESSION:5,VIEWABLE:6,TIME_IN_VIEW:7,ERROR:9,SLOT_DEFINED:10,SLOT_DESTROYED:11,CLICK:12,AD_RENDER_FAILED:13,UNRECOGNIZED:-1},M={BIDDER_OUTCOME_UNSPECIFIED:0,BIDDER_OUTCOME_BID:1,BIDDER_OUTCOME_NO_BID:2,BIDDER_OUTCOME_TIMEOUT:3,BIDDER_OUTCOME_ERROR:4,BIDDER_OUTCOME_NO_RESPONSE:5,UNRECOGNIZED:-1},ee={FLOOR_SOURCE_UNSPECIFIED:0,FLOOR_SOURCE_STATIC:1,FLOOR_SOURCE_POOL:2,FLOOR_SOURCE_NONE:3,UNRECOGNIZED:-1};ye={encode(i,e=new V){if(i.propertyId!==void 0&&i.propertyId.length!==0&&e.uint32(10).bytes(i.propertyId),i.pageviewId!==void 0&&i.pageviewId.length!==0&&e.uint32(18).bytes(i.pageviewId),i.sessionId!==void 0&&i.sessionId.length!==0&&e.uint32(26).bytes(i.sessionId),i.pageUrl!==void 0&&i.pageUrl!==""&&e.uint32(34).string(i.pageUrl),i.country!==void 0&&i.country!==""&&e.uint32(42).string(i.country),i.region!==void 0&&i.region!==""&&e.uint32(50).string(i.region),i.deviceType!==void 0&&i.deviceType!==""&&e.uint32(58).string(i.deviceType),i.userId!==void 0&&i.userId.length!==0&&e.uint32(66).bytes(i.userId),i.domain!==void 0&&i.domain!==""&&e.uint32(74).string(i.domain),i.events!==void 0&&i.events.length!==0)for(let t of i.events)$e.encode(t,e.uint32(82).fork()).join();return i.browser!==void 0&&i.browser!==""&&e.uint32(90).string(i.browser),i.deviceManufacturer!==void 0&&i.deviceManufacturer!==""&&e.uint32(98).string(i.deviceManufacturer),i.deviceModel!==void 0&&i.deviceModel!==""&&e.uint32(106).string(i.deviceModel),i.city!==void 0&&i.city!==""&&e.uint32(114).string(i.city),i.postalCode!==void 0&&i.postalCode!==""&&e.uint32(122).string(i.postalCode),e},decode(i,e){let t=i instanceof R?i:new R(i),n=e===void 0?t.len:t.pos+e,r=Ot();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.propertyId=t.bytes();continue}case 2:{if(o!==18)break;r.pageviewId=t.bytes();continue}case 3:{if(o!==26)break;r.sessionId=t.bytes();continue}case 4:{if(o!==34)break;r.pageUrl=t.string();continue}case 5:{if(o!==42)break;r.country=t.string();continue}case 6:{if(o!==50)break;r.region=t.string();continue}case 7:{if(o!==58)break;r.deviceType=t.string();continue}case 8:{if(o!==66)break;r.userId=t.bytes();continue}case 9:{if(o!==74)break;r.domain=t.string();continue}case 10:{if(o!==82)break;let s=$e.decode(t,t.uint32());s!==void 0&&r.events.push(s);continue}case 11:{if(o!==90)break;r.browser=t.string();continue}case 12:{if(o!==98)break;r.deviceManufacturer=t.string();continue}case 13:{if(o!==106)break;r.deviceModel=t.string();continue}case 14:{if(o!==114)break;r.city=t.string();continue}case 15:{if(o!==122)break;r.postalCode=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};$e={encode(i,e=new V){if(i.timestampMs!==void 0&&i.timestampMs!==0&&e.uint32(9).double(i.timestampMs),i.type!==void 0&&i.type!==0&&e.uint32(16).int32(i.type),i.eventName!==void 0&&i.eventName!==""&&e.uint32(26).string(i.eventName),i.auctionId!==void 0&&i.auctionId.length!==0&&e.uint32(34).bytes(i.auctionId),i.transactionId!==void 0&&i.transactionId.length!==0&&e.uint32(42).bytes(i.transactionId),i.adUnitCode!==void 0&&i.adUnitCode!==""&&e.uint32(50).string(i.adUnitCode),i.bid!==void 0&&J.encode(i.bid,e.uint32(58).fork()).join(),i.namespace!==void 0&&i.namespace!==""&&e.uint32(66).string(i.namespace),i.eventId!==void 0&&i.eventId.length!==0&&e.uint32(74).bytes(i.eventId),globalThis.Object.entries(i.metadata||{}).forEach(([t,n])=>{We.encode({key:t,value:n},e.uint32(82).fork()).join()}),i.viewableDurationMs!==void 0&&e.uint32(89).double(i.viewableDurationMs),i.bidderOutcomes!==void 0&&i.bidderOutcomes.length!==0)for(let t of i.bidderOutcomes)je.encode(t,e.uint32(98).fork()).join();return e},decode(i,e){let t=i instanceof R?i:new R(i),n=e===void 0?t.len:t.pos+e,r=Bt();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==9)break;r.timestampMs=t.double();continue}case 2:{if(o!==16)break;r.type=t.int32();continue}case 3:{if(o!==26)break;r.eventName=t.string();continue}case 4:{if(o!==34)break;r.auctionId=t.bytes();continue}case 5:{if(o!==42)break;r.transactionId=t.bytes();continue}case 6:{if(o!==50)break;r.adUnitCode=t.string();continue}case 7:{if(o!==58)break;r.bid=J.decode(t,t.uint32());continue}case 8:{if(o!==66)break;r.namespace=t.string();continue}case 9:{if(o!==74)break;r.eventId=t.bytes();continue}case 10:{if(o!==82)break;let s=We.decode(t,t.uint32());s.value!==void 0&&(r.metadata[s.key]=s.value);continue}case 11:{if(o!==89)break;r.viewableDurationMs=t.double();continue}case 12:{if(o!==98)break;let s=je.decode(t,t.uint32());s!==void 0&&r.bidderOutcomes.push(s);continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};We={encode(i,e=new V){return i.key!==""&&e.uint32(10).string(i.key),i.value!==""&&e.uint32(18).string(i.value),e},decode(i,e){let t=i instanceof R?i:new R(i),n=e===void 0?t.len:t.pos+e,r=Lt();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.key=t.string();continue}case 2:{if(o!==18)break;r.value=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};je={encode(i,e=new V){return i.adUnitCode!==void 0&&i.adUnitCode!==""&&e.uint32(18).string(i.adUnitCode),i.outcome!==void 0&&i.outcome!==0&&e.uint32(32).int32(i.outcome),i.bid!==void 0&&J.encode(i.bid,e.uint32(50).fork()).join(),i.refreshIndex!==void 0&&i.refreshIndex!==0&&e.uint32(56).int32(i.refreshIndex),i.floorCents!==void 0&&e.uint32(64).int32(i.floorCents),i.floorSource!==void 0&&i.floorSource!==0&&e.uint32(72).int32(i.floorSource),i.floorTreatmentBp!==void 0&&e.uint32(80).int32(i.floorTreatmentBp),e},decode(i,e){let t=i instanceof R?i:new R(i),n=e===void 0?t.len:t.pos+e,r=Dt();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 2:{if(o!==18)break;r.adUnitCode=t.string();continue}case 4:{if(o!==32)break;r.outcome=t.int32();continue}case 6:{if(o!==50)break;r.bid=J.decode(t,t.uint32());continue}case 7:{if(o!==56)break;r.refreshIndex=t.int32();continue}case 8:{if(o!==64)break;r.floorCents=t.int32();continue}case 9:{if(o!==72)break;r.floorSource=t.int32();continue}case 10:{if(o!==80)break;r.floorTreatmentBp=t.int32();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}};J={encode(i,e=new V){return i.bidder!==void 0&&i.bidder!==""&&e.uint32(10).string(i.bidder),i.cpm!==void 0&&i.cpm!==0&&e.uint32(17).double(i.cpm),i.currency!==void 0&&i.currency!==""&&e.uint32(26).string(i.currency),i.width!==void 0&&i.width!==0&&e.uint32(32).int32(i.width),i.height!==void 0&&i.height!==0&&e.uint32(40).int32(i.height),i.dealId!==void 0&&i.dealId!==""&&e.uint32(50).string(i.dealId),i.mediaType!==void 0&&i.mediaType!==""&&e.uint32(58).string(i.mediaType),i.latencyMs!==void 0&&i.latencyMs!==0&&e.uint32(65).double(i.latencyMs),i.advertiserDomain!==void 0&&i.advertiserDomain!==""&&e.uint32(74).string(i.advertiserDomain),i.creativeId!==void 0&&i.creativeId!==""&&e.uint32(82).string(i.creativeId),e},decode(i,e){let t=i instanceof R?i:new R(i),n=e===void 0?t.len:t.pos+e,r=xt();for(;t.pos<n;){let o=t.uint32();switch(o>>>3){case 1:{if(o!==10)break;r.bidder=t.string();continue}case 2:{if(o!==17)break;r.cpm=t.double();continue}case 3:{if(o!==26)break;r.currency=t.string();continue}case 4:{if(o!==32)break;r.width=t.int32();continue}case 5:{if(o!==40)break;r.height=t.int32();continue}case 6:{if(o!==50)break;r.dealId=t.string();continue}case 7:{if(o!==58)break;r.mediaType=t.string();continue}case 8:{if(o!==65)break;r.latencyMs=t.double();continue}case 9:{if(o!==74)break;r.advertiserDomain=t.string();continue}case 10:{if(o!==82)break;r.creativeId=t.string();continue}}if((o&7)===4||o===0)break;t.skip(o&7)}return r}}});function $(i){if(!i)return new Uint8Array(0);if(kt.test(i)){let t=i.replace(/-/g,""),n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}if(Ge)return Ge.encode(i);let e=new Uint8Array(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t)&255;return e}var kt,Ge,Pn,He=C(()=>{"use strict";kt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ge=typeof TextEncoder<"u"?new TextEncoder:null,Pn=typeof TextDecoder<"u"?new TextDecoder:null});function G(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return(i==="x"?e:e&3|8).toString(16)})}function Qt(i){let e="";for(let n=0;n<i.length;n+=8192)e+=String.fromCharCode(...i.subarray(n,n+8192));return btoa(e)}function Zt(i){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function Jt(i){if(!i)return!1;let e;try{e=new URL(i)}catch{return!1}return e.username||e.password?!1:e.protocol==="https:"?!0:e.protocol==="http:"?e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]":!1}function en(i){let e={},t=0;for(let n of Object.keys(i)){if(t>=Pt)break;let r=i[n];if(r==null)continue;let o=String(r);e[n]=o.length>Ye?`${o.slice(0,Ye)}...[truncated]`:o,t++}return e}function tn(i){let e=i.slice(te.length).split("_");return e.length===2&&/^\d+$/.test(e[0])}function nn(i,e){if(!i||!e)return!1;try{return new URL(i).origin===new URL(e).origin}catch{return!1}}function et(i){try{typeof localStorage<"u"&&(localStorage.setItem(Ze,i.toString()),q=i)}catch{}}function tt(i=Date.now()){return N>0&&i-N<=Je}function ne(){let i=Date.now(),e=!!x&&!tt(i);if(N=i,e){x=null;for(let t of sn)t();return}!K||!x||q===0||i-q<rn||et(i)}function dn(){return!x||K&&q===0}function an(){if(Qe||typeof window>"u")return;Qe=!0;let i=()=>ne();for(let e of on)window.addEventListener(e,i,{passive:!0,capture:!0});typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&ne()})}function me(){let i=Date.now(),e=!!x&&tt(i);try{if(K&&typeof localStorage<"u"){let t=localStorage.getItem(Xe),n=localStorage.getItem(Ze),r=n&&parseInt(n,10)||0;if(t&&r&&i-r<=Je)return(x!==t||N<r)&&(x=t,N=Math.max(N,r)),q===0&&(q=r),t;let o=e?x:G();return e||(N=i),localStorage.setItem(Xe,o),et(N),x=o,o}}catch{}return e||(x=G(),N=i),x}function f(i){return String(i??"").replace(/%/g,"%25").replace(/:/g,"%3A")}function cn(i,e){switch(i){case"auctionInit":return`auctionInit:${f(e?.auctionId)}`;case"auctionEnd":return`auctionEnd:${f(e?.auctionId)}`;case"bidRequested":{let t=Array.isArray(e?.bids)?e.bids.map(n=>f(n?.bidId||n?.transactionId||n?.adUnitCode)).join(","):"";return`bidRequested:${f(e?.auctionId)}:${f(e?.bidderCode||e?.bidder)}:${t}`}case"bidResponse":{let t=e||{},n=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidResponse:${f(t.auctionId)}:${f(t.adUnitCode)}:${f(t.bidderCode||t.bidder)}:${f(n)}:${f(r)}`}case"bidTimeout":return"bidTimeout:"+(Array.isArray(e)?e:e?[e]:[]).map(n=>`${f(n?.auctionId)}:${f(n?.bidderCode||n?.bidder)}:${f(n?.bidId||n?.transactionId||n?.adUnitCode)}`).join(",");case"bidWon":{let t=e||{},n=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidWon:${f(t.auctionId)}:${f(t.adUnitCode)}:${f(t.bidderCode||t.bidder)}:${f(n)}:${f(r)}`}case"noBid":return`noBid:${f(e?.auctionId)}:${f(e?.adUnitCode)}:${f(e?.bidderCode||e?.bidder)}:${f(e?.bidId||e?.transactionId)}`;case"adRenderFailed":{let t=e?.bid||{};return`adRenderFailed:${f(t.auctionId||e?.auctionId)}:${f(t.adUnitCode||e?.adUnitCode)}:${f(t.bidderCode||t.bidder||e?.bidderCode||e?.bidder)}:${f(e?.reason)}:${f(e?.message)}`}case"adRenderSucceeded":{let t=e?.bid||e||{},n=t.creativeId||t.adId||e?.adId||"",r=t.originalCpm??t.cpm??"";return`adRenderSucceeded:${f(t.auctionId||e?.auctionId)}:${f(t.adUnitCode||e?.adUnitCode)}:${f(t.bidderCode||t.bidder)}:${f(n)}:${f(r)}`}case"setTargeting":return`setTargeting:${Object.keys(e||{}).sort().map(f).join(",")}`;case"auctionDebug":return`auctionDebug:${f(e?.type)}:${f(String(e?.arguments?.[0]??"").slice(0,50))}`;default:return""}}function W(i){if(Number.isFinite(i?.width)&&Number.isFinite(i?.height))return{width:i.width,height:i.height};if(typeof i?.size=="string"){let e=i.size.match(/^(\d+)x(\d+)$/);if(e)return{width:Number(e[1]),height:Number(e[2])}}return{width:Number.isFinite(i?.width)?i.width:0,height:Number.isFinite(i?.height)?i.height:0}}function H(i,e=!0){if(!i)return null;if(Array.isArray(i)){let t=i.find(n=>n?.provider==="bidkernel")??(e?i.find(n=>n&&typeof n=="object"&&n.provider===void 0):void 0);return t?H(t,e):null}if(typeof i=="object"){if(i.options&&typeof i.options=="object")return i.options;if(i.config&&typeof i.config=="object")return i.config;if(i.propertyId||i.endpoint)return i}return null}function ln(i){if(!i)return null;if(i._bidkernelAnalyticsConfig){let e=H(i._bidkernelAnalyticsConfig);if(e)return e}if(i.bidkernelPrebidAnalytics){let e=i.bidkernelPrebidAnalytics;if(e.options){let t=H(e.options);if(t)return t}if(e.config){let t=H(e.config);if(t)return t}if(e.propertyId)return H(e)}return null}function Ee(i="pbjs",e){let t=typeof window<"u"?window:{};t[i]=t[i]||{};let n=t[i],r=s=>{let d=t._bidkernelPrebidAnalytics,a=d?.getEndpoint?.()||"",l={pbjsGlobalName:i,...e,...s};if(a&&!nn(l.endpoint||"",a)&&(Ie.warn(`Ignoring analytics endpoint change to ${l.endpoint||"(empty)"}: this page is pinned to ${a}. Reload to change the ingest endpoint.`),l.endpoint=a),d)try{d.disable()}catch(g){Ie.warn("Failed to disable previous analytics instance:",g)}let c=new S(l);return c.enable(),t._bidkernelPrebidAnalytics=c,c},o=()=>{try{n.adapterManager&&typeof n.adapterManager.registerAnalyticsAdapter=="function"&&n.adapterManager.registerAnalyticsAdapter({adapter:{enableAnalytics:d=>{let a=H(d,!Array.isArray(d));a&&r(a)},disableAnalytics:()=>{t._bidkernelPrebidAnalytics&&t._bidkernelPrebidAnalytics.disable()}},code:"bidkernel"});let s=ln(t);s&&(s.propertyId||e?.propertyId)&&r(s)}catch(s){Ie.warn("Failed to register standard Prebid analytics adapter:",s)}};n.adapterManager&&typeof n.adapterManager.registerAnalyticsAdapter=="function"?o():(n.que=n.que||[],n.que.push(o))}var Ke,Ut,z,Mt,Nt,be,Ye,Pt,ze,te,Ft,Vt,$t,Wt,jt,qt,j,Gt,Ht,Kt,Yt,zt,Xt,Xe,Ze,Je,x,N,K,rn,q,on,Qe,sn,ve,S,Ie,Te=C(()=>{"use strict";Ce();ge();He();Ke=1e4,Ut=50,z=200,Mt=300*1e3,Nt=10,be=32*1024,Ye=1024,Pt=16,ze="text/plain",te="_bidkernel_pending_",Ft=20,Vt=7200*1e3,$t=1e4,Wt={auctionStart:m.AUCTION_START,auctionEnd:m.AUCTION_END,bidWin:m.BID_WIN,adRenderFailed:m.AD_RENDER_FAILED,click:m.CLICK,impression:m.IMPRESSION,timeInView:m.TIME_IN_VIEW,viewable:m.VIEWABLE},jt=3e3,qt=new Set([m.IMPRESSION,m.BID_WIN,m.CLICK]),j=1800*1e3,Gt=200,Ht=1e3,Kt=50,Yt=200,zt={static:ee.FLOOR_SOURCE_STATIC,pool:ee.FLOOR_SOURCE_POOL,none:ee.FLOOR_SOURCE_NONE},Xt=1e3,Xe="_bidkernel_session",Ze="_bidkernel_session_ts",Je=1800*1e3,x=null,N=0,K=!0;rn=60*1e3,q=0,on=["pointerdown","pointermove","keydown","scroll","wheel","touchstart"],Qe=!1,sn=new Set;ve=class{seenObjects=new WeakMap;seenKeys=new Set;isDuplicate(e,t){if(!t)return!1;if(typeof t=="object"){let r=this.seenObjects.get(t);if(r){if(r.has(e))return!0;r.add(e)}else this.seenObjects.set(t,new Set([e]))}let n=cn(e,t);if(n){if(this.seenKeys.has(n))return!0;if(this.seenKeys.size>=1e3){let r=this.seenKeys.values().next().value;r!==void 0&&this.seenKeys.delete(r)}this.seenKeys.add(n)}return!1}};S=class i{static activeInstances=new Set;static getActiveInstances(){return i.activeInstances}static setStorageAllowed(e){K=e,q=0}static isStorageAllowed(){return K}config;queue=[];errorCount=0;flushTimer=null;boundFlushBeacon;boundVisibilityChange;isEnabled=!1;boundPbjsHandlers=[];pageUrl="";deduper=new ve;consecutiveSendFailures=0;nextSendAllowedAt=0;replayedEventCount=0;revenueFlushTimer=null;persistedBatchKeys=[];persistedCleanupTimer=null;intersectionObserver=null;slotViewabilityRecords=new Map;elementToSlotId=new Map;slotRefreshIndices=new Map;slotLastAuctionIds=new Map;pendingThresholdListeners=new Map;pendingViewableListeners=new Map;slotElements=new Map;clickDetachCleanups=new Set;lastClickAt=new Map;slotEmittedImpressionKeys=new Set;cachedWinningBids=new Map;videoDetachCleanups=new Set;auctionBidderOutcomes=new Map;floorDecisions=new Map;logger;managesSessionId;constructor(e){e.storageAllowed!==void 0&&i.setStorageAllowed(e.storageAllowed);let t=e.endpoint||"",n=!t||Jt(t)?t:"";this.config={endpoint:n,propertyId:e.propertyId||"",pageviewId:e.pageviewId||G(),sessionId:e.sessionId||"",userId:e.userId||"",deviceType:e.deviceType||"desktop",country:e.country||"",region:e.region||"",auctionEnabled:e.auctionEnabled??!0,warningsEnabled:e.warningsEnabled??!0,errorsEnabled:e.errorsEnabled??!0,viewabilityEnabled:e.viewabilityEnabled??!0,storageAllowed:e.storageAllowed??!0,logLevel:e.logLevel||"INFO",pbjsGlobalName:e.pbjsGlobalName||"pbjs",attachPbjsListeners:e.attachPbjsListeners??!0,revenueFlushDelayMs:Number.isFinite(e.revenueFlushDelayMs)&&e.revenueFlushDelayMs>=0?e.revenueFlushDelayMs:jt},this.logger=oe({prefix:"[bidkernel][prebid-analytics]",logLevel:this.config.logLevel}),ne(),this.managesSessionId=!e.sessionId,this.managesSessionId&&(this.config.sessionId=me()),t&&!n&&this.log("ERROR",`Rejected untrusted analytics endpoint ${t}: must be an absolute https:// URL without embedded credentials. Events will not be transmitted.`),this.boundFlushBeacon=()=>{this.flushAllSlotsTimeInView(),this.flushBeacon()},this.boundVisibilityChange=()=>this.handleVisibilityChange()}enable(){if(!this.isEnabled){if(this.isEnabled=!0,i.activeInstances.add(this),this.logger.setLevel(this.config.logLevel),this.config.endpoint||this.log("WARN","Endpoint is empty. Analytics events will not be transmitted."),this.config.viewabilityEnabled&&typeof IntersectionObserver<"u"){this.intersectionObserver=new IntersectionObserver(this.handleIntersection.bind(this),{threshold:[.5]});for(let e of this.slotViewabilityRecords.values())e.element&&this.intersectionObserver.observe(e.element)}if(this.config.attachPbjsListeners&&this.attachPbjs(),typeof window<"u"){if(!this.pageUrl)try{let e=new URL(window.location.href);this.pageUrl=e.origin+e.pathname}catch{this.pageUrl=window.location.href}window.addEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.addEventListener("visibilitychange",this.boundVisibilityChange),an(),this.flushTimer=setInterval(()=>this.flush(),Ke),this.resendPersistedBatches()}}}attachPbjs(){if(!this.isEnabled)return!1;if(this.boundPbjsHandlers.length>0)return!0;let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.onEvent!="function")return this.log("WARN","pbjs.onEvent is not defined. Prebid analytics will not function."),!1;this.log("DEBUG","Attaching event listeners to pbjs");let n={auctionInit:this.handleAuctionInit.bind(this),auctionEnd:this.handleAuctionEnd.bind(this),bidRequested:this.handleBidRequested.bind(this),bidResponse:this.handleBidResponse.bind(this),bidTimeout:this.handleBidTimeout.bind(this),bidWon:this.handleBidWon.bind(this),noBid:this.handleNoBid.bind(this),adRenderFailed:this.handleAdRenderFailed.bind(this),adRenderSucceeded:this.handleAdRenderSucceeded.bind(this)};for(let[r,o]of Object.entries(n))t.onEvent(r,o),this.boundPbjsHandlers.push({event:r,handler:o});if(typeof t.getEvents=="function")try{let r=t.getEvents();if(Array.isArray(r)){let o=r.slice(this.replayedEventCount);if(this.replayedEventCount=r.length,o.length>0){this.log("DEBUG",`Replaying ${o.length} historical events from pbjs.getEvents()`);for(let s of o){if(!s)continue;let d=s.eventType||s.event||s.name,a=s.args!==void 0?s.args:s.data!==void 0?s.data:s,l=n[d];l&&l(a)}}}}catch(r){this.log("WARN","Failed to replay historical events from pbjs.getEvents()",r)}return!0}disable(){if(this.isEnabled){this.flushAllSlotsTimeInView(),this.isEnabled=!1,i.activeInstances.delete(this);for(let e of this.slotViewabilityRecords.values()){e.dwellTimer&&(clearTimeout(e.dwellTimer),e.dwellTimer=null,e.dwellStartedAt=null);for(let t of e.thresholdListeners)t.timer&&(clearTimeout(t.timer),t.timer=null)}this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.slotViewabilityRecords.clear(),this.elementToSlotId.clear();for(let e of this.videoDetachCleanups)try{e()}catch{}this.videoDetachCleanups.clear();for(let e of Array.from(this.clickDetachCleanups))try{e()}catch{}if(this.clickDetachCleanups.clear(),this.slotElements.clear(),this.cachedWinningBids.clear(),this.slotEmittedImpressionKeys.clear(),this.slotLastAuctionIds.clear(),this.auctionBidderOutcomes.clear(),this.floorDecisions.clear(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.revenueFlushTimer&&(clearTimeout(this.revenueFlushTimer),this.revenueFlushTimer=null),this.persistedCleanupTimer&&(clearTimeout(this.persistedCleanupTimer),this.persistedCleanupTimer=null),typeof window<"u"&&(window.removeEventListener("pagehide",this.boundFlushBeacon),typeof document<"u"&&document.removeEventListener("visibilitychange",this.boundVisibilityChange)),this.boundPbjsHandlers.length>0){let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.offEvent=="function")for(let{event:n,handler:r}of this.boundPbjsHandlers)t.offEvent(n,r);this.boundPbjsHandlers=[]}this.flush()}}handleVisibilityChange(){if(!(typeof document>"u")){if(document.visibilityState==="hidden"){let e=typeof performance<"u"&&performance.now?performance.now():Date.now();for(let t of this.slotViewabilityRecords.values()){t.inView&&t.lastEnteredViewAt!==null&&(t.accumulatedTimeInViewMs+=Math.max(0,e-t.lastEnteredViewAt),t.lastEnteredViewAt=null,this.checkThresholdListeners(t)),t.dwellTimer&&(clearTimeout(t.dwellTimer),t.dwellTimer=null,t.dwellStartedAt=null);for(let r of t.thresholdListeners)r.timer&&(clearTimeout(r.timer),r.timer=null);let n=Math.round(t.accumulatedTimeInViewMs);n>0&&this.enqueue(m.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:n,bid:t.bidPayload,metadata:{...t.metadata,refresh_index:String(t.refreshIndex)}})}this.flushBeacon()}else if(document.visibilityState==="visible"){let e=typeof performance<"u"&&performance.now?performance.now():Date.now();for(let t of this.slotViewabilityRecords.values())if(t.inView){if(t.lastEnteredViewAt=e,!t.viewableFired&&t.dwellTimer===null){let n=t.mediaType==="video"?2e3:1e3;t.dwellStartedAt=e,t.dwellTimer=setTimeout(()=>{this.handleDwellComplete(t)},n)}this.scheduleThresholdTimers(t)}}}}handleIntersection(e){for(let t of e){let n=this.elementToSlotId.get(t.target);if(!n){for(let a of i.activeInstances)if(a!==this&&a.elementToSlotId.has(t.target)){a.handleIntersection([t]);break}continue}let r=this.slotViewabilityRecords.get(n);if(!r)continue;let o=t.isIntersecting&&(t.intersectionRatio===void 0||t.intersectionRatio>=.5),s=typeof document>"u"||document.visibilityState==="visible",d=typeof performance<"u"&&performance.now?performance.now():Date.now();if(o){if(!r.inView&&(r.inView=!0,s)){if(r.lastEnteredViewAt=d,!r.viewableFired&&r.dwellTimer===null){let a=r.mediaType==="video"?2e3:1e3;r.dwellStartedAt=d,r.dwellTimer=setTimeout(()=>{this.handleDwellComplete(r)},a)}this.scheduleThresholdTimers(r)}}else{r.inView&&(r.lastEnteredViewAt!==null&&(r.accumulatedTimeInViewMs+=Math.max(0,d-r.lastEnteredViewAt),r.lastEnteredViewAt=null),r.inView=!1,this.checkThresholdListeners(r)),r.dwellTimer!==null&&(clearTimeout(r.dwellTimer),r.dwellTimer=null,r.dwellStartedAt=null);for(let a of r.thresholdListeners)a.timer&&(clearTimeout(a.timer),a.timer=null)}}}handleDwellComplete(e){e.dwellTimer=null,e.dwellStartedAt=null,e.inView&&(typeof document<"u"&&document.visibilityState==="hidden"||(e.viewableFired||(e.viewableFired=!0,this.enqueue(m.VIEWABLE,"viewable",{auctionId:e.auctionId,transactionId:e.transactionId,adUnitCode:e.adUnitCode,bid:e.bidPayload,metadata:{...e.metadata,refresh_index:String(e.refreshIndex)}})),this.notifyViewable(e)))}notifyViewable(e){if(e.viewableFired){for(let t of e.viewableListeners)if(t.firedForIndex!==e.refreshIndex){t.firedForIndex=e.refreshIndex;try{t.callback(e.slotId)}catch(n){this.log("ERROR","Error in viewable listener callback",n)}}}}setSlotElement(e,t){this.slotElements.set(e,t);let n=this.slotViewabilityRecords.get(e);n&&n.element!==t&&this.observeSlot(t,e,{refreshIndex:n.refreshIndex})}recordClick(e,t){if(!this.isEnabled||!e)return!1;let n=Date.now();if(n-(this.lastClickAt.get(e)||0)<Xt)return!1;this.lastClickAt.set(e,n);let r=this.getCachedBid(e);return this.enqueue(m.CLICK,"click",{auctionId:r?.auctionId||"",transactionId:r?.transactionId||"",adUnitCode:e,bid:r?.bidTrace,metadata:{...t?.metadata,refresh_index:String(this.getRefreshIndex(e))}}),!0}attachClickTracker(e,t){if(typeof window>"u")return()=>{};let n=()=>{setTimeout(()=>{let o=document.activeElement;o&&(o===e||e.contains(o))&&(this.recordClick(t,{metadata:{source:"blur"}}),window.focus())},0)};window.addEventListener("blur",n);let r=()=>{window.removeEventListener("blur",n),this.clickDetachCleanups.delete(r)};return this.clickDetachCleanups.add(r),r}onViewable(e,t){let n={callback:t,firedForIndex:-1},r=this.slotViewabilityRecords.get(e);return r?(r.viewableListeners.add(n),this.notifyViewable(r)):(this.pendingViewableListeners.has(e)||this.pendingViewableListeners.set(e,new Set),this.pendingViewableListeners.get(e).add(n)),()=>{this.slotViewabilityRecords.get(e)?.viewableListeners.delete(n),this.pendingViewableListeners.get(e)?.delete(n)}}scheduleThresholdTimers(e){if(!e.inView||typeof document<"u"&&document.visibilityState==="hidden")return;let t=this.getCurrentTimeInView(e);for(let n of e.thresholdListeners)if(!n.fired)if(t>=n.thresholdMs){n.fired=!0,n.timer&&(clearTimeout(n.timer),n.timer=null);try{n.callback(e.slotId,t)}catch(r){this.log("ERROR","Error in threshold listener callback",r)}}else{n.timer&&clearTimeout(n.timer);let r=n.thresholdMs-t;n.timer=setTimeout(()=>{if(n.timer=null,!n.fired&&e.inView&&(typeof document>"u"||document.visibilityState==="visible")){let o=this.getCurrentTimeInView(e);if(o>=n.thresholdMs){n.fired=!0;try{n.callback(e.slotId,o)}catch(s){this.log("ERROR","Error in threshold listener callback",s)}}}},r)}}checkThresholdListeners(e){let t=this.getCurrentTimeInView(e);for(let n of e.thresholdListeners)if(!n.fired&&t>=n.thresholdMs){n.fired=!0,n.timer&&(clearTimeout(n.timer),n.timer=null);try{n.callback(e.slotId,t)}catch(r){this.log("ERROR","Error in threshold listener callback",r)}}}getCurrentTimeInView(e){let t=e.accumulatedTimeInViewMs;if(e.inView&&e.lastEnteredViewAt!==null){let n=typeof performance<"u"&&performance.now?performance.now():Date.now();t+=Math.max(0,n-e.lastEnteredViewAt)}return t}flushSlotTimeInView(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;if(t.inView&&t.lastEnteredViewAt!==null){let r=typeof performance<"u"&&performance.now?performance.now():Date.now();t.accumulatedTimeInViewMs+=Math.max(0,r-t.lastEnteredViewAt),t.lastEnteredViewAt=null}let n=Math.round(t.accumulatedTimeInViewMs);n>0&&this.enqueue(m.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:n,bid:t.bidPayload,metadata:{...t.metadata,refresh_index:String(t.refreshIndex)}}),t.accumulatedTimeInViewMs=0}flushAllSlotsTimeInView(){for(let e of Array.from(this.slotViewabilityRecords.keys()))this.flushSlotTimeInView(e)}observeSlot(e,t,n){if(!this.config.viewabilityEnabled)return;let r=null;if(typeof e=="string"){if(typeof document<"u"){try{r=document.querySelector(e)||document.getElementById(e)}catch{r=document.getElementById(e)}r||(r=document.getElementById(e))}}else r=e;let o=t||n?.adUnitCode||(r?r.id:"")||G(),s=this.slotViewabilityRecords.get(o);if(s){if(n?.refreshIndex===void 0||n.refreshIndex>s.refreshIndex){this.flushSlotTimeInView(o);let a=n?.refreshIndex!==void 0?n.refreshIndex:(this.slotRefreshIndices.get(o)??s.refreshIndex)+1;this.slotRefreshIndices.set(o,a),s.dwellTimer&&(clearTimeout(s.dwellTimer),s.dwellTimer=null,s.dwellStartedAt=null);for(let c of s.thresholdListeners)c.fired=!1,c.timer&&(clearTimeout(c.timer),c.timer=null);s.viewableFired=!1,s.accumulatedTimeInViewMs=0;let l=typeof performance<"u"&&performance.now?performance.now():Date.now();if(s.lastEnteredViewAt=s.inView?l:null,s.refreshIndex=a,s.auctionId=n?.auctionId||s.auctionId,s.transactionId=n?.transactionId||s.transactionId,s.mediaType=n?.mediaType||s.mediaType||"banner",s.bidPayload=n?.bid!==void 0?n.bid:s.bidPayload,s.metadata=n?.metadata??s.metadata,s.inView&&(typeof document>"u"||document.visibilityState==="visible")){let c=s.mediaType==="video"?2e3:1e3;s.dwellStartedAt=l,s.dwellTimer=setTimeout(()=>{this.handleDwellComplete(s)},c),this.scheduleThresholdTimers(s)}}else s.auctionId=n?.auctionId||s.auctionId,s.transactionId=n?.transactionId||s.transactionId,s.mediaType=n?.mediaType||s.mediaType,n?.bid!==void 0&&(s.bidPayload=n.bid),n?.metadata!==void 0&&(s.metadata=n.metadata);n?.auctionId&&this.slotLastAuctionIds.set(o,n.auctionId),r&&(s.element&&s.element!==r&&this.intersectionObserver&&(this.intersectionObserver.unobserve(s.element),this.elementToSlotId.delete(s.element)),s.element=r,this.elementToSlotId.set(r,o),this.intersectionObserver?.observe(r))}else{let d=n?.refreshIndex??this.slotRefreshIndices.get(o)??0;this.slotRefreshIndices.set(o,d),n?.auctionId&&this.slotLastAuctionIds.set(o,n.auctionId);let a=this.pendingThresholdListeners.get(o)||new Set;this.pendingThresholdListeners.delete(o);let l=this.pendingViewableListeners.get(o)||new Set;this.pendingViewableListeners.delete(o);let c={slotId:o,element:r,adUnitCode:n?.adUnitCode||o,auctionId:n?.auctionId||"",transactionId:n?.transactionId||"",mediaType:n?.mediaType||"banner",bidPayload:n?.bid,metadata:n?.metadata,refreshIndex:d,inView:!1,lastEnteredViewAt:null,accumulatedTimeInViewMs:0,viewableFired:!1,dwellTimer:null,dwellStartedAt:null,thresholdListeners:a,viewableListeners:l};this.slotViewabilityRecords.set(o,c),r&&(this.elementToSlotId.set(r,o),this.intersectionObserver?.observe(r))}}unobserveSlot(e){let t=this.slotViewabilityRecords.get(e);if(t){this.flushSlotTimeInView(e),t.dwellTimer&&(clearTimeout(t.dwellTimer),t.dwellTimer=null,t.dwellStartedAt=null);for(let n of t.thresholdListeners)n.timer&&(clearTimeout(n.timer),n.timer=null);t.thresholdListeners=new Set,t.viewableListeners=new Set,t.element&&this.intersectionObserver&&(this.intersectionObserver.unobserve(t.element),this.elementToSlotId.delete(t.element),t.element=null),t.inView=!1,t.lastEnteredViewAt=null}}destroySlot(e){this.unobserveSlot(e),this.slotViewabilityRecords.delete(e),this.slotRefreshIndices.delete(e),this.slotLastAuctionIds.delete(e),this.pendingThresholdListeners.delete(e),this.pendingViewableListeners.delete(e);let t=`${f(e)}:`;for(let r of Array.from(this.slotEmittedImpressionKeys))(r===e||r.startsWith(t))&&this.slotEmittedImpressionKeys.delete(r);let n=this.cachedWinningBids.get(e);n&&this.deleteCachedBidEntry(n)}getCachedBid(e){let t=this.cachedWinningBids.get(e);if(t){if(Date.now()-t.timestamp>j){this.deleteCachedBidEntry(t);return}return t}}deleteCachedBidEntry(e){for(let[t,n]of Array.from(this.cachedWinningBids))n===e&&this.cachedWinningBids.delete(t)}pruneCachedWinningBids(){let e=Date.now();for(let[t,n]of Array.from(this.cachedWinningBids))e-n.timestamp>j&&this.cachedWinningBids.delete(t);for(;this.cachedWinningBids.size>Gt;){let t=this.cachedWinningBids.keys().next();if(t.done)break;this.cachedWinningBids.delete(t.value)}}addImpressionKey(e){if(!this.slotEmittedImpressionKeys.has(e)){for(;this.slotEmittedImpressionKeys.size>=Ht;){let t=this.slotEmittedImpressionKeys.values().next();if(t.done)break;this.slotEmittedImpressionKeys.delete(t.value)}this.slotEmittedImpressionKeys.add(e)}}getOrCreateAuctionOutcomes(e){let t=this.auctionBidderOutcomes.get(e);for(t||(t=new Map,this.auctionBidderOutcomes.set(e,t));this.auctionBidderOutcomes.size>Kt;){let n=this.auctionBidderOutcomes.keys().next();if(n.done||n.value===e)break;this.auctionBidderOutcomes.delete(n.value)}return t}hasImpressionEmitted(e,t,n,r){let o=t??this.slotRefreshIndices.get(e)??0,s=`${f(e)}:${o}`;return r?n?this.slotEmittedImpressionKeys.has(`${s}:auc:${f(n)}:${f(r)}`)||this.slotEmittedImpressionKeys.has(`${s}:${f(r)}`):this.slotEmittedImpressionKeys.has(`${s}:${f(r)}`):n?this.slotEmittedImpressionKeys.has(`${s}:auc:${f(n)}`):this.slotEmittedImpressionKeys.has(s)}markImpressionEmitted(e,t,n,r){let o=`${f(e)}:${t}`;this.addImpressionKey(o),r&&this.addImpressionKey(`${o}:${f(r)}`),n&&(this.addImpressionKey(`${o}:auc:${f(n)}`),r&&this.addImpressionKey(`${o}:auc:${f(n)}:${f(r)}`))}recordImpression(e,t){if(!this.isEnabled)return!1;let n=e||t?.adUnitCode||"",r=t?.adUnitCode||n,o=(t?.auctionId&&n?this.getCachedBid(`${t.auctionId}:${n}`):void 0)||(t?.auctionId&&r?this.getCachedBid(`${t.auctionId}:${r}`):void 0)||(n?this.getCachedBid(n):void 0)||(r?this.getCachedBid(r):void 0),s=t?.bid||o?.rawBid||{},d=t?.auctionId||s.auctionId||o?.auctionId||"",a=t?.transactionId||s.transactionId||o?.transactionId||"",l=s.creativeId||o?.bidTrace?.creativeId||t?.bid?.creativeId||"",c=t?.mediaType||s.mediaType||o?.bidTrace?.mediaType||"banner",g=n||r,h=(n?this.slotViewabilityRecords.get(n):void 0)||(r?this.slotViewabilityRecords.get(r):void 0),I=g?this.slotLastAuctionIds.get(g)||(h?h.auctionId:void 0):void 0,A=!!(g&&d&&I&&I!==d&&t?.refreshIndex===void 0),p={bidder:s.bidderCode||s.bidder||o?.bidTrace?.bidder||"",cpm:Number.isFinite(s.originalCpm)?s.originalCpm:Number.isFinite(s.cpm)?s.cpm:o?.bidTrace?.cpm??0,currency:s.originalCurrency??s.currency??o?.bidTrace?.currency??"USD",...W(s).width?W(s):o?.bidTrace?{width:o.bidTrace.width,height:o.bidTrace.height}:W(s),dealId:s.dealId||o?.bidTrace?.dealId||"",mediaType:c,latencyMs:Number.isFinite(s.timeToRespond)?s.timeToRespond:o?.bidTrace?.latencyMs??0,advertiserDomain:s.meta?.advertiserDomains?.[0]||o?.bidTrace?.advertiserDomain||"",creativeId:s.creativeId||o?.bidTrace?.creativeId||""};if(A&&g){this.flushSlotTimeInView(g);let B=(this.slotRefreshIndices.get(g)??(h?h.refreshIndex:0))+1;this.slotRefreshIndices.set(g,B),this.slotLastAuctionIds.set(g,d),h&&(h.refreshIndex=B,h.auctionId=d,h.transactionId=a,h.bidPayload=p,h.viewableFired=!1,h.accumulatedTimeInViewMs=0)}else g&&(d&&this.slotLastAuctionIds.set(g,d),this.slotRefreshIndices.has(g)||this.slotRefreshIndices.set(g,0));let T=t?.refreshIndex??(n?this.slotRefreshIndices.get(n)??(r?this.slotRefreshIndices.get(r):void 0)??(h?h.refreshIndex:0):0);return n&&this.hasImpressionEmitted(n,T,d,l)||r&&r!==n&&this.hasImpressionEmitted(r,T,d,l)?(this.log("DEBUG",`Impression already emitted for slot ${n||r} in cycle ${T}`),!1):(n&&this.markImpressionEmitted(n,T,d,l),r&&r!==n&&this.markImpressionEmitted(r,T,d,l),this.enqueue(m.IMPRESSION,"impression",{auctionId:d,transactionId:a,adUnitCode:r,bid:p,metadata:{...t?.metadata,refresh_index:String(T)}}),h&&(!h.bidPayload&&p&&(h.bidPayload=p),!h.auctionId&&d&&(h.auctionId=d),!h.transactionId&&a&&(h.transactionId=a)),!0)}onTimeInViewThreshold(e,t,n){let r={thresholdMs:t,callback:n,timer:null,fired:!1},o=this.slotViewabilityRecords.get(e);if(o){o.thresholdListeners.add(r);let s=this.getCurrentTimeInView(o);if(s>=t){r.fired=!0;try{n(e,s)}catch(d){this.log("ERROR","Error in threshold callback",d)}}else if(o.inView&&(typeof document>"u"||document.visibilityState==="visible")){let d=t-s;r.timer=setTimeout(()=>{if(r.timer=null,!r.fired&&o.inView&&(typeof document>"u"||document.visibilityState==="visible")){let a=this.getCurrentTimeInView(o);if(a>=t){r.fired=!0;try{n(e,a)}catch(l){this.log("ERROR","Error in threshold callback",l)}}}},d)}}else this.pendingThresholdListeners.has(e)||this.pendingThresholdListeners.set(e,new Set),this.pendingThresholdListeners.get(e).add(r);return()=>{r.timer&&(clearTimeout(r.timer),r.timer=null),o&&o.thresholdListeners.delete(r);let s=this.pendingThresholdListeners.get(e);s&&s.delete(r)}}getViewabilityState(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;let n=Math.round(this.getCurrentTimeInView(t));return{inView:t.inView,viewable:t.viewableFired,timeInViewMs:n,refreshIndex:t.refreshIndex}}getEndpoint(){return this.config.endpoint}getRefreshIndex(e){return this.slotRefreshIndices.get(e)??0}triggerSlotRefresh(e,t){let n=this.slotViewabilityRecords.get(e);n&&n.element&&this.observeSlot(n.element,e,t)}trackRawEvent(e,t,n){let r=Wt[t]??(e==="ERROR"?m.ERROR:void 0);r!==void 0&&this.enqueue(r,t,n,e)}recordFloorDecision(e,t,n){if(!e||!t)return;let r=`${e}:${t}`;for(this.floorDecisions.delete(r),this.floorDecisions.set(r,{floorCents:n.floorCents!==void 0&&Number.isFinite(n.floorCents)?Math.round(n.floorCents):void 0,source:n.source,treatment:Number.isFinite(n.treatment)?n.treatment:1});this.floorDecisions.size>Yt;){let o=this.floorDecisions.keys().next();if(o.done)break;this.floorDecisions.delete(o.value)}}floorDecisionFor(e,t){return e&&t?this.floorDecisions.get(`${e}:${t}`):void 0}setUserId(e){this.config.userId=e}setSessionId(e){this.config.sessionId=e,this.managesSessionId=!e,this.managesSessionId&&(this.config.sessionId=me())}navigate(e,t){if(this.disable(),this.slotRefreshIndices.clear(),this.floorDecisions.clear(),this.pendingThresholdListeners.clear(),this.config.pageviewId=e||G(),t)try{let n=new URL(t);this.pageUrl=n.origin+n.pathname}catch{this.pageUrl=t}else this.pageUrl="";this.logger.resetTiming(),ne(),this.enable()}handleAuctionInit(e){if(this.isDuplicate("auctionInit",e))return;this.log("DEBUG","auctionInit",e);let t=e.auctionId||"";t&&(this.auctionBidderOutcomes.delete(t),this.getOrCreateAuctionOutcomes(t)),this.enqueue(m.AUCTION_START,"auctionStart",{auctionId:t,transactionId:e.transactionId||""})}handleAuctionEnd(e){if(this.isDuplicate("auctionEnd",e))return;this.log("DEBUG","auctionEnd",e);let t=e.auctionId||"",n=t?this.auctionBidderOutcomes.get(t):void 0,r=n?Array.from(n.values()):[];t&&this.auctionBidderOutcomes.delete(t),this.enqueue(m.AUCTION_END,"auctionEnd",{auctionId:t,transactionId:e.transactionId||"",bidderOutcomes:r})}auctionCycleIndex(e){if(!e)return 0;let t=this.slotRefreshIndices.get(e)??this.slotViewabilityRecords.get(e)?.refreshIndex;return t===void 0?0:t+1}handleBidRequested(e){if(this.isDuplicate("bidRequested",e))return;this.log("DEBUG","bidRequested",e);let t=e.auctionId||"",n=e.bidderCode||e.bidder||"";if(!t||!n)return;let r=this.getOrCreateAuctionOutcomes(t);Array.isArray(e.bids)&&e.bids.forEach(o=>{let s=o.adUnitCode||"",d=Object.keys(o.mediaTypes||{}),a=d.length>0?d[0]:o.mediaType||"banner",l=`${n}:${s}`;r.has(l)||r.set(l,{adUnitCode:s,outcome:M.BIDDER_OUTCOME_NO_RESPONSE,bid:{bidder:n,mediaType:a,latencyMs:0}})})}handleBidResponse(e){if(this.isDuplicate("bidResponse",e))return;this.log("DEBUG","bidResponse",e);let t=e.auctionId||"",n=e.bidderCode||e.bidder||"",r=e.adUnitCode||"",o=Number.isFinite(e.originalCpm)?e.originalCpm:Number.isFinite(e.cpm)?e.cpm:0,s=Number.isFinite(e.timeToRespond)?e.timeToRespond:0,d=Object.keys(e.mediaTypes||{}),a=e.mediaType||(e.mediaTypes?.video?"video":d.length>0?d[0]:"banner");if(!t||!n)return;let l=o>0?{bidder:n,cpm:o,currency:e.originalCurrency??e.currency??"USD",...W(e),dealId:e.dealId||"",mediaType:a,latencyMs:s,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""}:{bidder:n,mediaType:a,latencyMs:s};this.getOrCreateAuctionOutcomes(t).set(`${n}:${r}`,{adUnitCode:r,outcome:o>0?M.BIDDER_OUTCOME_BID:M.BIDDER_OUTCOME_NO_BID,bid:l})}handleBidTimeout(e){if(this.isDuplicate("bidTimeout",e))return;this.log("DEBUG","bidTimeout",e);let t=Array.isArray(e)?e:e?[e]:[];for(let n of t){let r=n.auctionId||"",o=n.bidderCode||n.bidder||"",s=n.adUnitCode||"",d=Number.isFinite(n.timeout)?n.timeout:0;if(r&&o){let a=this.getOrCreateAuctionOutcomes(r),l=`${o}:${s}`,c=a.get(l);c?(c.outcome=M.BIDDER_OUTCOME_TIMEOUT,d>0&&c.bid&&(c.bid.latencyMs=d)):a.set(l,{adUnitCode:s,outcome:M.BIDDER_OUTCOME_TIMEOUT,bid:{bidder:o,mediaType:"banner",latencyMs:d}})}}}handleBidWon(e){if(this.isDuplicate("bidWon",e))return;this.log("DEBUG","bidWon",e);let t=e.auctionId||"",n=e.transactionId||"",r=e.adUnitCode||e.adId||"",o=Object.keys(e.mediaTypes||{}),s=e.mediaType||(e.mediaTypes?.video?"video":o.length>0?o[0]:"banner"),d={bidder:e.bidderCode||e.bidder||"",cpm:Number.isFinite(e.originalCpm)?e.originalCpm:Number.isFinite(e.cpm)?e.cpm:0,currency:e.originalCurrency??e.currency??"USD",...W(e),dealId:e.dealId||"",mediaType:s,latencyMs:Number.isFinite(e.timeToRespond)?e.timeToRespond:0,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""};if(r){let a={bidTrace:d,auctionId:t,transactionId:n,adUnitCode:r,rawBid:e,timestamp:Date.now()};this.cachedWinningBids.set(r,a),e.adId&&e.adId!==r&&this.cachedWinningBids.set(e.adId,a),t&&(this.cachedWinningBids.set(`${t}:${r}`,a),e.adId&&e.adId!==r&&this.cachedWinningBids.set(`${t}:${e.adId}`,a)),this.pruneCachedWinningBids()}this.enqueue(m.BID_WIN,"bidWon",{auctionId:t,transactionId:n,adUnitCode:r,bid:d})}handleNoBid(e){if(this.isDuplicate("noBid",e))return;this.log("DEBUG","noBid",e);let t=e.auctionId||"",n=e.bidderCode||e.bidder||"",r=e.adUnitCode||"";if(t&&n){let o=this.getOrCreateAuctionOutcomes(t),s=`${n}:${r}`,d=o.get(s);d?d.outcome===M.BIDDER_OUTCOME_NO_RESPONSE&&(d.outcome=M.BIDDER_OUTCOME_NO_BID):o.set(s,{adUnitCode:r,outcome:M.BIDDER_OUTCOME_NO_BID,bid:{bidder:n,mediaType:"banner",latencyMs:0}})}}handleAdRenderFailed(e){if(this.isDuplicate("adRenderFailed",e))return;this.log("DEBUG","adRenderFailed",e);let t=e.bid||{};this.enqueue(m.AD_RENDER_FAILED,"adRenderFailed",{auctionId:t.auctionId||e.auctionId||"",transactionId:t.transactionId||e.transactionId||"",adUnitCode:t.adUnitCode||e.adUnitCode||"",bid:{bidder:t.bidderCode||t.bidder||e.bidderCode||e.bidder||""},metadata:{reason:String(e.reason||""),message:String(e.message||e.error?.message||"")},error:e.error||(e.message?new Error(String(e.message)):void 0)})}handleAdRenderSucceeded(e){if(this.isDuplicate("adRenderSucceeded",e))return;this.log("DEBUG","adRenderSucceeded",e);let t=e.bid||e||{},n=e.adUnitCode||t.adUnitCode||e.adId||t.adId||"",r=t.auctionId||e.auctionId||"",o=t.transactionId||e.transactionId||"",s=t.mediaType||"banner",d=e.adUnitCode||t.adUnitCode||"",a=e.adId||t.adId||"",l=(r&&d?this.getCachedBid(`${r}:${d}`):void 0)||(r&&a?this.getCachedBid(`${r}:${a}`):void 0)||(d?this.getCachedBid(d):void 0)||(a?this.getCachedBid(a):void 0),c=s==="video"||t.mediaType==="video"||t.mediaTypes?.video!==void 0||l?.bidTrace?.mediaType==="video"||l?.rawBid?.mediaType==="video"||n&&this.slotViewabilityRecords.get(n)?.mediaType==="video",g=c?"video":s||l?.bidTrace?.mediaType||"banner",h={bidder:t.bidderCode||t.bidder||l?.bidTrace?.bidder||"",cpm:Number.isFinite(t.originalCpm)?t.originalCpm:Number.isFinite(t.cpm)?t.cpm:l?.bidTrace?.cpm??0,currency:t.originalCurrency??t.currency??l?.bidTrace?.currency??"USD",...W(t).width?W(t):l?.bidTrace?{width:l.bidTrace.width,height:l.bidTrace.height}:W(t),dealId:t.dealId||l?.bidTrace?.dealId||"",mediaType:g,latencyMs:Number.isFinite(t.timeToRespond)?t.timeToRespond:l?.bidTrace?.latencyMs??0,advertiserDomain:t.meta?.advertiserDomains?.[0]||l?.bidTrace?.advertiserDomain||"",creativeId:t.creativeId||l?.bidTrace?.creativeId||""},I=r||l?.auctionId||"",A=o||l?.transactionId||"",p=n?this.slotViewabilityRecords.get(n):void 0,T=p&&I&&p.auctionId&&p.auctionId!==I;if(!!(n&&p&&T)){this.flushSlotTimeInView(n);let E=(this.slotRefreshIndices.get(n)??(p?p.refreshIndex:0))+1;this.slotRefreshIndices.set(n,E),this.slotLastAuctionIds.set(n,I),p&&(p.refreshIndex=E,p.auctionId=I,p.transactionId=A,p.bidPayload=h,p.viewableFired=!1,p.accumulatedTimeInViewMs=0)}else n&&(I&&this.slotLastAuctionIds.set(n,I),this.slotRefreshIndices.has(n)||this.slotRefreshIndices.set(n,0));let B=n?this.slotRefreshIndices.get(n)??(p?p.refreshIndex:0):0;if(c?this.log("DEBUG",`adRenderSucceeded received for video ad unit ${n||"unknown"}: suppressing IMPRESSION until verified video lifecycle event`):n&&this.hasImpressionEmitted(n,B,I,h.creativeId)||(n&&this.markImpressionEmitted(n,B,I,h.creativeId),this.enqueue(m.IMPRESSION,"impression",{auctionId:I,transactionId:A,adUnitCode:n,bid:h,metadata:{refresh_index:String(B)}})),this.config.viewabilityEnabled&&typeof document<"u"){let E=n&&this.slotElements.get(n)||null,L=n||e.adId||t.adId;if(!E&&L&&(E=document.getElementById(L)),!E&&typeof window<"u"&&window.googletag?.pubads)try{let D=window.googletag.pubads().getSlots();for(let b of D)if((b.getAdUnitPath?.()===n||b.getSlotElementId?.()===n)&&(E=document.getElementById(b.getSlotElementId()),E))break}catch{}if(!E&&L)try{for(let D of Array.from(document.querySelectorAll("[data-ad-slot]")))if(D.getAttribute("data-ad-slot")===L){E=D;break}}catch{}E&&this.observeSlot(E,n||L,{adUnitCode:n,auctionId:I,transactionId:A,mediaType:g,bid:h,refreshIndex:B})}}isDuplicate(e,t){return this.deduper.isDuplicate(e,t)}enqueue(e,t,n,r){if(!this.isEnabled||!this.shouldSample(e,r))return;this.managesSessionId&&dn()&&(this.config.sessionId=me());let o={eventId:$(G()),timestampMs:Date.now(),type:e,eventName:e===m.ERROR?t:"",auctionId:$(String(n.auctionId||"")),transactionId:$(String(n.transactionId||"")),adUnitCode:n.adUnitCode||n.elementId||"",namespace:n.ns||n.namespace||""};n.bid&&(o.bid={bidder:n.bid.bidder||"",cpm:Number.isFinite(n.bid.cpm)?n.bid.cpm:0,currency:n.bid.currency||"",width:Number.isFinite(n.bid.width)?n.bid.width:0,height:Number.isFinite(n.bid.height)?n.bid.height:0,dealId:n.bid.dealId||"",mediaType:n.bid.mediaType||"",latencyMs:Number.isFinite(n.bid.latencyMs)?n.bid.latencyMs:0,advertiserDomain:n.bid.advertiserDomain||"",creativeId:n.bid.creativeId||""}),n.viewableDurationMs!==void 0&&(o.viewableDurationMs=Number.isFinite(n.viewableDurationMs)?n.viewableDurationMs:0),n.bidderOutcomes&&Array.isArray(n.bidderOutcomes)&&(o.bidderOutcomes=n.bidderOutcomes.map(a=>{let l=this.floorDecisionFor(String(n.auctionId||""),a.adUnitCode||"");return{...a,refreshIndex:a.refreshIndex??this.auctionCycleIndex(a.adUnitCode||""),...l?{floorCents:l.floorCents,floorSource:zt[l.source],floorTreatmentBp:Math.round(l.treatment*1e4)}:{}}}));let s={...n.metadata};if(e===m.BID_WIN||e===m.IMPRESSION){let a=this.floorDecisionFor(String(n.auctionId||""),o.adUnitCode||"");a&&(a.floorCents!==void 0&&(s.floor_cents=String(a.floorCents)),s.floor_source=a.source,s.floor_treatment=a.treatment.toFixed(2))}n.error!==void 0&&n.error!==null&&(s.error=typeof n.error=="object"&&n.error.message?String(n.error.message):String(n.error)),n.gpid&&(s.gpid=String(n.gpid)),n.refreshIndex!==void 0&&s.refresh_index===void 0&&(s.refresh_index=String(n.refreshIndex));let d=en(s);Object.keys(d).length>0&&(o.metadata=d),this.queue.push(o),this.queue.length>=z?(this.flush(),this.queue.length>z&&this.queue.splice(0,this.queue.length-z)):qt.has(e)&&this.revenueFlushTimer===null&&(this.revenueFlushTimer=setTimeout(()=>{this.revenueFlushTimer=null,this.flush()},this.config.revenueFlushDelayMs))}shouldSample(e,t){return e===m.ERROR?(this.errorCount++,this.errorCount>Ut?!1:this.config.errorsEnabled):t==="WARN"?this.config.warningsEnabled:this.config.auctionEnabled}requeue(e){e.length&&(this.queue=e.concat(this.queue),this.queue.length>z&&this.queue.splice(0,this.queue.length-z))}drainBatch(){if(this.queue.length===0||!this.config.endpoint)return null;let e=typeof window<"u"?window.location.hostname:"",t=n=>({propertyId:$(this.config.propertyId),pageviewId:$(this.config.pageviewId),sessionId:$(this.config.sessionId),pageUrl:this.pageUrl,country:this.config.country,region:this.config.region,deviceType:this.config.deviceType,userId:$(this.config.userId),domain:e,events:n});for(;;){if(this.queue.length===0)return null;let n=this.queue,r=ye.encode(t(n)).finish();for(;n.length>1&&r.byteLength>be;)n=n.slice(0,Math.floor(n.length/2)),r=ye.encode(t(n)).finish();if(r.byteLength>be){let[o]=this.queue.splice(0,1);this.log("WARN",`Dropping oversized event (type ${o?.type}, ${r.byteLength} bytes exceeds the ${be}-byte cap on its own)`);continue}return this.queue=this.queue.slice(n.length),{url:`${this.config.endpoint}/${this.config.propertyId}`,encoded:r,events:n}}}sendFetch(e,t=!1,n,r=!1){let o={method:"POST",headers:{"Content-Type":ze},body:e.encoded};t&&(o.keepalive=!0),fetch(e.url,o).then(d=>{if(d.ok)r||(this.consecutiveSendFailures=0,this.nextSendAllowedAt=0),n&&n();else{if(this.log("WARN",`Failed to send batch: HTTP ${d.status}`),d.status>=400&&d.status<500&&d.status!==429&&d.status!==408){this.log("WARN",`Dropping batch due to non-retryable client error HTTP ${d.status}`);return}r||this.handleSendFailure(e.events)}}).catch(d=>{this.log("ERROR","Failed to send batch",d),r||this.handleSendFailure(e.events)});let s=typeof globalThis<"u"?globalThis.process:void 0;if(s&&typeof s._tickCallback=="function")try{s._tickCallback()}catch{}}handleSendFailure(e){this.consecutiveSendFailures++;let t=Math.min(Ke*2**(this.consecutiveSendFailures-1),Mt);this.nextSendAllowedAt=Date.now()+t,this.consecutiveSendFailures<=Nt?this.requeue(e):this.log("WARN",`Dropping ${e.length} events after ${this.consecutiveSendFailures} consecutive send failures`)}flush(){if(Date.now()<this.nextSendAllowedAt)return;let e=this.drainBatch();for(;e&&(this.sendFetch(e,!1),!(Date.now()<this.nextSendAllowedAt));)e=this.drainBatch()}flushBeacon(){let e=this.drainBatch();for(;e;){let t=!1;if(typeof navigator<"u"&&typeof navigator.sendBeacon=="function")try{let n=new Blob([e.encoded],{type:ze});t=navigator.sendBeacon(e.url,n)}catch{t=!1}if(!t){let n=this.persistBatch(e.encoded);this.sendFetch(e,!0,()=>this.removePersistedBatch(n))}e=this.drainBatch()}this.schedulePersistedCleanup()}pendingKeyPrefix(){return`${te}${encodeURIComponent(this.config.propertyId)}_`}persistBatch(e){if(!K)return null;try{if(typeof localStorage>"u"||!this.config.propertyId)return null;let t=0;for(let r=0;r<localStorage.length;r++){let o=localStorage.key(r);o&&o.startsWith(te)&&t++}if(t>=Ft)return null;let n=`${this.pendingKeyPrefix()}${Date.now()}_${Math.floor(Math.random()*1e6)}`;return localStorage.setItem(n,Qt(e)),this.persistedBatchKeys.push(n),n}catch{return null}}removePersistedBatch(e){if(!e)return;try{typeof localStorage<"u"&&localStorage.removeItem(e)}catch{}let t=this.persistedBatchKeys.indexOf(e);t!==-1&&this.persistedBatchKeys.splice(t,1)}schedulePersistedCleanup(){this.persistedBatchKeys.length!==0&&(this.persistedCleanupTimer&&clearTimeout(this.persistedCleanupTimer),this.persistedCleanupTimer=setTimeout(()=>{this.persistedCleanupTimer=null;for(let e of Array.from(this.persistedBatchKeys))this.removePersistedBatch(e)},$t))}resendPersistedBatches(){try{if(typeof localStorage>"u"||!this.config.endpoint||!this.config.propertyId)return;let e=this.pendingKeyPrefix(),t=[],n=[];for(let r=0;r<localStorage.length;r++){let o=localStorage.key(r);!o||!o.startsWith(te)||(o.startsWith(e)?t.push(o):tn(o)&&n.push(o))}for(let r of n)try{localStorage.removeItem(r)}catch{}for(let r of t){let o=null;try{o=localStorage.getItem(r),localStorage.removeItem(r)}catch{continue}if(!o)continue;let s=parseInt(r.slice(e.length),10);if(!Number.isFinite(s)||Date.now()-s>Vt)continue;let d;try{d=Zt(o)}catch{continue}d.byteLength!==0&&(this.log("DEBUG",`Resending persisted exit batch (${d.byteLength} bytes)`),this.sendFetch({url:`${this.config.endpoint}/${this.config.propertyId}`,encoded:d,events:[]},!1,void 0,!0))}}catch{}}log(e,t,...n){this.logger.log(e,t,...n)}},Ie=oe({prefix:"[bidkernel]",logLevel:"INFO"})});function un(i){let e=typeof i?.getError=="function"?i.getError():i?.error||i,t=a=>e&&typeof e[a]=="function"?e[a]():void 0,n=t("getMessage")||e?.message||String(e||"IMA ad error"),r=t("getErrorCode")??e?.code,o=t("getVastErrorCode"),s=t("getType")??e?.type,d={message:n};return r&&(d.error_code=String(r)),o&&(d.vast_error_code=String(o)),s&&(d.error_type=String(s)),{err:e,message:n,metadata:d}}function st(i,e,t){let n=ie(i),{err:r,message:o,metadata:s}=un(e);return n.log("WARN","IMA AdErrorEvent received",e),n.enqueue(m.AD_RENDER_FAILED,"adRenderFailed",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,bid:t.bid,metadata:{...t.metadata,reason:t.adStarted?"ima_playback_error":"ima_ad_error",playback_phase:t.adStarted?"post_start":"pre_start",...s},error:typeof r=="object"?r:new Error(o)}),r}function fn(i,e){if(!i||typeof i!="object"||nt.has(i))return;nt.add(i);let t=typeof window<"u"&&window.google?.ima?.AdErrorEvent?.Type?.AD_ERROR||"adError";try{e.call(i,t,n=>{for(let r of S.getActiveInstances())try{let o=at(r,{mediaType:"video"});st(r,n,{adStarted:!1,adUnitCode:o?.adUnitCode||"video",auctionId:o?.auctionId,transactionId:o?.transactionId,bid:o?.bidTrace})}catch{}})}catch{}}function it(i){if(i)try{let e=i.prototype;if(e&&typeof e.getAdsManager=="function"&&!e.getAdsManager.__bidkernelHooked){let t=e.getAdsManager,n=function(...r){let o=t.apply(this,r);if(o)for(let s of S.getActiveInstances())try{s.attachImaAdsManager(o)}catch{}return o};n.__bidkernelHooked=!0,e.getAdsManager=n}}catch{}}function rt(i){if(i)try{let e=i.prototype||i;if(e&&typeof e.init=="function"&&!e.init.__bidkernelHooked){let t=e.init,n=function(...r){for(let o of S.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};n.__bidkernelHooked=!0,e.init=n}if(e&&typeof e.start=="function"&&!e.start.__bidkernelHooked){let t=e.start,n=function(...r){for(let o of S.getActiveInstances())try{o.attachImaAdsManager(this)}catch{}return t.apply(this,r)};n.__bidkernelHooked=!0,e.start=n}}catch{}}function ot(i){if(i)try{let e=i.prototype;if(!e)return;if(typeof e.addEventListener=="function"&&!e.addEventListener.__bidkernelHooked){let t=e.addEventListener,n=function(r,o,...s){if(fn(this,t),(r==="adsManagerLoaded"||r===(this?.AdsManagerLoadedEvent?.Type?.ADS_MANAGER_LOADED||"adsManagerLoaded"))&&typeof o=="function"){let d=we.get(o);return d||(d=function(a){if(a&&typeof a.getAdsManager=="function"&&!a.getAdsManager.__bidkernelHooked){let l=a.getAdsManager;a.getAdsManager=function(...c){let g=l.apply(this,c);if(g)for(let h of S.getActiveInstances())try{h.attachImaAdsManager(g)}catch{}return g},a.getAdsManager.__bidkernelHooked=!0}return o.apply(this,arguments)},we.set(o,d)),t.call(this,r,d,...s)}return t.call(this,r,o,...s)};n.__bidkernelHooked=!0,e.addEventListener=n}if(typeof e.removeEventListener=="function"&&!e.removeEventListener.__bidkernelHooked){let t=e.removeEventListener,n=function(r,o,...s){let d=typeof o=="function"?we.get(o):void 0;return t.call(this,r,d||o,...s)};n.__bidkernelHooked=!0,e.removeEventListener=n}}catch{}}function X(i){if(!(!i||typeof i!="object"))try{i.AdsManagerLoadedEvent&&it(i.AdsManagerLoadedEvent);let e=Object.getOwnPropertyDescriptor(i,"AdsManagerLoadedEvent");if(!e||e.configurable){let r=i.AdsManagerLoadedEvent;try{Object.defineProperty(i,"AdsManagerLoadedEvent",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,it(o)}})}catch{}}i.AdsLoader&&ot(i.AdsLoader);let t=Object.getOwnPropertyDescriptor(i,"AdsLoader");if(!t||t.configurable){let r=i.AdsLoader;try{Object.defineProperty(i,"AdsLoader",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,ot(o)}})}catch{}}i.AdsManager&&rt(i.AdsManager);let n=Object.getOwnPropertyDescriptor(i,"AdsManager");if(!n||n.configurable){let r=i.AdsManager;try{Object.defineProperty(i,"AdsManager",{configurable:!0,enumerable:!0,get(){return r},set(o){r=o,rt(o)}})}catch{}}}catch{}}function dt(){if(typeof window>"u")return;let i=window;if(i.google?.ima&&X(i.google.ima),i.google&&typeof i.google=="object"){let t=Object.getOwnPropertyDescriptor(i.google,"ima");if(!t||t.configurable){let n=i.google.ima;try{Object.defineProperty(i.google,"ima",{configurable:!0,enumerable:!0,get(){return n},set(r){n=r,X(r)}})}catch{}}}let e=Object.getOwnPropertyDescriptor(i,"google");if(!e||e.configurable){let t=i.google;try{Object.defineProperty(i,"google",{configurable:!0,enumerable:!0,get(){return t},set(n){if(t=n,t&&typeof t=="object"){t.ima&&X(t.ima);let r=Object.getOwnPropertyDescriptor(t,"ima");if(!r||r.configurable){let o=t.ima;try{Object.defineProperty(t,"ima",{configurable:!0,enumerable:!0,get(){return o},set(s){o=s,X(s)}})}catch{}}}}})}catch{}}}function at(i,e){let t=ie(i),n=Date.now(),r=d=>t.hasImpressionEmitted(d.adUnitCode,void 0,d.auctionId,d.bidTrace.creativeId);if(e?.creativeId||e?.adId){for(let d of Array.from(t.cachedWinningBids.values()))if(!(n-d.timestamp>j)&&(e.creativeId&&(d.bidTrace.creativeId===e.creativeId||d.rawBid?.creativeId===e.creativeId)||e.adId&&(d.rawBid?.adId===e.adId||d.adUnitCode===e.adId)))return d}let o;if(e?.mediaType){for(let a of Array.from(t.cachedWinningBids.values())){if(n-a.timestamp>j)continue;(a.bidTrace.mediaType===e.mediaType||a.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&a.rawBid?.mediaTypes?.video!==void 0)&&(r(a)||(!o||a.timestamp<o.timestamp)&&(o=a))}if(o)return o;let d;for(let a of Array.from(t.cachedWinningBids.values())){if(n-a.timestamp>j)continue;(a.bidTrace.mediaType===e.mediaType||a.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&a.rawBid?.mediaTypes?.video!==void 0)&&(!d||a.timestamp>d.timestamp)&&(d=a)}if(d)return d}for(let d of Array.from(t.cachedWinningBids.values()))n-d.timestamp>j||r(d)||(!o||d.timestamp>o.timestamp)&&(o=d);if(o)return o;let s;for(let d of Array.from(t.cachedWinningBids.values()))n-d.timestamp>j||(!s||d.timestamp>s.timestamp)&&(s=d);return s}function ct(i,e,t){let n=ie(i);if(!e||typeof e.addEventListener!="function")return n.log("WARN","Invalid AdsManager passed to attachImaAdsManager"),()=>{};if(!e.__bidkernelAttachedInstances)try{Object.defineProperty(e,"__bidkernelAttachedInstances",{value:new Map,configurable:!0,writable:!0})}catch{e.__bidkernelAttachedInstances=new Map}let r=e.__bidkernelAttachedInstances,o=r.get(i);if(o){if(!t)return()=>{};o()}let s=t?.slotId||t?.adUnitCode||"video",d=t?.adUnitCode||s,a=t?.auctionId||"",l=t?.transactionId||"",c=y=>{let u=(a?n.getCachedBid(`${a}:${d}`):void 0)||(a&&s!==d?n.getCachedBid(`${a}:${s}`):void 0)||(d!=="video"?n.getCachedBid(d):void 0)||(s!==d&&s!=="video"?n.getCachedBid(s):void 0);return u||(u=at(i,{creativeId:y?.creativeId,adId:y?.adId,mediaType:"video"})),u},g=!1,h=y=>{g=!0,n.log("DEBUG","IMA AdEvent.STARTED / IMPRESSION received",y);let u=typeof y?.getAd=="function"?y.getAd():y?.ad,v={};u&&(v.creativeId=(typeof u.getCreativeId=="function"?u.getCreativeId():u.creativeId)||"",v.adId=(typeof u.getAdId=="function"?u.getAdId():u.id)||"",v.title=(typeof u.getTitle=="function"?u.getTitle():u.title)||"",v.duration=typeof u.getDuration=="function"?u.getDuration():u.duration,v.advertiserName=typeof u.getAdvertiserName=="function"?u.getAdvertiserName():"");let _=c(v),U=t?.slotId&&t.slotId!=="video"?t.slotId:t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:_?.adUnitCode||t?.slotId||t?.adUnitCode||"video",ft=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:_?.adUnitCode||U,ht=a||_?.auctionId||"",pt=l||_?.transactionId||"",Ae={..._?.rawBid||t?.bid,mediaType:"video",creativeId:v.creativeId||_?.bidTrace?.creativeId||t?.bid?.creativeId||""};if(n.recordImpression(U,{adUnitCode:ft,auctionId:ht,transactionId:pt,mediaType:"video",bid:Ae,metadata:{...t?.metadata,media_type:"video",...v.title?{ad_title:v.title}:{},...Number.isFinite(v.duration)?{ad_duration_s:String(v.duration)}:{}}})&&t?.onImpression)try{t.onImpression(U,{ad:u,bid:Ae})}catch(yt){n.log("ERROR","Error in onImpression callback",yt)}},I=y=>{if(n.log("DEBUG",`IMA AdEvent milestone: ${y}`),t?.onMilestone)try{t.onMilestone(y,s)}catch(u){n.log("ERROR","Error in onMilestone callback",u)}},A=y=>{n.log("DEBUG","IMA AdEvent.CLICK received",y);let u=c(),v=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:u?.adUnitCode||s;n.enqueue(m.CLICK,"click",{auctionId:a||u?.auctionId,transactionId:l||u?.transactionId,adUnitCode:v,bid:u?.bidTrace||t?.bid,metadata:{...t?.metadata,media_type:"video"}})},p=y=>{let u=c(),v=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:u?.adUnitCode||s,_=st(i,y,{adStarted:g,adUnitCode:v,auctionId:a||u?.auctionId,transactionId:l||u?.transactionId,bid:u?.bidTrace||t?.bid,metadata:t?.metadata});if(t?.onError)try{t.onError(_)}catch(U){n.log("ERROR","Error in onError callback",U)}},T=typeof window<"u"?window.google?.ima:void 0,O=T?.AdEvent?.Type||{},B=T?.AdErrorEvent?.Type||{},E=[{type:O.STARTED||"started",handler:h},{type:O.IMPRESSION||"impression",handler:h},{type:O.FIRST_QUARTILE||"firstQuartile",handler:()=>I("firstQuartile")},{type:O.MIDPOINT||"midpoint",handler:()=>I("midpoint")},{type:O.THIRD_QUARTILE||"thirdQuartile",handler:()=>I("thirdQuartile")},{type:O.COMPLETE||"complete",handler:()=>I("complete")},{type:O.CLICK||"click",handler:A},{type:B.AD_ERROR||"adError",handler:p}],L=new Set,D=[];for(let y of E)L.has(y.type)||(L.add(y.type),D.push(y));for(let{type:y,handler:u}of D)try{e.addEventListener(y,u)}catch{}let b=()=>{r.delete(i);for(let{type:y,handler:u}of D)try{e.removeEventListener(y,u)}catch{}n.videoDetachCleanups.delete(b)};return r.set(i,b),n.videoDetachCleanups.add(b),b}function hn(i,e,t){let n=ie(i);if(!e)return n.log("WARN","attachVideoPlayer called with null/undefined target"),()=>{};let r=null;if(typeof e=="string"){if(typeof document<"u")try{r=document.querySelector(e)||document.getElementById(e)}catch{r=document.getElementById(e)}}else if(typeof HTMLElement<"u"&&e instanceof HTMLElement)r=e;else if(e&&typeof e=="object"&&e.nodeType===1)r=e;else{if(typeof e.addEventListener=="function"&&(typeof e.init=="function"||typeof e.start=="function"||typeof e.getCuePoints=="function"||typeof e.getVolume=="function"||e.__imaAdsManager))return ct(i,e,t);e&&typeof e.addEventListener=="function"&&(r=e)}let o=t?.slotId||t?.adUnitCode||(r?r.id:"")||"video",s=t?.adUnitCode||o,d=t?.auctionId||"",a=t?.transactionId||"",l=()=>(d?n.getCachedBid(`${d}:${s}`):void 0)||(d&&o!==s?n.getCachedBid(`${d}:${o}`):void 0)||n.getCachedBid(s)||(o!==s?n.getCachedBid(o):void 0),c=null;r&&(r.tagName&&r.tagName.toLowerCase()==="video"?c=r:c=r.querySelector("video"));let g={q1:!1,q2:!1,q3:!1,q4:!1},h=b=>{let y=b||c||(r?.querySelector?r.querySelector("video"):null),u=l(),v={...u?.rawBid||t?.bid,mediaType:"video"};if(n.recordImpression(o,{adUnitCode:s,auctionId:d||u?.auctionId,transactionId:a||u?.transactionId,mediaType:"video",bid:v,metadata:{...t?.metadata,media_type:"video",...y&&Number.isFinite(y.duration)?{video_duration_s:String(Math.round(y.duration))}:{}}})&&t?.onImpression)try{t.onImpression(o,{element:y||r,bid:v})}catch(U){n.log("ERROR","Error in onImpression callback",U)}},I=b=>{n.log("DEBUG","HTML5 video playing event received");let y=b?.target instanceof HTMLVideoElement?b.target:c;h(y)},A=b=>{let y=b?.target instanceof HTMLVideoElement?b.target:c;if(y&&y.currentTime>0&&(h(y),Number.isFinite(y.duration)&&y.duration>0)){let u=y.currentTime/y.duration;u>=.25&&!g.q1&&(g.q1=!0,t?.onMilestone?.("firstQuartile",o)),u>=.5&&!g.q2&&(g.q2=!0,t?.onMilestone?.("midpoint",o)),u>=.75&&!g.q3&&(g.q3=!0,t?.onMilestone?.("thirdQuartile",o))}},p=()=>{g.q4||(g.q4=!0,t?.onMilestone?.("complete",o))},T=b=>{let u=(b?.target instanceof HTMLVideoElement?b.target:c)?.error||c?.error,v=l(),_=u?`HTML5 video error code ${u.code}: ${u.message}`:"Video playback error";if(n.log("WARN",_),n.enqueue(m.AD_RENDER_FAILED,"adRenderFailed",{auctionId:d||v?.auctionId,transactionId:a||v?.transactionId,adUnitCode:s,bid:v?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"html5_video_error",message:_,...u?.code?{error_code:String(u.code)}:{}},error:u?new Error(_):void 0}),t?.onError)try{t.onError(u)}catch(U){n.log("ERROR","Error in onError callback",U)}},O=b=>{b.addEventListener("playing",I),b.addEventListener("play",I),b.addEventListener("timeupdate",A),b.addEventListener("ended",p),b.addEventListener("error",T)},B=b=>{b.removeEventListener("playing",I),b.removeEventListener("play",I),b.removeEventListener("timeupdate",A),b.removeEventListener("ended",p),b.removeEventListener("error",T)},E=null;r&&r!==c&&(r.addEventListener("playing",I,!0),r.addEventListener("play",I,!0),r.addEventListener("timeupdate",A,!0),r.addEventListener("ended",p,!0),r.addEventListener("error",T,!0)),c&&O(c),r&&r.tagName?.toLowerCase()!=="video"&&typeof MutationObserver<"u"&&(E=new MutationObserver(()=>{let b=r.querySelector("video");b&&b!==c&&(c&&B(c),c=b,c&&O(c))}),E.observe(r,{childList:!0,subtree:!0}));let L=l();t?.trackViewability!==!1&&r&&n.observeSlot(r,o,{adUnitCode:s,auctionId:d||L?.auctionId,transactionId:a||L?.transactionId,mediaType:"video",bid:L?.bidTrace||t?.bid,metadata:t?.metadata});let D=()=>{E&&(E.disconnect(),E=null),r&&r!==c&&(r.removeEventListener("playing",I,!0),r.removeEventListener("play",I,!0),r.removeEventListener("timeupdate",A,!0),r.removeEventListener("ended",p,!0),r.removeEventListener("error",T,!0)),c&&B(c),n.videoDetachCleanups.delete(D)};return n.videoDetachCleanups.add(D),D}var ie,we,nt,pn,lt=C(()=>{"use strict";Te();ge();ie=i=>i,we=new WeakMap,nt=new WeakSet;typeof window<"u"&&dt();S.prototype.attachImaAdsManager=function(i,e){return ct(this,i,e)};S.prototype.attachVideoPlayer=function(i,e){return hn(this,i,e)};pn=S.prototype.enable;S.prototype.enable=function(){pn.call(this),typeof window<"u"&&(dt(),window.google?.ima&&X(window.google.ima))}});var gn=gt(()=>{Te();lt();var ut="https://by.bidkernel.io/t",yn=window._bidkernelPbjsGlobal||"pbjs";Ee(yn,{endpoint:ut});window.bidkernelPrebidAnalytics={...window.bidkernelPrebidAnalytics,register:(i,e)=>Ee(i,{endpoint:ut,...e}),attachVideoPlayer:(i,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.attachVideoPlayer?t.attachVideoPlayer(i,e):()=>{}},attachImaAdsManager:(i,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.attachImaAdsManager?t.attachImaAdsManager(i,e):()=>{}},recordImpression:(i,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.recordImpression?t.recordImpression(i,e):!1}}});return gn();})();
package/dist/index.d.mts CHANGED
@@ -85,6 +85,15 @@ interface SlotViewabilityState {
85
85
  refreshIndex: number;
86
86
  }
87
87
  declare const CACHED_BID_TTL_MS: number;
88
+ /** A Live Floors decision for one auction and ad unit, as the wrapper reports it. */
89
+ interface FloorDecision {
90
+ /** The applied floor for the slot's primary size, integer cents of the floor currency. */
91
+ floorCents?: number;
92
+ /** Which term set it. */
93
+ source: "static" | "pool" | "none";
94
+ /** The pageview's variance multiplier, two decimals. */
95
+ treatment: number;
96
+ }
88
97
  /**
89
98
  * The ingest endpoint decides where auction telemetry -- CPMs, deal IDs,
90
99
  * advertiser domains, user and session IDs -- is shipped, and it arrives from
@@ -177,6 +186,7 @@ declare class BidkernelPrebidAnalytics {
177
186
  private cachedWinningBids;
178
187
  private videoDetachCleanups;
179
188
  private auctionBidderOutcomes;
189
+ private floorDecisions;
180
190
  private logger;
181
191
  private managesSessionId;
182
192
  constructor(config: AnalyticsConfig);
@@ -265,6 +275,16 @@ declare class BidkernelPrebidAnalytics {
265
275
  getRefreshIndex(slotId: string): number;
266
276
  triggerSlotRefresh(slotId: string, options?: SlotObserveOptions): void;
267
277
  trackRawEvent(level: string, eventName: string, data: any): void;
278
+ /**
279
+ * Record the wrapper's Live Floors decision for an auction and ad unit,
280
+ * before the auction runs. The decision is stamped on the auction's
281
+ * outcome entries for the ad unit at auction end and on the win and
282
+ * impression rows that follow, so every outcome can be split by floor,
283
+ * source and treatment without a join. Integrations without the module
284
+ * never call this and their rows carry no floor fields.
285
+ */
286
+ recordFloorDecision(auctionId: string, adUnitCode: string, decision: FloorDecision): void;
287
+ private floorDecisionFor;
268
288
  setUserId(userId: string): void;
269
289
  setSessionId(sessionId: string): void;
270
290
  navigate(pageviewId: string, pageUrl: string): void;
@@ -368,6 +388,25 @@ declare module "./prebid-analytics" {
368
388
  attachVideoPlayer(target: any, options?: VideoPlayerOptions): () => void;
369
389
  }
370
390
  }
391
+ /**
392
+ * Normalizes event names for Google IMA compatibility, folding variants
393
+ * and folding impression onto started so one relayed start calls the shared
394
+ * handler exactly once.
395
+ */
396
+ declare function normalizeImaEventName(name: string): string;
397
+ /**
398
+ * Double implementing Google IMA AdsManager event surface.
399
+ * Relays outstream video host events into analytics adapters with IMA-shaped
400
+ * objects (getAd, getError).
401
+ */
402
+ declare class ImaAdsManagerStub {
403
+ private listeners;
404
+ addEventListener(type: string, listener: (event: any) => void): void;
405
+ removeEventListener(type: string, listener: (event: any) => void): void;
406
+ dispatch(name: string, payload?: any): void;
407
+ destroy(): void;
408
+ private createImaEvent;
409
+ }
371
410
 
372
411
  type SlotSize = [number, number];
373
412
  type SlotSizes = SlotSize[];
@@ -435,4 +474,4 @@ interface AdsGlobal {
435
474
  */
436
475
  declare function getbidkernel(alias?: string): AdsGlobal;
437
476
 
438
- export { type AdsGlobal, type AnalyticsConfig, BidkernelPrebidAnalytics, CACHED_BID_TTL_MS, type CachedWinningBid, PrebidEventDeduper, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, type VideoPlayerOptions, attachImaAdsManager, attachVideoPlayer, getOrCreateSessionId, getPrebidEventKey, getbidkernel, hookImaPrototype, initImaInterception, isSessionActive, isTrustedEndpoint, onSessionResume, registerPrebidAnalytics };
477
+ export { type AdsGlobal, type AnalyticsConfig, BidkernelPrebidAnalytics, CACHED_BID_TTL_MS, type CachedWinningBid, type FloorDecision, ImaAdsManagerStub, PrebidEventDeduper, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, type VideoPlayerOptions, attachImaAdsManager, attachVideoPlayer, getOrCreateSessionId, getPrebidEventKey, getbidkernel, hookImaPrototype, initImaInterception, isSessionActive, isTrustedEndpoint, normalizeImaEventName, onSessionResume, registerPrebidAnalytics };
package/dist/index.d.ts CHANGED
@@ -85,6 +85,15 @@ interface SlotViewabilityState {
85
85
  refreshIndex: number;
86
86
  }
87
87
  declare const CACHED_BID_TTL_MS: number;
88
+ /** A Live Floors decision for one auction and ad unit, as the wrapper reports it. */
89
+ interface FloorDecision {
90
+ /** The applied floor for the slot's primary size, integer cents of the floor currency. */
91
+ floorCents?: number;
92
+ /** Which term set it. */
93
+ source: "static" | "pool" | "none";
94
+ /** The pageview's variance multiplier, two decimals. */
95
+ treatment: number;
96
+ }
88
97
  /**
89
98
  * The ingest endpoint decides where auction telemetry -- CPMs, deal IDs,
90
99
  * advertiser domains, user and session IDs -- is shipped, and it arrives from
@@ -177,6 +186,7 @@ declare class BidkernelPrebidAnalytics {
177
186
  private cachedWinningBids;
178
187
  private videoDetachCleanups;
179
188
  private auctionBidderOutcomes;
189
+ private floorDecisions;
180
190
  private logger;
181
191
  private managesSessionId;
182
192
  constructor(config: AnalyticsConfig);
@@ -265,6 +275,16 @@ declare class BidkernelPrebidAnalytics {
265
275
  getRefreshIndex(slotId: string): number;
266
276
  triggerSlotRefresh(slotId: string, options?: SlotObserveOptions): void;
267
277
  trackRawEvent(level: string, eventName: string, data: any): void;
278
+ /**
279
+ * Record the wrapper's Live Floors decision for an auction and ad unit,
280
+ * before the auction runs. The decision is stamped on the auction's
281
+ * outcome entries for the ad unit at auction end and on the win and
282
+ * impression rows that follow, so every outcome can be split by floor,
283
+ * source and treatment without a join. Integrations without the module
284
+ * never call this and their rows carry no floor fields.
285
+ */
286
+ recordFloorDecision(auctionId: string, adUnitCode: string, decision: FloorDecision): void;
287
+ private floorDecisionFor;
268
288
  setUserId(userId: string): void;
269
289
  setSessionId(sessionId: string): void;
270
290
  navigate(pageviewId: string, pageUrl: string): void;
@@ -368,6 +388,25 @@ declare module "./prebid-analytics" {
368
388
  attachVideoPlayer(target: any, options?: VideoPlayerOptions): () => void;
369
389
  }
370
390
  }
391
+ /**
392
+ * Normalizes event names for Google IMA compatibility, folding variants
393
+ * and folding impression onto started so one relayed start calls the shared
394
+ * handler exactly once.
395
+ */
396
+ declare function normalizeImaEventName(name: string): string;
397
+ /**
398
+ * Double implementing Google IMA AdsManager event surface.
399
+ * Relays outstream video host events into analytics adapters with IMA-shaped
400
+ * objects (getAd, getError).
401
+ */
402
+ declare class ImaAdsManagerStub {
403
+ private listeners;
404
+ addEventListener(type: string, listener: (event: any) => void): void;
405
+ removeEventListener(type: string, listener: (event: any) => void): void;
406
+ dispatch(name: string, payload?: any): void;
407
+ destroy(): void;
408
+ private createImaEvent;
409
+ }
371
410
 
372
411
  type SlotSize = [number, number];
373
412
  type SlotSizes = SlotSize[];
@@ -435,4 +474,4 @@ interface AdsGlobal {
435
474
  */
436
475
  declare function getbidkernel(alias?: string): AdsGlobal;
437
476
 
438
- export { type AdsGlobal, type AnalyticsConfig, BidkernelPrebidAnalytics, CACHED_BID_TTL_MS, type CachedWinningBid, PrebidEventDeduper, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, type VideoPlayerOptions, attachImaAdsManager, attachVideoPlayer, getOrCreateSessionId, getPrebidEventKey, getbidkernel, hookImaPrototype, initImaInterception, isSessionActive, isTrustedEndpoint, onSessionResume, registerPrebidAnalytics };
477
+ export { type AdsGlobal, type AnalyticsConfig, BidkernelPrebidAnalytics, CACHED_BID_TTL_MS, type CachedWinningBid, type FloorDecision, ImaAdsManagerStub, PrebidEventDeduper, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, type VideoPlayerOptions, attachImaAdsManager, attachVideoPlayer, getOrCreateSessionId, getPrebidEventKey, getbidkernel, hookImaPrototype, initImaInterception, isSessionActive, isTrustedEndpoint, normalizeImaEventName, onSessionResume, registerPrebidAnalytics };
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  BidkernelPrebidAnalytics: () => BidkernelPrebidAnalytics,
24
24
  CACHED_BID_TTL_MS: () => CACHED_BID_TTL_MS,
25
+ ImaAdsManagerStub: () => ImaAdsManagerStub,
25
26
  PrebidEventDeduper: () => PrebidEventDeduper,
26
27
  attachImaAdsManager: () => attachImaAdsManager,
27
28
  attachVideoPlayer: () => attachVideoPlayer,
@@ -32,6 +33,7 @@ __export(src_exports, {
32
33
  initImaInterception: () => initImaInterception,
33
34
  isSessionActive: () => isSessionActive,
34
35
  isTrustedEndpoint: () => isTrustedEndpoint,
36
+ normalizeImaEventName: () => normalizeImaEventName,
35
37
  onSessionResume: () => onSessionResume,
36
38
  registerPrebidAnalytics: () => registerPrebidAnalytics
37
39
  });
@@ -356,6 +358,17 @@ var BidderOutcome = {
356
358
  BIDDER_OUTCOME_NO_RESPONSE: 5,
357
359
  UNRECOGNIZED: -1
358
360
  };
361
+ var FloorSource = {
362
+ /** FLOOR_SOURCE_UNSPECIFIED - module off, no decision */
363
+ FLOOR_SOURCE_UNSPECIFIED: 0,
364
+ /** FLOOR_SOURCE_STATIC - the publisher's rule, scaled by the treatment */
365
+ FLOOR_SOURCE_STATIC: 1,
366
+ /** FLOOR_SOURCE_POOL - the bid pool's standing bid plus margin */
367
+ FLOOR_SOURCE_POOL: 2,
368
+ /** FLOOR_SOURCE_NONE - module on, but neither term applied */
369
+ FLOOR_SOURCE_NONE: 3,
370
+ UNRECOGNIZED: -1
371
+ };
359
372
  function createBaseTraceEventBatch() {
360
373
  return {
361
374
  propertyId: new Uint8Array(0),
@@ -758,7 +771,15 @@ var TraceEvent_MetadataEntry = {
758
771
  }
759
772
  };
760
773
  function createBaseBidderOutcomeEntry() {
761
- return { adUnitCode: "", outcome: 0, bid: void 0, refreshIndex: 0 };
774
+ return {
775
+ adUnitCode: "",
776
+ outcome: 0,
777
+ bid: void 0,
778
+ refreshIndex: 0,
779
+ floorCents: void 0,
780
+ floorSource: 0,
781
+ floorTreatmentBp: void 0
782
+ };
762
783
  }
763
784
  var BidderOutcomeEntry = {
764
785
  encode(message, writer = new import_wire.BinaryWriter()) {
@@ -774,6 +795,15 @@ var BidderOutcomeEntry = {
774
795
  if (message.refreshIndex !== void 0 && message.refreshIndex !== 0) {
775
796
  writer.uint32(56).int32(message.refreshIndex);
776
797
  }
798
+ if (message.floorCents !== void 0) {
799
+ writer.uint32(64).int32(message.floorCents);
800
+ }
801
+ if (message.floorSource !== void 0 && message.floorSource !== 0) {
802
+ writer.uint32(72).int32(message.floorSource);
803
+ }
804
+ if (message.floorTreatmentBp !== void 0) {
805
+ writer.uint32(80).int32(message.floorTreatmentBp);
806
+ }
777
807
  return writer;
778
808
  },
779
809
  decode(input, length) {
@@ -811,6 +841,27 @@ var BidderOutcomeEntry = {
811
841
  message.refreshIndex = reader.int32();
812
842
  continue;
813
843
  }
844
+ case 8: {
845
+ if (tag !== 64) {
846
+ break;
847
+ }
848
+ message.floorCents = reader.int32();
849
+ continue;
850
+ }
851
+ case 9: {
852
+ if (tag !== 72) {
853
+ break;
854
+ }
855
+ message.floorSource = reader.int32();
856
+ continue;
857
+ }
858
+ case 10: {
859
+ if (tag !== 80) {
860
+ break;
861
+ }
862
+ message.floorTreatmentBp = reader.int32();
863
+ continue;
864
+ }
814
865
  }
815
866
  if ((tag & 7) === 4 || tag === 0) {
816
867
  break;
@@ -1010,6 +1061,12 @@ var CACHED_BID_TTL_MS = 30 * 60 * 1e3;
1010
1061
  var MAX_CACHED_BID_KEYS = 200;
1011
1062
  var MAX_IMPRESSION_KEYS = 1e3;
1012
1063
  var MAX_TRACKED_AUCTIONS = 50;
1064
+ var MAX_FLOOR_DECISIONS = 200;
1065
+ var FLOOR_SOURCE_PROTO = {
1066
+ static: FloorSource.FLOOR_SOURCE_STATIC,
1067
+ pool: FloorSource.FLOOR_SOURCE_POOL,
1068
+ none: FloorSource.FLOOR_SOURCE_NONE
1069
+ };
1013
1070
  var CLICK_DEDUP_MS = 1e3;
1014
1071
  var SESSION_KEY = "_bidkernel_session";
1015
1072
  var SESSION_TS_KEY = "_bidkernel_session_ts";
@@ -1320,6 +1377,8 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
1320
1377
  videoDetachCleanups = /* @__PURE__ */ new Set();
1321
1378
  // Compacted bidder participation map per auction: auctionId -> Map<`${bidder}:${adUnitCode}`, BidderOutcomeEntry>
1322
1379
  auctionBidderOutcomes = /* @__PURE__ */ new Map();
1380
+ // Live Floors decisions: `${auctionId}:${adUnitCode}` -> decision (see recordFloorDecision)
1381
+ floorDecisions = /* @__PURE__ */ new Map();
1323
1382
  logger;
1324
1383
  // True when this instance owns its session id (none was supplied), so the
1325
1384
  // id follows the page-wide session as it lapses and restarts. An id the
@@ -1515,6 +1574,7 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
1515
1574
  this.slotEmittedImpressionKeys.clear();
1516
1575
  this.slotLastAuctionIds.clear();
1517
1576
  this.auctionBidderOutcomes.clear();
1577
+ this.floorDecisions.clear();
1518
1578
  if (this.flushTimer) {
1519
1579
  clearInterval(this.flushTimer);
1520
1580
  this.flushTimer = null;
@@ -2274,6 +2334,32 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
2274
2334
  if (eventType === void 0) return;
2275
2335
  this.enqueue(eventType, eventName, data, level);
2276
2336
  }
2337
+ /**
2338
+ * Record the wrapper's Live Floors decision for an auction and ad unit,
2339
+ * before the auction runs. The decision is stamped on the auction's
2340
+ * outcome entries for the ad unit at auction end and on the win and
2341
+ * impression rows that follow, so every outcome can be split by floor,
2342
+ * source and treatment without a join. Integrations without the module
2343
+ * never call this and their rows carry no floor fields.
2344
+ */
2345
+ recordFloorDecision(auctionId, adUnitCode, decision) {
2346
+ if (!auctionId || !adUnitCode) return;
2347
+ const key = `${auctionId}:${adUnitCode}`;
2348
+ this.floorDecisions.delete(key);
2349
+ this.floorDecisions.set(key, {
2350
+ floorCents: decision.floorCents !== void 0 && Number.isFinite(decision.floorCents) ? Math.round(decision.floorCents) : void 0,
2351
+ source: decision.source,
2352
+ treatment: Number.isFinite(decision.treatment) ? decision.treatment : 1
2353
+ });
2354
+ while (this.floorDecisions.size > MAX_FLOOR_DECISIONS) {
2355
+ const oldest = this.floorDecisions.keys().next();
2356
+ if (oldest.done) break;
2357
+ this.floorDecisions.delete(oldest.value);
2358
+ }
2359
+ }
2360
+ floorDecisionFor(auctionId, adUnitCode) {
2361
+ return auctionId && adUnitCode ? this.floorDecisions.get(`${auctionId}:${adUnitCode}`) : void 0;
2362
+ }
2277
2363
  setUserId(userId) {
2278
2364
  this.config.userId = userId;
2279
2365
  }
@@ -2285,6 +2371,7 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
2285
2371
  navigate(pageviewId, pageUrl) {
2286
2372
  this.disable();
2287
2373
  this.slotRefreshIndices.clear();
2374
+ this.floorDecisions.clear();
2288
2375
  this.pendingThresholdListeners.clear();
2289
2376
  this.config.pageviewId = pageviewId || generateUUID();
2290
2377
  if (pageUrl) {
@@ -2674,13 +2761,32 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
2674
2761
  }
2675
2762
  if (data.bidderOutcomes && Array.isArray(data.bidderOutcomes)) {
2676
2763
  protoEvent.bidderOutcomes = data.bidderOutcomes.map(
2677
- (entry) => ({
2678
- ...entry,
2679
- refreshIndex: entry.refreshIndex ?? this.auctionCycleIndex(entry.adUnitCode || "")
2680
- })
2764
+ (entry) => {
2765
+ const floor = this.floorDecisionFor(String(data.auctionId || ""), entry.adUnitCode || "");
2766
+ return {
2767
+ ...entry,
2768
+ refreshIndex: entry.refreshIndex ?? this.auctionCycleIndex(entry.adUnitCode || ""),
2769
+ ...floor ? {
2770
+ floorCents: floor.floorCents,
2771
+ floorSource: FLOOR_SOURCE_PROTO[floor.source],
2772
+ floorTreatmentBp: Math.round(floor.treatment * 1e4)
2773
+ } : {}
2774
+ };
2775
+ }
2681
2776
  );
2682
2777
  }
2683
2778
  const metadata = { ...data.metadata };
2779
+ if (type === TraceEventType.BID_WIN || type === TraceEventType.IMPRESSION) {
2780
+ const floor = this.floorDecisionFor(
2781
+ String(data.auctionId || ""),
2782
+ protoEvent.adUnitCode || ""
2783
+ );
2784
+ if (floor) {
2785
+ if (floor.floorCents !== void 0) metadata.floor_cents = String(floor.floorCents);
2786
+ metadata.floor_source = floor.source;
2787
+ metadata.floor_treatment = floor.treatment.toFixed(2);
2788
+ }
2789
+ }
2684
2790
  if (data.error !== void 0 && data.error !== null) {
2685
2791
  metadata.error = typeof data.error === "object" && data.error.message ? String(data.error.message) : String(data.error);
2686
2792
  }
@@ -3846,6 +3952,120 @@ BidkernelPrebidAnalytics.prototype.enable = function() {
3846
3952
  }
3847
3953
  }
3848
3954
  };
3955
+ function normalizeImaEventName(name) {
3956
+ if (!name) return "";
3957
+ const lower = name.toLowerCase().replace(/[_-]/g, "");
3958
+ switch (lower) {
3959
+ case "started":
3960
+ case "start":
3961
+ case "impression":
3962
+ return "started";
3963
+ case "firstquartile":
3964
+ return "firstQuartile";
3965
+ case "midpoint":
3966
+ return "midpoint";
3967
+ case "thirdquartile":
3968
+ return "thirdQuartile";
3969
+ case "complete":
3970
+ case "completed":
3971
+ case "ended":
3972
+ return "complete";
3973
+ case "click":
3974
+ case "clicked":
3975
+ return "click";
3976
+ case "pause":
3977
+ case "paused":
3978
+ return "pause";
3979
+ case "resume":
3980
+ case "resumed":
3981
+ return "resume";
3982
+ case "skipped":
3983
+ case "skip":
3984
+ return "skipped";
3985
+ case "volumechanged":
3986
+ case "volumechange":
3987
+ return "volumeChanged";
3988
+ case "loaded":
3989
+ return "loaded";
3990
+ case "aderror":
3991
+ case "error":
3992
+ return "adError";
3993
+ default:
3994
+ return name;
3995
+ }
3996
+ }
3997
+ var ImaAdsManagerStub = class {
3998
+ listeners = /* @__PURE__ */ new Map();
3999
+ addEventListener(type, listener) {
4000
+ if (!type || typeof listener !== "function") return;
4001
+ const eventName = normalizeImaEventName(type);
4002
+ let set = this.listeners.get(eventName);
4003
+ if (!set) {
4004
+ set = /* @__PURE__ */ new Set();
4005
+ this.listeners.set(eventName, set);
4006
+ }
4007
+ set.add(listener);
4008
+ }
4009
+ removeEventListener(type, listener) {
4010
+ if (!type || typeof listener !== "function") return;
4011
+ const eventName = normalizeImaEventName(type);
4012
+ const set = this.listeners.get(eventName);
4013
+ if (set) {
4014
+ set.delete(listener);
4015
+ if (set.size === 0) {
4016
+ this.listeners.delete(eventName);
4017
+ }
4018
+ }
4019
+ }
4020
+ dispatch(name, payload) {
4021
+ const eventName = normalizeImaEventName(name);
4022
+ const set = this.listeners.get(eventName);
4023
+ if (!set || set.size === 0) return;
4024
+ const event = this.createImaEvent(eventName, payload);
4025
+ for (const listener of Array.from(set)) {
4026
+ try {
4027
+ listener(event);
4028
+ } catch {
4029
+ }
4030
+ }
4031
+ }
4032
+ destroy() {
4033
+ this.listeners.clear();
4034
+ }
4035
+ createImaEvent(eventName, payload) {
4036
+ 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;
4037
+ const adObj = rawAd ? {
4038
+ getAdId: () => typeof rawAd.getAdId === "function" ? rawAd.getAdId() : rawAd.adId ?? rawAd.id ?? "",
4039
+ getCreativeId: () => typeof rawAd.getCreativeId === "function" ? rawAd.getCreativeId() : rawAd.creativeId ?? "",
4040
+ getTitle: () => typeof rawAd.getTitle === "function" ? rawAd.getTitle() : rawAd.title ?? "",
4041
+ getAdvertiserName: () => typeof rawAd.getAdvertiserName === "function" ? rawAd.getAdvertiserName() : rawAd.advertiser ?? rawAd.advertiserName ?? "",
4042
+ getDuration: () => typeof rawAd.getDuration === "function" ? rawAd.getDuration() : rawAd.duration ?? 0,
4043
+ adId: typeof rawAd.getAdId === "function" ? rawAd.getAdId() : rawAd.adId ?? rawAd.id ?? "",
4044
+ creativeId: typeof rawAd.getCreativeId === "function" ? rawAd.getCreativeId() : rawAd.creativeId ?? "",
4045
+ title: typeof rawAd.getTitle === "function" ? rawAd.getTitle() : rawAd.title ?? "",
4046
+ advertiserName: typeof rawAd.getAdvertiserName === "function" ? rawAd.getAdvertiserName() : rawAd.advertiser ?? rawAd.advertiserName ?? "",
4047
+ duration: typeof rawAd.getDuration === "function" ? rawAd.getDuration() : rawAd.duration ?? 0
4048
+ } : null;
4049
+ 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;
4050
+ const errorObj = rawError ? {
4051
+ getMessage: () => typeof rawError.getMessage === "function" ? rawError.getMessage() : rawError.message ?? String(rawError),
4052
+ getErrorCode: () => typeof rawError.getErrorCode === "function" ? rawError.getErrorCode() : rawError.code ?? rawError.errorCode ?? rawError.error_code,
4053
+ getVastErrorCode: () => typeof rawError.getVastErrorCode === "function" ? rawError.getVastErrorCode() : rawError.vastCode ?? rawError.vastErrorCode ?? rawError.vast_error_code,
4054
+ getType: () => typeof rawError.getType === "function" ? rawError.getType() : rawError.class ?? rawError.error_class ?? rawError.type ?? rawError.errorType ?? "other",
4055
+ message: typeof rawError.getMessage === "function" ? rawError.getMessage() : rawError.message ?? String(rawError),
4056
+ code: typeof rawError.getErrorCode === "function" ? rawError.getErrorCode() : rawError.code ?? rawError.errorCode ?? rawError.error_code,
4057
+ vastCode: typeof rawError.getVastErrorCode === "function" ? rawError.getVastErrorCode() : rawError.vastCode ?? rawError.vastErrorCode ?? rawError.vast_error_code,
4058
+ type: typeof rawError.getType === "function" ? rawError.getType() : rawError.class ?? rawError.error_class ?? rawError.type ?? rawError.errorType ?? "other"
4059
+ } : null;
4060
+ return {
4061
+ type: eventName,
4062
+ getAd: () => adObj,
4063
+ getError: () => errorObj,
4064
+ ad: adObj,
4065
+ error: errorObj
4066
+ };
4067
+ }
4068
+ };
3849
4069
 
3850
4070
  // src/index.ts
3851
4071
  function getbidkernel(alias = "bidkernel") {
@@ -3881,6 +4101,7 @@ function getbidkernel(alias = "bidkernel") {
3881
4101
  0 && (module.exports = {
3882
4102
  BidkernelPrebidAnalytics,
3883
4103
  CACHED_BID_TTL_MS,
4104
+ ImaAdsManagerStub,
3884
4105
  PrebidEventDeduper,
3885
4106
  attachImaAdsManager,
3886
4107
  attachVideoPlayer,
@@ -3891,6 +4112,7 @@ function getbidkernel(alias = "bidkernel") {
3891
4112
  initImaInterception,
3892
4113
  isSessionActive,
3893
4114
  isTrustedEndpoint,
4115
+ normalizeImaEventName,
3894
4116
  onSessionResume,
3895
4117
  registerPrebidAnalytics
3896
4118
  });
package/dist/index.mjs CHANGED
@@ -317,6 +317,17 @@ var BidderOutcome = {
317
317
  BIDDER_OUTCOME_NO_RESPONSE: 5,
318
318
  UNRECOGNIZED: -1
319
319
  };
320
+ var FloorSource = {
321
+ /** FLOOR_SOURCE_UNSPECIFIED - module off, no decision */
322
+ FLOOR_SOURCE_UNSPECIFIED: 0,
323
+ /** FLOOR_SOURCE_STATIC - the publisher's rule, scaled by the treatment */
324
+ FLOOR_SOURCE_STATIC: 1,
325
+ /** FLOOR_SOURCE_POOL - the bid pool's standing bid plus margin */
326
+ FLOOR_SOURCE_POOL: 2,
327
+ /** FLOOR_SOURCE_NONE - module on, but neither term applied */
328
+ FLOOR_SOURCE_NONE: 3,
329
+ UNRECOGNIZED: -1
330
+ };
320
331
  function createBaseTraceEventBatch() {
321
332
  return {
322
333
  propertyId: new Uint8Array(0),
@@ -719,7 +730,15 @@ var TraceEvent_MetadataEntry = {
719
730
  }
720
731
  };
721
732
  function createBaseBidderOutcomeEntry() {
722
- return { adUnitCode: "", outcome: 0, bid: void 0, refreshIndex: 0 };
733
+ return {
734
+ adUnitCode: "",
735
+ outcome: 0,
736
+ bid: void 0,
737
+ refreshIndex: 0,
738
+ floorCents: void 0,
739
+ floorSource: 0,
740
+ floorTreatmentBp: void 0
741
+ };
723
742
  }
724
743
  var BidderOutcomeEntry = {
725
744
  encode(message, writer = new BinaryWriter()) {
@@ -735,6 +754,15 @@ var BidderOutcomeEntry = {
735
754
  if (message.refreshIndex !== void 0 && message.refreshIndex !== 0) {
736
755
  writer.uint32(56).int32(message.refreshIndex);
737
756
  }
757
+ if (message.floorCents !== void 0) {
758
+ writer.uint32(64).int32(message.floorCents);
759
+ }
760
+ if (message.floorSource !== void 0 && message.floorSource !== 0) {
761
+ writer.uint32(72).int32(message.floorSource);
762
+ }
763
+ if (message.floorTreatmentBp !== void 0) {
764
+ writer.uint32(80).int32(message.floorTreatmentBp);
765
+ }
738
766
  return writer;
739
767
  },
740
768
  decode(input, length) {
@@ -772,6 +800,27 @@ var BidderOutcomeEntry = {
772
800
  message.refreshIndex = reader.int32();
773
801
  continue;
774
802
  }
803
+ case 8: {
804
+ if (tag !== 64) {
805
+ break;
806
+ }
807
+ message.floorCents = reader.int32();
808
+ continue;
809
+ }
810
+ case 9: {
811
+ if (tag !== 72) {
812
+ break;
813
+ }
814
+ message.floorSource = reader.int32();
815
+ continue;
816
+ }
817
+ case 10: {
818
+ if (tag !== 80) {
819
+ break;
820
+ }
821
+ message.floorTreatmentBp = reader.int32();
822
+ continue;
823
+ }
775
824
  }
776
825
  if ((tag & 7) === 4 || tag === 0) {
777
826
  break;
@@ -971,6 +1020,12 @@ var CACHED_BID_TTL_MS = 30 * 60 * 1e3;
971
1020
  var MAX_CACHED_BID_KEYS = 200;
972
1021
  var MAX_IMPRESSION_KEYS = 1e3;
973
1022
  var MAX_TRACKED_AUCTIONS = 50;
1023
+ var MAX_FLOOR_DECISIONS = 200;
1024
+ var FLOOR_SOURCE_PROTO = {
1025
+ static: FloorSource.FLOOR_SOURCE_STATIC,
1026
+ pool: FloorSource.FLOOR_SOURCE_POOL,
1027
+ none: FloorSource.FLOOR_SOURCE_NONE
1028
+ };
974
1029
  var CLICK_DEDUP_MS = 1e3;
975
1030
  var SESSION_KEY = "_bidkernel_session";
976
1031
  var SESSION_TS_KEY = "_bidkernel_session_ts";
@@ -1281,6 +1336,8 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
1281
1336
  videoDetachCleanups = /* @__PURE__ */ new Set();
1282
1337
  // Compacted bidder participation map per auction: auctionId -> Map<`${bidder}:${adUnitCode}`, BidderOutcomeEntry>
1283
1338
  auctionBidderOutcomes = /* @__PURE__ */ new Map();
1339
+ // Live Floors decisions: `${auctionId}:${adUnitCode}` -> decision (see recordFloorDecision)
1340
+ floorDecisions = /* @__PURE__ */ new Map();
1284
1341
  logger;
1285
1342
  // True when this instance owns its session id (none was supplied), so the
1286
1343
  // id follows the page-wide session as it lapses and restarts. An id the
@@ -1476,6 +1533,7 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
1476
1533
  this.slotEmittedImpressionKeys.clear();
1477
1534
  this.slotLastAuctionIds.clear();
1478
1535
  this.auctionBidderOutcomes.clear();
1536
+ this.floorDecisions.clear();
1479
1537
  if (this.flushTimer) {
1480
1538
  clearInterval(this.flushTimer);
1481
1539
  this.flushTimer = null;
@@ -2235,6 +2293,32 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
2235
2293
  if (eventType === void 0) return;
2236
2294
  this.enqueue(eventType, eventName, data, level);
2237
2295
  }
2296
+ /**
2297
+ * Record the wrapper's Live Floors decision for an auction and ad unit,
2298
+ * before the auction runs. The decision is stamped on the auction's
2299
+ * outcome entries for the ad unit at auction end and on the win and
2300
+ * impression rows that follow, so every outcome can be split by floor,
2301
+ * source and treatment without a join. Integrations without the module
2302
+ * never call this and their rows carry no floor fields.
2303
+ */
2304
+ recordFloorDecision(auctionId, adUnitCode, decision) {
2305
+ if (!auctionId || !adUnitCode) return;
2306
+ const key = `${auctionId}:${adUnitCode}`;
2307
+ this.floorDecisions.delete(key);
2308
+ this.floorDecisions.set(key, {
2309
+ floorCents: decision.floorCents !== void 0 && Number.isFinite(decision.floorCents) ? Math.round(decision.floorCents) : void 0,
2310
+ source: decision.source,
2311
+ treatment: Number.isFinite(decision.treatment) ? decision.treatment : 1
2312
+ });
2313
+ while (this.floorDecisions.size > MAX_FLOOR_DECISIONS) {
2314
+ const oldest = this.floorDecisions.keys().next();
2315
+ if (oldest.done) break;
2316
+ this.floorDecisions.delete(oldest.value);
2317
+ }
2318
+ }
2319
+ floorDecisionFor(auctionId, adUnitCode) {
2320
+ return auctionId && adUnitCode ? this.floorDecisions.get(`${auctionId}:${adUnitCode}`) : void 0;
2321
+ }
2238
2322
  setUserId(userId) {
2239
2323
  this.config.userId = userId;
2240
2324
  }
@@ -2246,6 +2330,7 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
2246
2330
  navigate(pageviewId, pageUrl) {
2247
2331
  this.disable();
2248
2332
  this.slotRefreshIndices.clear();
2333
+ this.floorDecisions.clear();
2249
2334
  this.pendingThresholdListeners.clear();
2250
2335
  this.config.pageviewId = pageviewId || generateUUID();
2251
2336
  if (pageUrl) {
@@ -2635,13 +2720,32 @@ var BidkernelPrebidAnalytics = class _BidkernelPrebidAnalytics {
2635
2720
  }
2636
2721
  if (data.bidderOutcomes && Array.isArray(data.bidderOutcomes)) {
2637
2722
  protoEvent.bidderOutcomes = data.bidderOutcomes.map(
2638
- (entry) => ({
2639
- ...entry,
2640
- refreshIndex: entry.refreshIndex ?? this.auctionCycleIndex(entry.adUnitCode || "")
2641
- })
2723
+ (entry) => {
2724
+ const floor = this.floorDecisionFor(String(data.auctionId || ""), entry.adUnitCode || "");
2725
+ return {
2726
+ ...entry,
2727
+ refreshIndex: entry.refreshIndex ?? this.auctionCycleIndex(entry.adUnitCode || ""),
2728
+ ...floor ? {
2729
+ floorCents: floor.floorCents,
2730
+ floorSource: FLOOR_SOURCE_PROTO[floor.source],
2731
+ floorTreatmentBp: Math.round(floor.treatment * 1e4)
2732
+ } : {}
2733
+ };
2734
+ }
2642
2735
  );
2643
2736
  }
2644
2737
  const metadata = { ...data.metadata };
2738
+ if (type === TraceEventType.BID_WIN || type === TraceEventType.IMPRESSION) {
2739
+ const floor = this.floorDecisionFor(
2740
+ String(data.auctionId || ""),
2741
+ protoEvent.adUnitCode || ""
2742
+ );
2743
+ if (floor) {
2744
+ if (floor.floorCents !== void 0) metadata.floor_cents = String(floor.floorCents);
2745
+ metadata.floor_source = floor.source;
2746
+ metadata.floor_treatment = floor.treatment.toFixed(2);
2747
+ }
2748
+ }
2645
2749
  if (data.error !== void 0 && data.error !== null) {
2646
2750
  metadata.error = typeof data.error === "object" && data.error.message ? String(data.error.message) : String(data.error);
2647
2751
  }
@@ -3807,6 +3911,120 @@ BidkernelPrebidAnalytics.prototype.enable = function() {
3807
3911
  }
3808
3912
  }
3809
3913
  };
3914
+ function normalizeImaEventName(name) {
3915
+ if (!name) return "";
3916
+ const lower = name.toLowerCase().replace(/[_-]/g, "");
3917
+ switch (lower) {
3918
+ case "started":
3919
+ case "start":
3920
+ case "impression":
3921
+ return "started";
3922
+ case "firstquartile":
3923
+ return "firstQuartile";
3924
+ case "midpoint":
3925
+ return "midpoint";
3926
+ case "thirdquartile":
3927
+ return "thirdQuartile";
3928
+ case "complete":
3929
+ case "completed":
3930
+ case "ended":
3931
+ return "complete";
3932
+ case "click":
3933
+ case "clicked":
3934
+ return "click";
3935
+ case "pause":
3936
+ case "paused":
3937
+ return "pause";
3938
+ case "resume":
3939
+ case "resumed":
3940
+ return "resume";
3941
+ case "skipped":
3942
+ case "skip":
3943
+ return "skipped";
3944
+ case "volumechanged":
3945
+ case "volumechange":
3946
+ return "volumeChanged";
3947
+ case "loaded":
3948
+ return "loaded";
3949
+ case "aderror":
3950
+ case "error":
3951
+ return "adError";
3952
+ default:
3953
+ return name;
3954
+ }
3955
+ }
3956
+ var ImaAdsManagerStub = class {
3957
+ listeners = /* @__PURE__ */ new Map();
3958
+ addEventListener(type, listener) {
3959
+ if (!type || typeof listener !== "function") return;
3960
+ const eventName = normalizeImaEventName(type);
3961
+ let set = this.listeners.get(eventName);
3962
+ if (!set) {
3963
+ set = /* @__PURE__ */ new Set();
3964
+ this.listeners.set(eventName, set);
3965
+ }
3966
+ set.add(listener);
3967
+ }
3968
+ removeEventListener(type, listener) {
3969
+ if (!type || typeof listener !== "function") return;
3970
+ const eventName = normalizeImaEventName(type);
3971
+ const set = this.listeners.get(eventName);
3972
+ if (set) {
3973
+ set.delete(listener);
3974
+ if (set.size === 0) {
3975
+ this.listeners.delete(eventName);
3976
+ }
3977
+ }
3978
+ }
3979
+ dispatch(name, payload) {
3980
+ const eventName = normalizeImaEventName(name);
3981
+ const set = this.listeners.get(eventName);
3982
+ if (!set || set.size === 0) return;
3983
+ const event = this.createImaEvent(eventName, payload);
3984
+ for (const listener of Array.from(set)) {
3985
+ try {
3986
+ listener(event);
3987
+ } catch {
3988
+ }
3989
+ }
3990
+ }
3991
+ destroy() {
3992
+ this.listeners.clear();
3993
+ }
3994
+ createImaEvent(eventName, payload) {
3995
+ 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;
3996
+ const adObj = rawAd ? {
3997
+ getAdId: () => typeof rawAd.getAdId === "function" ? rawAd.getAdId() : rawAd.adId ?? rawAd.id ?? "",
3998
+ getCreativeId: () => typeof rawAd.getCreativeId === "function" ? rawAd.getCreativeId() : rawAd.creativeId ?? "",
3999
+ getTitle: () => typeof rawAd.getTitle === "function" ? rawAd.getTitle() : rawAd.title ?? "",
4000
+ getAdvertiserName: () => typeof rawAd.getAdvertiserName === "function" ? rawAd.getAdvertiserName() : rawAd.advertiser ?? rawAd.advertiserName ?? "",
4001
+ getDuration: () => typeof rawAd.getDuration === "function" ? rawAd.getDuration() : rawAd.duration ?? 0,
4002
+ adId: typeof rawAd.getAdId === "function" ? rawAd.getAdId() : rawAd.adId ?? rawAd.id ?? "",
4003
+ creativeId: typeof rawAd.getCreativeId === "function" ? rawAd.getCreativeId() : rawAd.creativeId ?? "",
4004
+ title: typeof rawAd.getTitle === "function" ? rawAd.getTitle() : rawAd.title ?? "",
4005
+ advertiserName: typeof rawAd.getAdvertiserName === "function" ? rawAd.getAdvertiserName() : rawAd.advertiser ?? rawAd.advertiserName ?? "",
4006
+ duration: typeof rawAd.getDuration === "function" ? rawAd.getDuration() : rawAd.duration ?? 0
4007
+ } : null;
4008
+ 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;
4009
+ const errorObj = rawError ? {
4010
+ getMessage: () => typeof rawError.getMessage === "function" ? rawError.getMessage() : rawError.message ?? String(rawError),
4011
+ getErrorCode: () => typeof rawError.getErrorCode === "function" ? rawError.getErrorCode() : rawError.code ?? rawError.errorCode ?? rawError.error_code,
4012
+ getVastErrorCode: () => typeof rawError.getVastErrorCode === "function" ? rawError.getVastErrorCode() : rawError.vastCode ?? rawError.vastErrorCode ?? rawError.vast_error_code,
4013
+ getType: () => typeof rawError.getType === "function" ? rawError.getType() : rawError.class ?? rawError.error_class ?? rawError.type ?? rawError.errorType ?? "other",
4014
+ message: typeof rawError.getMessage === "function" ? rawError.getMessage() : rawError.message ?? String(rawError),
4015
+ code: typeof rawError.getErrorCode === "function" ? rawError.getErrorCode() : rawError.code ?? rawError.errorCode ?? rawError.error_code,
4016
+ vastCode: typeof rawError.getVastErrorCode === "function" ? rawError.getVastErrorCode() : rawError.vastCode ?? rawError.vastErrorCode ?? rawError.vast_error_code,
4017
+ type: typeof rawError.getType === "function" ? rawError.getType() : rawError.class ?? rawError.error_class ?? rawError.type ?? rawError.errorType ?? "other"
4018
+ } : null;
4019
+ return {
4020
+ type: eventName,
4021
+ getAd: () => adObj,
4022
+ getError: () => errorObj,
4023
+ ad: adObj,
4024
+ error: errorObj
4025
+ };
4026
+ }
4027
+ };
3810
4028
 
3811
4029
  // src/index.ts
3812
4030
  function getbidkernel(alias = "bidkernel") {
@@ -3841,6 +4059,7 @@ function getbidkernel(alias = "bidkernel") {
3841
4059
  export {
3842
4060
  BidkernelPrebidAnalytics,
3843
4061
  CACHED_BID_TTL_MS,
4062
+ ImaAdsManagerStub,
3844
4063
  PrebidEventDeduper,
3845
4064
  attachImaAdsManager,
3846
4065
  attachVideoPlayer,
@@ -3851,6 +4070,7 @@ export {
3851
4070
  initImaInterception,
3852
4071
  isSessionActive,
3853
4072
  isTrustedEndpoint,
4073
+ normalizeImaEventName,
3854
4074
  onSessionResume,
3855
4075
  registerPrebidAnalytics
3856
4076
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bidkernel/analytics",
3
- "version": "0.21.0",
3
+ "version": "0.23.0",
4
4
  "description": "Bidkernel auction analytics: a standalone Prebid.js analytics adapter, plus TypeScript bindings for the Bidkernel ad SDK.",
5
5
  "keywords": [
6
6
  "advertising",