@bidkernel/analytics 0.7.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,19 +52,19 @@ analytics.enable();
52
52
 
53
53
  ## Configuration
54
54
 
55
- | Option | Default | Description |
56
- | ----------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------- |
57
- | `endpoint` | - | Ingest base URL; events POST to `{endpoint}/{propertyId}`. The standalone bundle defaults it to `https://by.bidkernel.io/t`. |
58
- | `propertyId` | - | Your Bidkernel property ID. |
59
- | `pbjsGlobalName` | `"pbjs"` | Window global holding the Prebid instance (for renamed installs). |
60
- | `attachPbjsListeners` | `true` | Set `false` when events are fed via `trackRawEvent` (full SDK mode). |
61
- | `auctionEnabled` | `true` | Collect auction lifecycle events. |
62
- | `warningsEnabled` | `true` | Collect warning events. |
63
- | `errorsEnabled` | `true` | Collect error events (capped per session). |
64
- | `userId` | `""` (empty) | **Not generated, you must pass it.** See [User identity](#user-identity). |
65
- | `sessionId` / `pageviewId` | generated | Override identity; a 30-minute rolling session is managed otherwise. |
66
- | `deviceType` / `country` / `region` | server-derived | Optional client hints; ingest resolves these server-side. |
67
- | `logLevel` | `"INFO"` | Console log verbosity. |
55
+ | Option | Default | Description |
56
+ | ----------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
57
+ | `endpoint` | - | Ingest base URL; events POST to `{endpoint}/{propertyId}`. The standalone bundle defaults it to `https://by.bidkernel.io/t`. Must be an absolute `https://` URL (plain `http://` only for loopback); an endpoint that fails validation is rejected and no events are sent. The first registration on a page pins the ingest origin -- a later `enableAnalytics` can change any other option but cannot redirect telemetry to a different origin. |
58
+ | `propertyId` | - | Your Bidkernel property ID. |
59
+ | `pbjsGlobalName` | `"pbjs"` | Window global holding the Prebid instance (for renamed installs). |
60
+ | `attachPbjsListeners` | `true` | Set `false` when events are fed via `trackRawEvent` (full SDK mode). |
61
+ | `auctionEnabled` | `true` | Collect auction lifecycle events. |
62
+ | `warningsEnabled` | `true` | Collect warning events. |
63
+ | `errorsEnabled` | `true` | Collect error events (capped per session). |
64
+ | `userId` | `""` (empty) | **Not generated, you must pass it.** See [User identity](#user-identity). |
65
+ | `sessionId` / `pageviewId` | generated | Override identity; a 30-minute rolling session is managed otherwise. |
66
+ | `deviceType` / `country` / `region` | server-derived | Optional client hints; ingest resolves these server-side. |
67
+ | `logLevel` | `"INFO"` | Console log verbosity. |
68
68
 
69
69
  SPA navigations: call `analytics.navigate(newPageviewId, newUrl)` to flush the old pageview and continue under the new one.
70
70
 
@@ -1 +1 @@
1
- "use strict";var bidkernelPrebidAnalyticsBundle=(()=>{var B=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ue=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);function de(){let n=0,e=0;for(let i=0;i<28;i+=7){let r=this.buf[this.pos++];if(n|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<i,(r&128)==0)return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function L(n,e,t){for(let s=0;s<28;s=s+7){let o=n>>>s,d=!(!(o>>>7)&&e==0),a=(d?o|128:o)&255;if(t.push(a),!d)return}let i=n>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?i|128:i)&255),!!r){for(let s=3;s<31;s=s+7){let o=e>>>s,d=!!(o>>>7),a=(d?o|128:o)&255;if(t.push(a),!d)return}t.push(e>>>31&1)}}function z(n){let e=n[0]==="-";e&&(n=n.slice(1));let t=1e6,i=0,r=0;function s(o,d){let a=Number(n.slice(o,d));r*=t,i=i*t+a,i>=V&&(r=r+(i/V|0),i=i%V)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?ce(i,r):Q(i,r)}function ae(n,e){let t=Q(n,e),i=t.hi&2147483648;i&&(t=ce(t.lo,t.hi));let r=Y(t.lo,t.hi);return i?"-"+r:r}function Y(n,e){if({lo:n,hi:e}=_e(n,e),e<=2097151)return String(V*e+n);let t=n&16777215,i=(n>>>24|e<<8)&16777215,r=e>>16&65535,s=t+i*6777216+r*6710656,o=i+r*8147497,d=r*2,a=1e7;return s>=a&&(o+=Math.floor(s/a),s%=a),o>=a&&(d+=Math.floor(o/a),o%=a),d.toString()+oe(o)+oe(s)}function _e(n,e){return{lo:n>>>0,hi:e>>>0}}function Q(n,e){return{lo:n|0,hi:e|0}}function ce(n,e){return e=~e,n?n=~n+1:e+=1,Q(n,e)}function j(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function le(){let n=this.buf[this.pos++],e=n&127;if((n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,(n&128)==0)return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,(n&128)==0)return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;(n&128)!==0&&t<10;t++)n=this.buf[this.pos++];if((n&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var V,oe,X=B(()=>{"use strict";V=4294967296;oe=n=>{let e=String(n);return"0000000".slice(e.length)+e}});function Pe(){let n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),r=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(o){let d=typeof o=="bigint"?o:BigInt(o);if(d>i||d<t)throw new Error(`invalid int64: ${o}`);return d},uParse(o){let d=typeof o=="bigint"?o:BigInt(o);if(d>s||d<r)throw new Error(`invalid uint64: ${o}`);return d},enc(o){return n.setBigInt64(0,this.parse(o),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(o){return n.setBigInt64(0,this.uParse(o),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(o,d){return n.setInt32(0,o,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(o,d){return n.setInt32(0,o,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(t){return typeof t!="string"&&(t=t.toString()),ue(t),t},uParse(t){return typeof t!="string"&&(t=t.toString()),fe(t),t},enc(t){return typeof t!="string"&&(t=t.toString()),ue(t),z(t)},uEnc(t){return typeof t!="string"&&(t=t.toString()),fe(t),z(t)},dec(t,i){return ae(t,i)},uDec(t,i){return Y(t,i)}}}function ue(n){if(!/^-?[0-9]+$/.test(n))throw new Error("invalid int64: "+n)}function fe(n){if(!/^[0-9]+$/.test(n))throw new Error("invalid uint64: "+n)}var R,he=B(()=>{"use strict";X();R=Pe()});function J(){if(globalThis[Z]==null){let n=new globalThis.TextEncoder,e=new globalThis.TextDecoder;globalThis[Z]={encodeUtf8(t){return n.encode(t)},decodeUtf8(t){return e.decode(t)},checkUtf8(t){try{return encodeURIComponent(t),!0}catch{return!1}}}}return globalThis[Z]}var Z,ee=B(()=>{"use strict";Z=Symbol.for("@bufbuild/protobuf/text-encoding")});function te(n){if(typeof n=="string")n=Number(n);else if(typeof n!="number")throw new Error("invalid int32: "+typeof n);if(!Number.isInteger(n)||n>Oe||n<Fe)throw new Error("invalid int32: "+n)}function pe(n){if(typeof n=="string")n=Number(n);else if(typeof n!="number")throw new Error("invalid uint32: "+typeof n);if(!Number.isInteger(n)||n>Le||n<0)throw new Error("invalid uint32: "+n)}function $e(n){if(typeof n=="string"){let e=n;if(n=Number(n),Number.isNaN(n)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof n!="number")throw new Error("invalid float32: "+typeof n);if(Number.isFinite(n)&&(n>Ne||n<Ve))throw new Error("invalid float32: "+n)}var D,Ne,Ve,Le,Oe,Fe,k,A,ye=B(()=>{"use strict";X();he();ee();(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(D||(D={}));Ne=34028234663852886e22,Ve=-34028234663852886e22,Le=4294967295,Oe=2147483647,Fe=-2147483648,k=class{constructor(e=J().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),i=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],i),i+=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(pe(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return te(e),j(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){$e(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){pe(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){te(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return te(e),e=(e<<1^e>>31)>>>0,j(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=R.enc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),r=R.uEnc(e);return i.setInt32(0,r.lo,!0),i.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=R.enc(e);return L(t.lo,t.hi,this.buf),this}sint64(e){let t=R.enc(e),i=t.hi>>31,r=t.lo<<1^i,s=(t.hi<<1|t.lo>>>31)^i;return L(r,s,this.buf),this}uint64(e){let t=R.uEnc(e);return L(t.lo,t.hi,this.buf),this}},A=class{constructor(e,t=J().decodeUtf8){this.decodeUtf8=t,this.varint64=de,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,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case D.Varint:for(;this.buf[this.pos++]&128;);break;case D.Bit64:this.pos+=4;case D.Bit32:this.pos+=4;break;case D.LengthDelimited:let r=this.uint32();this.pos+=r;break;case D.StartGroup:for(;;){let[s,o]=this.tag();if(o===D.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(o,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,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 R.dec(...this.varint64())}uint64(){return R.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,R.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 R.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return R.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 be=B(()=>{"use strict"});var Ie=B(()=>{"use strict"});var me=B(()=>{"use strict"});var Te=B(()=>{"use strict";ye();be();ee();Ie();me()});function ge(){return{propertyId:"",pageviewId:"",sessionId:"",pageUrl:"",country:"",region:"",deviceType:"",userId:"",domain:"",events:[],browser:"",deviceManufacturer:"",deviceModel:"",city:"",postalCode:""}}function Ee(){return{timestampMs:0,type:0,eventName:"",auctionId:"",transactionId:"",adUnitCode:"",bid:void 0,namespace:"",eventId:"",metadata:{},viewableDurationMs:void 0}}function ve(){return{key:"",value:""}}function we(){return{bidder:"",cpm:0,currency:"",width:0,height:0,dealId:"",mediaType:"",latencyMs:0,advertiserDomain:"",creativeId:""}}var f,$,O,ie,F,Se=B(()=>{"use strict";Te();f={TRACE_EVENT_TYPE_UNSPECIFIED:0,AUCTION_START:1,AUCTION_END:2,BID_REQUEST:3,BID_RESPONSE:4,BID_WIN:5,BID_TIMEOUT:6,IMPRESSION:7,VIEWABLE:8,TIME_IN_VIEW:14,REFRESH:9,ERROR:10,SLOT_DEFINED:11,SLOT_DESTROYED:12,CLICK:13,NO_BID:15,AD_RENDER_FAILED:16,UNRECOGNIZED:-1};$={encode(n,e=new k){if(n.propertyId!==void 0&&n.propertyId!==""&&e.uint32(10).string(n.propertyId),n.pageviewId!==void 0&&n.pageviewId!==""&&e.uint32(18).string(n.pageviewId),n.sessionId!==void 0&&n.sessionId!==""&&e.uint32(26).string(n.sessionId),n.pageUrl!==void 0&&n.pageUrl!==""&&e.uint32(34).string(n.pageUrl),n.country!==void 0&&n.country!==""&&e.uint32(42).string(n.country),n.region!==void 0&&n.region!==""&&e.uint32(50).string(n.region),n.deviceType!==void 0&&n.deviceType!==""&&e.uint32(58).string(n.deviceType),n.userId!==void 0&&n.userId!==""&&e.uint32(66).string(n.userId),n.domain!==void 0&&n.domain!==""&&e.uint32(74).string(n.domain),n.events!==void 0&&n.events.length!==0)for(let t of n.events)O.encode(t,e.uint32(82).fork()).join();return n.browser!==void 0&&n.browser!==""&&e.uint32(90).string(n.browser),n.deviceManufacturer!==void 0&&n.deviceManufacturer!==""&&e.uint32(98).string(n.deviceManufacturer),n.deviceModel!==void 0&&n.deviceModel!==""&&e.uint32(106).string(n.deviceModel),n.city!==void 0&&n.city!==""&&e.uint32(114).string(n.city),n.postalCode!==void 0&&n.postalCode!==""&&e.uint32(122).string(n.postalCode),e},decode(n,e){let t=n instanceof A?n:new A(n),i=e===void 0?t.len:t.pos+e,r=ge();for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==10)break;r.propertyId=t.string();continue}case 2:{if(s!==18)break;r.pageviewId=t.string();continue}case 3:{if(s!==26)break;r.sessionId=t.string();continue}case 4:{if(s!==34)break;r.pageUrl=t.string();continue}case 5:{if(s!==42)break;r.country=t.string();continue}case 6:{if(s!==50)break;r.region=t.string();continue}case 7:{if(s!==58)break;r.deviceType=t.string();continue}case 8:{if(s!==66)break;r.userId=t.string();continue}case 9:{if(s!==74)break;r.domain=t.string();continue}case 10:{if(s!==82)break;let o=O.decode(t,t.uint32());o!==void 0&&r.events.push(o);continue}case 11:{if(s!==90)break;r.browser=t.string();continue}case 12:{if(s!==98)break;r.deviceManufacturer=t.string();continue}case 13:{if(s!==106)break;r.deviceModel=t.string();continue}case 14:{if(s!==114)break;r.city=t.string();continue}case 15:{if(s!==122)break;r.postalCode=t.string();continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(n){return $.fromPartial(n??{})},fromPartial(n){let e=ge();return e.propertyId=n.propertyId??"",e.pageviewId=n.pageviewId??"",e.sessionId=n.sessionId??"",e.pageUrl=n.pageUrl??"",e.country=n.country??"",e.region=n.region??"",e.deviceType=n.deviceType??"",e.userId=n.userId??"",e.domain=n.domain??"",e.events=n.events?.map(t=>O.fromPartial(t))||[],e.browser=n.browser??"",e.deviceManufacturer=n.deviceManufacturer??"",e.deviceModel=n.deviceModel??"",e.city=n.city??"",e.postalCode=n.postalCode??"",e}};O={encode(n,e=new k){return n.timestampMs!==void 0&&n.timestampMs!==0&&e.uint32(9).double(n.timestampMs),n.type!==void 0&&n.type!==0&&e.uint32(16).int32(n.type),n.eventName!==void 0&&n.eventName!==""&&e.uint32(26).string(n.eventName),n.auctionId!==void 0&&n.auctionId!==""&&e.uint32(34).string(n.auctionId),n.transactionId!==void 0&&n.transactionId!==""&&e.uint32(42).string(n.transactionId),n.adUnitCode!==void 0&&n.adUnitCode!==""&&e.uint32(50).string(n.adUnitCode),n.bid!==void 0&&F.encode(n.bid,e.uint32(58).fork()).join(),n.namespace!==void 0&&n.namespace!==""&&e.uint32(66).string(n.namespace),n.eventId!==void 0&&n.eventId!==""&&e.uint32(74).string(n.eventId),globalThis.Object.entries(n.metadata||{}).forEach(([t,i])=>{ie.encode({key:t,value:i},e.uint32(82).fork()).join()}),n.viewableDurationMs!==void 0&&e.uint32(89).double(n.viewableDurationMs),e},decode(n,e){let t=n instanceof A?n:new A(n),i=e===void 0?t.len:t.pos+e,r=Ee();for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==9)break;r.timestampMs=t.double();continue}case 2:{if(s!==16)break;r.type=t.int32();continue}case 3:{if(s!==26)break;r.eventName=t.string();continue}case 4:{if(s!==34)break;r.auctionId=t.string();continue}case 5:{if(s!==42)break;r.transactionId=t.string();continue}case 6:{if(s!==50)break;r.adUnitCode=t.string();continue}case 7:{if(s!==58)break;r.bid=F.decode(t,t.uint32());continue}case 8:{if(s!==66)break;r.namespace=t.string();continue}case 9:{if(s!==74)break;r.eventId=t.string();continue}case 10:{if(s!==82)break;let o=ie.decode(t,t.uint32());o.value!==void 0&&(r.metadata[o.key]=o.value);continue}case 11:{if(s!==89)break;r.viewableDurationMs=t.double();continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(n){return O.fromPartial(n??{})},fromPartial(n){let e=Ee();return e.timestampMs=n.timestampMs??0,e.type=n.type??0,e.eventName=n.eventName??"",e.auctionId=n.auctionId??"",e.transactionId=n.transactionId??"",e.adUnitCode=n.adUnitCode??"",e.bid=n.bid!==void 0&&n.bid!==null?F.fromPartial(n.bid):void 0,e.namespace=n.namespace??"",e.eventId=n.eventId??"",e.metadata=globalThis.Object.entries(n.metadata??{}).reduce((t,[i,r])=>(r!==void 0&&(t[i]=globalThis.String(r)),t),{}),e.viewableDurationMs=n.viewableDurationMs??void 0,e}};ie={encode(n,e=new k){return n.key!==""&&e.uint32(10).string(n.key),n.value!==""&&e.uint32(18).string(n.value),e},decode(n,e){let t=n instanceof A?n:new A(n),i=e===void 0?t.len:t.pos+e,r=ve();for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==10)break;r.key=t.string();continue}case 2:{if(s!==18)break;r.value=t.string();continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(n){return ie.fromPartial(n??{})},fromPartial(n){let e=ve();return e.key=n.key??"",e.value=n.value??"",e}};F={encode(n,e=new k){return n.bidder!==void 0&&n.bidder!==""&&e.uint32(10).string(n.bidder),n.cpm!==void 0&&n.cpm!==0&&e.uint32(17).double(n.cpm),n.currency!==void 0&&n.currency!==""&&e.uint32(26).string(n.currency),n.width!==void 0&&n.width!==0&&e.uint32(32).int32(n.width),n.height!==void 0&&n.height!==0&&e.uint32(40).int32(n.height),n.dealId!==void 0&&n.dealId!==""&&e.uint32(50).string(n.dealId),n.mediaType!==void 0&&n.mediaType!==""&&e.uint32(58).string(n.mediaType),n.latencyMs!==void 0&&n.latencyMs!==0&&e.uint32(65).double(n.latencyMs),n.advertiserDomain!==void 0&&n.advertiserDomain!==""&&e.uint32(74).string(n.advertiserDomain),n.creativeId!==void 0&&n.creativeId!==""&&e.uint32(82).string(n.creativeId),e},decode(n,e){let t=n instanceof A?n:new A(n),i=e===void 0?t.len:t.pos+e,r=we();for(;t.pos<i;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==10)break;r.bidder=t.string();continue}case 2:{if(s!==17)break;r.cpm=t.double();continue}case 3:{if(s!==26)break;r.currency=t.string();continue}case 4:{if(s!==32)break;r.width=t.int32();continue}case 5:{if(s!==40)break;r.height=t.int32();continue}case 6:{if(s!==50)break;r.dealId=t.string();continue}case 7:{if(s!==58)break;r.mediaType=t.string();continue}case 8:{if(s!==65)break;r.latencyMs=t.double();continue}case 9:{if(s!==74)break;r.advertiserDomain=t.string();continue}case 10:{if(s!==82)break;r.creativeId=t.string();continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(n){return F.fromPartial(n??{})},fromPartial(n){let e=we();return e.bidder=n.bidder??"",e.cpm=n.cpm??0,e.currency=n.currency??"",e.width=n.width??0,e.height=n.height??0,e.dealId=n.dealId??"",e.mediaType=n.mediaType??"",e.latencyMs=n.latencyMs??0,e.advertiserDomain=n.advertiserDomain??"",e.creativeId=n.creativeId??"",e}}});function U(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Je(n){let e="";for(let i=0;i<n.length;i+=8192)e+=String.fromCharCode(...n.subarray(i,i+8192));return btoa(e)}function et(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function De(){let n=Date.now();P=n;try{typeof localStorage<"u"&&localStorage.setItem(H,n.toString())}catch{}}function tt(){let n=Date.now();try{if(typeof localStorage<"u"){let e=localStorage.getItem(xe),t=localStorage.getItem(H),i=t&&parseInt(t,10)||0;if(e&&i&&n-i<=Be)return localStorage.setItem(H,n.toString()),e;let r=U();return localStorage.setItem(xe,r),localStorage.setItem(H,n.toString()),r}}catch{}return K&&P&&n-P<=Be?(P=n,K):(K=U(),P=n,K)}function u(n){return String(n??"").replace(/%/g,"%25").replace(/:/g,"%3A")}function it(n,e){switch(n){case"auctionInit":return`auctionInit:${u(e?.auctionId)}`;case"auctionEnd":return`auctionEnd:${u(e?.auctionId)}`;case"bidRequested":{let t=Array.isArray(e?.bids)?e.bids.map(i=>u(i?.bidId||i?.transactionId||i?.adUnitCode)).join(","):"";return`bidRequested:${u(e?.auctionId)}:${u(e?.bidderCode||e?.bidder)}:${t}`}case"bidResponse":{let t=e||{},i=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidResponse:${u(t.auctionId)}:${u(t.adUnitCode)}:${u(t.bidderCode||t.bidder)}:${u(i)}:${u(r)}`}case"bidTimeout":return"bidTimeout:"+(Array.isArray(e)?e:e?[e]:[]).map(i=>`${u(i?.auctionId)}:${u(i?.bidderCode||i?.bidder)}:${u(i?.bidId||i?.transactionId||i?.adUnitCode)}`).join(",");case"bidWon":{let t=e||{},i=t.creativeId||t.adId||t.requestId||t.bidId||"",r=t.originalCpm??t.cpm??"";return`bidWon:${u(t.auctionId)}:${u(t.adUnitCode)}:${u(t.bidderCode||t.bidder)}:${u(i)}:${u(r)}`}case"noBid":return`noBid:${u(e?.auctionId)}:${u(e?.adUnitCode)}:${u(e?.bidderCode||e?.bidder)}:${u(e?.bidId||e?.transactionId)}`;case"adRenderFailed":{let t=e?.bid||{};return`adRenderFailed:${u(t.auctionId||e?.auctionId)}:${u(t.adUnitCode||e?.adUnitCode)}:${u(t.bidderCode||t.bidder||e?.bidderCode||e?.bidder)}:${u(e?.reason)}:${u(e?.message)}`}case"adRenderSucceeded":{let t=e?.bid||e||{},i=t.creativeId||t.adId||e?.adId||"",r=t.originalCpm??t.cpm??"";return`adRenderSucceeded:${u(t.auctionId||e?.auctionId)}:${u(t.adUnitCode||e?.adUnitCode)}:${u(t.bidderCode||t.bidder)}:${u(i)}:${u(r)}`}case"setTargeting":return`setTargeting:${Object.keys(e||{}).sort().map(u).join(",")}`;case"auctionDebug":return`auctionDebug:${u(e?.type)}:${u(String(e?.arguments?.[0]??"").slice(0,50))}`;default:return""}}function Ce(n){if(!n)return{width:0,height:0};let e=n;for(;Array.isArray(e)&&e.length>0&&Array.isArray(e[0]);)e=e[0];if(Array.isArray(e)&&e.length>=2){let t=Number(e[0]),i=Number(e[1]);return{width:Number.isFinite(t)?t:0,height:Number.isFinite(i)?i:0}}return{width:0,height:0}}function C(n){if(Number.isFinite(n?.width)&&Number.isFinite(n?.height))return{width:n.width,height:n.height};if(typeof n?.size=="string"){let e=n.size.match(/^(\d+)x(\d+)$/);if(e)return{width:Number(e[1]),height:Number(e[2])}}return{width:Number.isFinite(n?.width)?n.width:0,height:Number.isFinite(n?.height)?n.height:0}}function _(n){if(!n)return null;if(Array.isArray(n)){let e=n.find(t=>t?.provider==="bidkernel")??n.find(t=>t&&typeof t=="object"&&t.provider===void 0);return e?_(e):null}if(typeof n=="object"){if(n.options&&typeof n.options=="object")return n.options;if(n.config&&typeof n.config=="object")return n.config;if(n.propertyId||n.endpoint)return n}return null}function nt(n){if(!n)return null;if(n._bidkernelAnalyticsConfig){let e=_(n._bidkernelAnalyticsConfig);if(e)return e}if(n.bidkernelPrebidAnalytics){let e=n.bidkernelPrebidAnalytics;if(e.options){let t=_(e.options);if(t)return t}if(e.config){let t=_(e.config);if(t)return t}if(e.propertyId)return _(e)}return null}function se(n="pbjs",e){let t=typeof window<"u"?window:{};t[n]=t[n]||{};let i=t[n],r=o=>{if(t._bidkernelPrebidAnalytics)try{t._bidkernelPrebidAnalytics.disable()}catch(a){console.warn("[bidkernel] Failed to disable previous analytics instance:",a)}let d=new re({pbjsGlobalName:n,...e,...o});return d.enable(),t._bidkernelPrebidAnalytics=d,d},s=()=>{try{i.adapterManager&&typeof i.adapterManager.registerAnalyticsAdapter=="function"&&i.adapterManager.registerAnalyticsAdapter({adapter:{enableAnalytics:d=>{let a=_(d);a&&r(a)},disableAnalytics:()=>{t._bidkernelPrebidAnalytics&&t._bidkernelPrebidAnalytics.disable()}},code:"bidkernel"});let o=nt(t);o&&(o.propertyId||e?.propertyId)&&r(o)}catch(o){console.warn("[bidkernel] Failed to register standard Prebid analytics adapter:",o)}};i.adapterManager&&typeof i.adapterManager.registerAnalyticsAdapter=="function"?s():(i.que=i.que||[],i.que.push(s))}var We,Re,Ke,q,He,Ge,ze,Ae,W,Ye,Qe,je,Xe,Ze,xe,H,Be,K,P,ne,re,ke=B(()=>{"use strict";Se();We=20,Re=1e4,Ke=50,q=200,He=300*1e3,Ge=10,ze=32*1024,Ae="text/plain",W="_bidkernel_pending_",Ye=20,Qe=7200*1e3,je=1e4,Xe={auctionStart:f.AUCTION_START,auctionEnd:f.AUCTION_END,bidRequest:f.BID_REQUEST,bidResponse:f.BID_RESPONSE,bidTimeout:f.BID_TIMEOUT,bidWin:f.BID_WIN,noBid:f.NO_BID,adRenderFailed:f.AD_RENDER_FAILED,click:f.CLICK,impression:f.IMPRESSION,refresh:f.REFRESH,timeInView:f.TIME_IN_VIEW,viewable:f.VIEWABLE},Ze=new Set([f.IMPRESSION,f.BID_WIN,f.CLICK]),xe="_bidkernel_session",H="_bidkernel_session_ts",Be=1800*1e3,K=null,P=0;ne=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 i=it(e,t);if(i){if(this.seenKeys.has(i))return!0;if(this.seenKeys.size>=1e3){let r=this.seenKeys.values().next().value;r!==void 0&&this.seenKeys.delete(r)}this.seenKeys.add(i)}return!1}};re=class n{static activeInstances=new Set;config;queue=[];errorCount=0;flushTimer=null;boundFlushBeacon;boundVisibilityChange;isEnabled=!1;boundPbjsHandlers=[];pageUrl="";deduper=new ne;consecutiveSendFailures=0;nextSendAllowedAt=0;replayedEventCount=0;immediateFlushScheduled=!1;persistedBatchKeys=[];persistedCleanupTimer=null;intersectionObserver=null;slotViewabilityRecords=new Map;elementToSlotId=new Map;slotRefreshIndices=new Map;slotLastAuctionIds=new Map;pendingThresholdListeners=new Map;slotEmittedImpressionKeys=new Set;cachedWinningBids=new Map;videoDetachCleanups=new Set;constructor(e){this.config={endpoint:e.endpoint||"",propertyId:e.propertyId||"",pageviewId:e.pageviewId||U(),sessionId:e.sessionId||tt(),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,logLevel:e.logLevel||"INFO",pbjsGlobalName:e.pbjsGlobalName||"pbjs",attachPbjsListeners:e.attachPbjsListeners??!0},this.boundFlushBeacon=()=>{this.flushAllSlotsTimeInView(),this.flushBeacon()},this.boundVisibilityChange=()=>this.handleVisibilityChange()}enable(){if(!this.isEnabled){if(this.isEnabled=!0,n.activeInstances.add(this),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){let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.onEvent=="function"){this.log("DEBUG","Attaching event listeners to pbjs");let i=[["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,s]of i)t.onEvent(r,s),this.boundPbjsHandlers.push({event:r,handler:s})}else this.log("WARN","pbjs.onEvent is not defined. Prebid analytics will not function.");if(typeof t.getEvents=="function")try{let i=t.getEvents();if(Array.isArray(i)){let r=i.slice(this.replayedEventCount);if(this.replayedEventCount=i.length,r.length>0){this.log("DEBUG",`Replaying ${r.length} historical events from pbjs.getEvents()`);let s={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 o of r){if(!o)continue;let d=o.eventType||o.event||o.name,a=o.args!==void 0?o.args:o.data!==void 0?o.data:o,l=s[d];l&&l(a)}}}}catch(i){this.log("WARN","Failed to replay historical events from pbjs.getEvents()",i)}}if(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),this.flushTimer=setInterval(()=>this.flush(),Re),this.resendPersistedBatches()}}}disable(){if(this.isEnabled){this.flushAllSlotsTimeInView(),this.isEnabled=!1,n.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{}if(this.videoDetachCleanups.clear(),this.cachedWinningBids.clear(),this.slotEmittedImpressionKeys.clear(),this.slotLastAuctionIds.clear(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=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:i,handler:r}of this.boundPbjsHandlers)t.offEvent(i,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 i=Math.round(t.accumulatedTimeInViewMs);i>0&&this.enqueue(f.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:i,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 i=t.mediaType==="video"?2e3:1e3;t.dwellStartedAt=e,t.dwellTimer=setTimeout(()=>{this.handleDwellComplete(t)},i)}this.scheduleThresholdTimers(t)}}}}handleIntersection(e){for(let t of e){let i=this.elementToSlotId.get(t.target);if(!i){for(let a of n.activeInstances)if(a!==this&&a.elementToSlotId.has(t.target)){a.handleIntersection([t]);break}continue}let r=this.slotViewabilityRecords.get(i);if(!r)continue;let s=t.isIntersecting&&(t.intersectionRatio===void 0||t.intersectionRatio>=.5),o=typeof document>"u"||document.visibilityState==="visible",d=typeof performance<"u"&&performance.now?performance.now():Date.now();if(s){if(!r.inView&&(r.inView=!0,o)){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(f.VIEWABLE,"viewable",{auctionId:e.auctionId,transactionId:e.transactionId,adUnitCode:e.adUnitCode,bid:e.bidPayload,metadata:{...e.metadata,refresh_index:String(e.refreshIndex)}})))}scheduleThresholdTimers(e){if(!e.inView||typeof document<"u"&&document.visibilityState==="hidden")return;let t=this.getCurrentTimeInView(e);for(let i of e.thresholdListeners)if(!i.fired)if(t>=i.thresholdMs){i.fired=!0,i.timer&&(clearTimeout(i.timer),i.timer=null);try{i.callback(e.slotId,t)}catch(r){this.log("ERROR","Error in threshold listener callback",r)}}else{i.timer&&clearTimeout(i.timer);let r=i.thresholdMs-t;i.timer=setTimeout(()=>{if(i.timer=null,!i.fired&&e.inView&&(typeof document>"u"||document.visibilityState==="visible")){let s=this.getCurrentTimeInView(e);if(s>=i.thresholdMs){i.fired=!0;try{i.callback(e.slotId,s)}catch(o){this.log("ERROR","Error in threshold listener callback",o)}}}},r)}}checkThresholdListeners(e){let t=this.getCurrentTimeInView(e);for(let i of e.thresholdListeners)if(!i.fired&&t>=i.thresholdMs){i.fired=!0,i.timer&&(clearTimeout(i.timer),i.timer=null);try{i.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 i=typeof performance<"u"&&performance.now?performance.now():Date.now();t+=Math.max(0,i-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 i=Math.round(t.accumulatedTimeInViewMs);i>0&&this.enqueue(f.TIME_IN_VIEW,"timeInView",{auctionId:t.auctionId,transactionId:t.transactionId,adUnitCode:t.adUnitCode,viewableDurationMs:i,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,i){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 s=t||i?.adUnitCode||(r?r.id:"")||U(),o=this.slotViewabilityRecords.get(s);if(o){if(i?.refreshIndex===void 0||i.refreshIndex>o.refreshIndex){this.flushSlotTimeInView(s);let a=i?.refreshIndex!==void 0?i.refreshIndex:(this.slotRefreshIndices.get(s)??o.refreshIndex)+1;this.slotRefreshIndices.set(s,a),i?.emitRefreshEvent!==!1&&this.enqueue(f.REFRESH,"refresh",{auctionId:i?.auctionId||o.auctionId,transactionId:i?.transactionId||o.transactionId,adUnitCode:s,bid:i?.bid??o.bidPayload,metadata:{...i?.metadata,refresh_index:String(a)}}),o.dwellTimer&&(clearTimeout(o.dwellTimer),o.dwellTimer=null,o.dwellStartedAt=null);for(let I of o.thresholdListeners)I.fired=!1,I.timer&&(clearTimeout(I.timer),I.timer=null);o.viewableFired=!1,o.accumulatedTimeInViewMs=0;let l=typeof performance<"u"&&performance.now?performance.now():Date.now();if(o.lastEnteredViewAt=o.inView?l:null,o.refreshIndex=a,o.auctionId=i?.auctionId||o.auctionId,o.transactionId=i?.transactionId||o.transactionId,o.mediaType=i?.mediaType||o.mediaType||"banner",o.bidPayload=i?.bid!==void 0?i.bid:o.bidPayload,o.metadata=i?.metadata??o.metadata,o.inView&&(typeof document>"u"||document.visibilityState==="visible")){let I=o.mediaType==="video"?2e3:1e3;o.dwellStartedAt=l,o.dwellTimer=setTimeout(()=>{this.handleDwellComplete(o)},I),this.scheduleThresholdTimers(o)}}else o.auctionId=i?.auctionId||o.auctionId,o.transactionId=i?.transactionId||o.transactionId,o.mediaType=i?.mediaType||o.mediaType,i?.bid!==void 0&&(o.bidPayload=i.bid),i?.metadata!==void 0&&(o.metadata=i.metadata);i?.auctionId&&this.slotLastAuctionIds.set(s,i.auctionId),r&&(o.element&&o.element!==r&&this.intersectionObserver&&(this.intersectionObserver.unobserve(o.element),this.elementToSlotId.delete(o.element)),o.element=r,this.elementToSlotId.set(r,s),this.intersectionObserver?.observe(r))}else{let d=i?.refreshIndex??this.slotRefreshIndices.get(s)??0;this.slotRefreshIndices.set(s,d),i?.auctionId&&this.slotLastAuctionIds.set(s,i.auctionId);let a=this.pendingThresholdListeners.get(s)||new Set;this.pendingThresholdListeners.delete(s);let l={slotId:s,element:r,adUnitCode:i?.adUnitCode||s,auctionId:i?.auctionId||"",transactionId:i?.transactionId||"",mediaType:i?.mediaType||"banner",bidPayload:i?.bid,metadata:i?.metadata,refreshIndex:d,inView:!1,lastEnteredViewAt:null,accumulatedTimeInViewMs:0,viewableFired:!1,dwellTimer:null,dwellStartedAt:null,thresholdListeners:a};this.slotViewabilityRecords.set(s,l),r&&(this.elementToSlotId.set(r,s),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 i of t.thresholdListeners)i.timer&&(clearTimeout(i.timer),i.timer=null);t.thresholdListeners=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);let t=`${u(e)}:`;for(let i of Array.from(this.slotEmittedImpressionKeys))(i===e||i.startsWith(t))&&this.slotEmittedImpressionKeys.delete(i);this.cachedWinningBids.delete(e)}hasImpressionEmitted(e,t,i,r){let s=t??this.slotRefreshIndices.get(e)??0,o=`${u(e)}:${s}`;return r?i?this.slotEmittedImpressionKeys.has(`${o}:auc:${u(i)}:${u(r)}`)||this.slotEmittedImpressionKeys.has(`${o}:${u(r)}`):this.slotEmittedImpressionKeys.has(`${o}:${u(r)}`):i?this.slotEmittedImpressionKeys.has(`${o}:auc:${u(i)}`):this.slotEmittedImpressionKeys.has(o)}markImpressionEmitted(e,t,i,r){let s=`${u(e)}:${t}`;this.slotEmittedImpressionKeys.add(s),r&&this.slotEmittedImpressionKeys.add(`${s}:${u(r)}`),i&&(this.slotEmittedImpressionKeys.add(`${s}:auc:${u(i)}`),r&&this.slotEmittedImpressionKeys.add(`${s}:auc:${u(i)}:${u(r)}`))}recordImpression(e,t){if(!this.isEnabled)return!1;let i=e||t?.adUnitCode||"",r=t?.adUnitCode||i,s=(t?.auctionId&&i?this.cachedWinningBids.get(`${t.auctionId}:${i}`):void 0)||(t?.auctionId&&r?this.cachedWinningBids.get(`${t.auctionId}:${r}`):void 0)||(i?this.cachedWinningBids.get(i):void 0)||(r?this.cachedWinningBids.get(r):void 0),o=t?.bid||s?.rawBid||{},d=t?.auctionId||o.auctionId||s?.auctionId||"",a=t?.transactionId||o.transactionId||s?.transactionId||"",l=o.creativeId||s?.bidTrace?.creativeId||t?.bid?.creativeId||"",I=t?.mediaType||o.mediaType||s?.bidTrace?.mediaType||"banner",y=i||r,h=(i?this.slotViewabilityRecords.get(i):void 0)||(r?this.slotViewabilityRecords.get(r):void 0),b=y?this.slotLastAuctionIds.get(y)||(h?h.auctionId:void 0):void 0,x=!!(y&&d&&b&&b!==d&&t?.refreshIndex===void 0),w={bidder:o.bidderCode||o.bidder||s?.bidTrace?.bidder||"",cpm:Number.isFinite(o.originalCpm)?o.originalCpm:Number.isFinite(o.cpm)?o.cpm:s?.bidTrace?.cpm??0,currency:o.originalCurrency??o.currency??s?.bidTrace?.currency??"USD",...C(o).width?C(o):s?.bidTrace?{width:s.bidTrace.width,height:s.bidTrace.height}:C(o),dealId:o.dealId||s?.bidTrace?.dealId||"",mediaType:I,latencyMs:Number.isFinite(o.timeToRespond)?o.timeToRespond:s?.bidTrace?.latencyMs??0,advertiserDomain:o.meta?.advertiserDomains?.[0]||s?.bidTrace?.advertiserDomain||"",creativeId:o.creativeId||s?.bidTrace?.creativeId||""};if(x&&y){this.flushSlotTimeInView(y);let c=(this.slotRefreshIndices.get(y)??(h?h.refreshIndex:0))+1;this.slotRefreshIndices.set(y,c),this.slotLastAuctionIds.set(y,d),h&&(h.refreshIndex=c,h.auctionId=d,h.transactionId=a,h.bidPayload=w,h.viewableFired=!1,h.accumulatedTimeInViewMs=0),this.enqueue(f.REFRESH,"refresh",{auctionId:d,transactionId:a,adUnitCode:y,bid:w,metadata:{...t?.metadata,refresh_index:String(c)}})}else y&&(d&&this.slotLastAuctionIds.set(y,d),this.slotRefreshIndices.has(y)||this.slotRefreshIndices.set(y,0));let g=t?.refreshIndex??(i?this.slotRefreshIndices.get(i)??(r?this.slotRefreshIndices.get(r):void 0)??(h?h.refreshIndex:0):0);return i&&this.hasImpressionEmitted(i,g,d,l)||r&&r!==i&&this.hasImpressionEmitted(r,g,d,l)?(this.log("DEBUG",`Impression already emitted for slot ${i||r} in cycle ${g}`),!1):(i&&this.markImpressionEmitted(i,g,d,l),r&&r!==i&&this.markImpressionEmitted(r,g,d,l),this.enqueue(f.IMPRESSION,"impression",{auctionId:d,transactionId:a,adUnitCode:r,bid:w,metadata:{...t?.metadata,refresh_index:String(g)}}),h&&(!h.bidPayload&&w&&(h.bidPayload=w),!h.auctionId&&d&&(h.auctionId=d),!h.transactionId&&a&&(h.transactionId=a)),!0)}attachImaAdsManager(e,t){if(!e||typeof e.addEventListener!="function")return this.log("WARN","Invalid AdsManager passed to attachImaAdsManager"),()=>{};let i=t?.slotId||t?.adUnitCode||"video",r=t?.adUnitCode||i,s=t?.auctionId||"",o=t?.transactionId||"",d=()=>(s?this.cachedWinningBids.get(`${s}:${r}`):void 0)||(s&&i!==r?this.cachedWinningBids.get(`${s}:${i}`):void 0)||this.cachedWinningBids.get(r)||(i!==r?this.cachedWinningBids.get(i):void 0),a=m=>{this.log("DEBUG","IMA AdEvent.STARTED / IMPRESSION received",m);let c=typeof m?.getAd=="function"?m.getAd():m?.ad,T={};c&&(T.creativeId=(typeof c.getCreativeId=="function"?c.getCreativeId():c.creativeId)||"",T.adId=(typeof c.getAdId=="function"?c.getAdId():c.id)||"",T.title=(typeof c.getTitle=="function"?c.getTitle():c.title)||"",T.duration=typeof c.getDuration=="function"?c.getDuration():c.duration,T.advertiserName=typeof c.getAdvertiserName=="function"?c.getAdvertiserName():"");let S=d(),p={...S?.rawBid||t?.bid,mediaType:"video",creativeId:T.creativeId||S?.bidTrace?.creativeId||t?.bid?.creativeId||""};if(this.recordImpression(i,{adUnitCode:r,auctionId:s||S?.auctionId,transactionId:o||S?.transactionId,mediaType:"video",bid:p,metadata:{...t?.metadata,media_type:"video",...T.title?{ad_title:T.title}:{},...Number.isFinite(T.duration)?{ad_duration_s:String(T.duration)}:{}}})&&t?.onImpression)try{t.onImpression(i,{ad:c,bid:p})}catch(v){this.log("ERROR","Error in onImpression callback",v)}},l=m=>{if(this.log("DEBUG",`IMA AdEvent milestone: ${m}`),t?.onMilestone)try{t.onMilestone(m,i)}catch(c){this.log("ERROR","Error in onMilestone callback",c)}},I=m=>{this.log("DEBUG","IMA AdEvent.CLICK received",m);let c=d();this.enqueue(f.CLICK,"click",{auctionId:s||c?.auctionId,transactionId:o||c?.transactionId,adUnitCode:r,bid:c?.bidTrace||t?.bid,metadata:{...t?.metadata,media_type:"video"}})},y=m=>{this.log("WARN","IMA AdErrorEvent received",m);let c=typeof m?.getError=="function"?m.getError():m?.error||m,T=(c&&typeof c.getMessage=="function"?c.getMessage():c?.message)||String(c||"IMA ad error"),S=(c&&typeof c.getErrorCode=="function"?c.getErrorCode():c?.code)||"",p=d();if(this.enqueue(f.AD_RENDER_FAILED,"adRenderFailed",{auctionId:s||p?.auctionId,transactionId:o||p?.transactionId,adUnitCode:r,bid:p?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"ima_ad_error",message:T,...S?{ima_error_code:String(S)}:{}},error:typeof c=="object"?c:new Error(T)}),t?.onError)try{t.onError(c)}catch(E){this.log("ERROR","Error in onError callback",E)}},h=typeof window<"u"?window.google?.ima:void 0,b=h?.AdEvent?.Type||{},x=h?.AdErrorEvent?.Type||{},w=[{type:b.STARTED||"started",handler:a},{type:b.IMPRESSION||"impression",handler:a},{type:b.FIRST_QUARTILE||"firstQuartile",handler:()=>l("firstQuartile")},{type:b.MIDPOINT||"midpoint",handler:()=>l("midpoint")},{type:b.THIRD_QUARTILE||"thirdQuartile",handler:()=>l("thirdQuartile")},{type:b.COMPLETE||"complete",handler:()=>l("complete")},{type:b.CLICK||"click",handler:I},{type:x.AD_ERROR||"adError",handler:y}];for(let{type:m,handler:c}of w)try{e.addEventListener(m,c)}catch{}let g=()=>{for(let{type:m,handler:c}of w)try{e.removeEventListener(m,c)}catch{}this.videoDetachCleanups.delete(g)};return this.videoDetachCleanups.add(g),g}attachVideoPlayer(e,t){if(!e)return this.log("WARN","attachVideoPlayer called with null/undefined target"),()=>{};let i=null;if(typeof e=="string"){if(typeof document<"u")try{i=document.querySelector(e)||document.getElementById(e)}catch{i=document.getElementById(e)}}else if(typeof HTMLElement<"u"&&e instanceof HTMLElement)i=e;else if(e&&typeof e=="object"&&e.nodeType===1)i=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 this.attachImaAdsManager(e,t);e&&typeof e.addEventListener=="function"&&(i=e)}let r=t?.slotId||t?.adUnitCode||(i?i.id:"")||"video",s=t?.adUnitCode||r,o=t?.auctionId||"",d=t?.transactionId||"",a=()=>(o?this.cachedWinningBids.get(`${o}:${s}`):void 0)||(o&&r!==s?this.cachedWinningBids.get(`${o}:${r}`):void 0)||this.cachedWinningBids.get(s)||(r!==s?this.cachedWinningBids.get(r):void 0),l=null;i&&(i.tagName&&i.tagName.toLowerCase()==="video"?l=i:l=i.querySelector("video"));let I={q1:!1,q2:!1,q3:!1,q4:!1},y=p=>{let E=p||l||(i?.querySelector?i.querySelector("video"):null),v=a(),M={...v?.rawBid||t?.bid,mediaType:"video"};if(this.recordImpression(r,{adUnitCode:s,auctionId:o||v?.auctionId,transactionId:d||v?.transactionId,mediaType:"video",bid:M,metadata:{...t?.metadata,media_type:"video",...E&&Number.isFinite(E.duration)?{video_duration_s:String(Math.round(E.duration))}:{}}})&&t?.onImpression)try{t.onImpression(r,{element:E||i,bid:M})}catch(G){this.log("ERROR","Error in onImpression callback",G)}},h=p=>{this.log("DEBUG","HTML5 video playing event received");let E=p?.target instanceof HTMLVideoElement?p.target:l;y(E)},b=p=>{let E=p?.target instanceof HTMLVideoElement?p.target:l;if(E&&E.currentTime>0&&(y(E),Number.isFinite(E.duration)&&E.duration>0)){let v=E.currentTime/E.duration;v>=.25&&!I.q1&&(I.q1=!0,t?.onMilestone?.("firstQuartile",r)),v>=.5&&!I.q2&&(I.q2=!0,t?.onMilestone?.("midpoint",r)),v>=.75&&!I.q3&&(I.q3=!0,t?.onMilestone?.("thirdQuartile",r))}},x=()=>{I.q4||(I.q4=!0,t?.onMilestone?.("complete",r))},w=p=>{let v=(p?.target instanceof HTMLVideoElement?p.target:l)?.error||l?.error,M=a(),N=v?`HTML5 video error code ${v.code}: ${v.message}`:"Video playback error";if(this.log("WARN",N),this.enqueue(f.AD_RENDER_FAILED,"adRenderFailed",{auctionId:o||M?.auctionId,transactionId:d||M?.transactionId,adUnitCode:s,bid:M?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"html5_video_error",message:N,...v?.code?{video_error_code:String(v.code)}:{}},error:v?new Error(N):void 0}),t?.onError)try{t.onError(v)}catch(G){this.log("ERROR","Error in onError callback",G)}},g=p=>{p.addEventListener("playing",h),p.addEventListener("play",h),p.addEventListener("timeupdate",b),p.addEventListener("ended",x),p.addEventListener("error",w)},m=p=>{p.removeEventListener("playing",h),p.removeEventListener("play",h),p.removeEventListener("timeupdate",b),p.removeEventListener("ended",x),p.removeEventListener("error",w)},c=null;i&&i!==l&&(i.addEventListener("playing",h,!0),i.addEventListener("play",h,!0),i.addEventListener("timeupdate",b,!0),i.addEventListener("ended",x,!0),i.addEventListener("error",w,!0)),l&&g(l),i&&i.tagName?.toLowerCase()!=="video"&&typeof MutationObserver<"u"&&(c=new MutationObserver(()=>{let p=i.querySelector("video");p&&p!==l&&(l&&m(l),l=p,l&&g(l))}),c.observe(i,{childList:!0,subtree:!0}));let T=a();t?.trackViewability!==!1&&i&&this.observeSlot(i,r,{adUnitCode:s,auctionId:o||T?.auctionId,transactionId:d||T?.transactionId,mediaType:"video",bid:T?.bidTrace||t?.bid,metadata:t?.metadata,emitRefreshEvent:!1});let S=()=>{c&&(c.disconnect(),c=null),i&&i!==l&&(i.removeEventListener("playing",h,!0),i.removeEventListener("play",h,!0),i.removeEventListener("timeupdate",b,!0),i.removeEventListener("ended",x,!0),i.removeEventListener("error",w,!0)),l&&m(l),this.videoDetachCleanups.delete(S)};return this.videoDetachCleanups.add(S),S}onTimeInViewThreshold(e,t,i){let r={thresholdMs:t,callback:i,timer:null,fired:!1},s=this.slotViewabilityRecords.get(e);if(s){s.thresholdListeners.add(r);let o=this.getCurrentTimeInView(s);if(o>=t){r.fired=!0;try{i(e,o)}catch(d){this.log("ERROR","Error in threshold callback",d)}}else if(s.inView&&(typeof document>"u"||document.visibilityState==="visible")){let d=t-o;r.timer=setTimeout(()=>{if(r.timer=null,!r.fired&&s.inView&&(typeof document>"u"||document.visibilityState==="visible")){let a=this.getCurrentTimeInView(s);if(a>=t){r.fired=!0;try{i(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),s&&s.thresholdListeners.delete(r);let o=this.pendingThresholdListeners.get(e);o&&o.delete(r)}}getViewabilityState(e){let t=this.slotViewabilityRecords.get(e);if(!t)return;let i=Math.round(this.getCurrentTimeInView(t));return{inView:t.inView,viewable:t.viewableFired,timeInViewMs:i,refreshIndex:t.refreshIndex}}getRefreshIndex(e){return this.slotRefreshIndices.get(e)??0}triggerSlotRefresh(e,t){let i=this.slotViewabilityRecords.get(e);i&&i.element&&this.observeSlot(i.element,e,t)}trackRawEvent(e,t,i){let r=Xe[t]??(e==="ERROR"?f.ERROR:f.TRACE_EVENT_TYPE_UNSPECIFIED);this.enqueue(r,t,i,e)}setUserId(e){this.config.userId=e}setSessionId(e){this.config.sessionId=e}navigate(e,t){if(this.disable(),this.slotRefreshIndices.clear(),this.pendingThresholdListeners.clear(),this.config.pageviewId=e||U(),t)try{let i=new URL(t);this.pageUrl=i.origin+i.pathname}catch{this.pageUrl=t}else this.pageUrl="";De(),this.enable()}handleAuctionInit(e){this.isDuplicate("auctionInit",e)||(this.log("DEBUG","auctionInit",e),this.enqueue(f.AUCTION_START,"auctionStart",{auctionId:e.auctionId||"",transactionId:e.transactionId||""}))}handleAuctionEnd(e){this.isDuplicate("auctionEnd",e)||(this.log("DEBUG","auctionEnd",e),this.enqueue(f.AUCTION_END,"auctionEnd",{auctionId:e.auctionId||"",transactionId:e.transactionId||""}))}handleBidRequested(e){if(this.isDuplicate("bidRequested",e))return;this.log("DEBUG","bidRequested",e);let t=e.auctionId||"",i=e.bidderCode||e.bidder||"";Array.isArray(e.bids)&&e.bids.forEach(r=>{let s=Object.keys(r.mediaTypes||{}),o=r.ortb2Imp?.ext?.gpid||r.gpid||e.gpid||"",d=r.transactionId||r.ortb2Imp?.id||e.transactionId||"";if(s.length===0){let a=r.mediaType||"banner",{width:l,height:I}=Ce(r.sizes||r.playerSize);this.enqueue(f.BID_REQUEST,"bidRequest",{auctionId:t,transactionId:d,adUnitCode:r.adUnitCode||"",gpid:o,bid:{bidder:i,mediaType:a,width:l,height:I}});return}s.forEach(a=>{let l=null;a==="banner"?l=r.mediaTypes?.banner?.sizes||r.sizes:a==="video"?l=r.mediaTypes?.video?.playerSize||r.mediaTypes?.video?.sizes||r.playerSize:l=r.mediaTypes?.[a]?.sizes;let{width:I,height:y}=Ce(l);this.enqueue(f.BID_REQUEST,"bidRequest",{auctionId:t,transactionId:d,adUnitCode:r.adUnitCode||"",gpid:o,bid:{bidder:i,mediaType:a,width:I,height:y}})})})}handleBidResponse(e){this.isDuplicate("bidResponse",e)||(this.log("DEBUG","bidResponse",e),this.enqueue(f.BID_RESPONSE,"bidResponse",{auctionId:e.auctionId||"",transactionId:e.transactionId||"",adUnitCode:e.adUnitCode||"",bid:{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",...C(e),dealId:e.dealId||"",mediaType:e.mediaType||"banner",latencyMs:Number.isFinite(e.timeToRespond)?e.timeToRespond:0,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""}}))}handleBidTimeout(e){if(this.isDuplicate("bidTimeout",e))return;this.log("DEBUG","bidTimeout",e);let t=Array.isArray(e)?e:e?[e]:[];for(let i of t)this.enqueue(f.BID_TIMEOUT,"bidTimeout",{auctionId:i.auctionId||"",transactionId:i.transactionId||"",adUnitCode:i.adUnitCode||"",bid:{bidder:i.bidderCode||i.bidder||"",latencyMs:Number.isFinite(i.timeout)?i.timeout:0}})}handleBidWon(e){if(this.isDuplicate("bidWon",e))return;this.log("DEBUG","bidWon",e);let t=e.auctionId||"",i=e.transactionId||"",r=e.adUnitCode||e.adId||"",s={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",...C(e),dealId:e.dealId||"",mediaType:e.mediaType||"banner",latencyMs:Number.isFinite(e.timeToRespond)?e.timeToRespond:0,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""};if(r){let o={bidTrace:s,auctionId:t,transactionId:i,adUnitCode:r,rawBid:e,timestamp:Date.now()};this.cachedWinningBids.set(r,o),e.adId&&e.adId!==r&&this.cachedWinningBids.set(e.adId,o),t&&(this.cachedWinningBids.set(`${t}:${r}`,o),e.adId&&e.adId!==r&&this.cachedWinningBids.set(`${t}:${e.adId}`,o))}this.enqueue(f.BID_WIN,"bidWon",{auctionId:t,transactionId:i,adUnitCode:r,bid:s})}handleNoBid(e){this.isDuplicate("noBid",e)||(this.log("DEBUG","noBid",e),this.enqueue(f.NO_BID,"noBid",{auctionId:e.auctionId||"",transactionId:e.transactionId||"",adUnitCode:e.adUnitCode||"",bid:{bidder:e.bidderCode||e.bidder||""}}))}handleAdRenderFailed(e){if(this.isDuplicate("adRenderFailed",e))return;this.log("DEBUG","adRenderFailed",e);let t=e.bid||{};this.enqueue(f.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||{},i=e.adUnitCode||t.adUnitCode||e.adId||t.adId||"",r=t.auctionId||e.auctionId||"",s=t.transactionId||e.transactionId||"",o=t.mediaType||"banner",d=e.adUnitCode||t.adUnitCode||"",a=e.adId||t.adId||"",l=(r&&d?this.cachedWinningBids.get(`${r}:${d}`):void 0)||(r&&a?this.cachedWinningBids.get(`${r}:${a}`):void 0)||(d?this.cachedWinningBids.get(d):void 0)||(a?this.cachedWinningBids.get(a):void 0),I={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",...C(t).width?C(t):l?.bidTrace?{width:l.bidTrace.width,height:l.bidTrace.height}:C(t),dealId:t.dealId||l?.bidTrace?.dealId||"",mediaType:o||l?.bidTrace?.mediaType||"banner",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||""},y=r||l?.auctionId||"",h=s||l?.transactionId||"",b=i?this.slotViewabilityRecords.get(i):void 0,x=b&&y&&b.auctionId&&b.auctionId!==y;if(!!(i&&b&&x)){this.flushSlotTimeInView(i);let c=(this.slotRefreshIndices.get(i)??(b?b.refreshIndex:0))+1;this.slotRefreshIndices.set(i,c),this.slotLastAuctionIds.set(i,y),b&&(b.refreshIndex=c,b.auctionId=y,b.transactionId=h,b.bidPayload=I,b.viewableFired=!1,b.accumulatedTimeInViewMs=0),this.enqueue(f.REFRESH,"refresh",{auctionId:y,transactionId:h,adUnitCode:i,bid:I,metadata:{refresh_index:String(c)}})}else i&&(y&&this.slotLastAuctionIds.set(i,y),this.slotRefreshIndices.has(i)||this.slotRefreshIndices.set(i,0));let g=i?this.slotRefreshIndices.get(i)??(b?b.refreshIndex:0):0;if(i&&this.hasImpressionEmitted(i,g,y,I.creativeId)||(i&&this.markImpressionEmitted(i,g,y,I.creativeId),this.enqueue(f.IMPRESSION,"impression",{auctionId:y,transactionId:h,adUnitCode:i,bid:I,metadata:{refresh_index:String(g)}})),this.config.viewabilityEnabled&&typeof document<"u"){let c=null,T=i||e.adId||t.adId;if(T&&(c=document.getElementById(T)),!c&&typeof window<"u"&&window.googletag?.pubads)try{let S=window.googletag.pubads().getSlots();for(let p of S)if((p.getAdUnitPath?.()===i||p.getSlotElementId?.()===i)&&(c=document.getElementById(p.getSlotElementId()),c))break}catch{}if(!c&&T)try{c=document.querySelector(`[data-ad-slot="${T}"]`)||document.querySelector(`#${T}`)}catch{}c&&this.observeSlot(c,i||T,{adUnitCode:i,auctionId:y,transactionId:h,mediaType:o,bid:I,refreshIndex:g,emitRefreshEvent:!1})}}isDuplicate(e,t){return this.deduper.isDuplicate(e,t)}enqueue(e,t,i,r){if(!this.isEnabled||!this.shouldSample(e,r))return;De();let s={eventId:U(),timestampMs:Date.now(),type:e,eventName:t,auctionId:i.auctionId||"",transactionId:i.transactionId||"",adUnitCode:i.adUnitCode||i.elementId||"",namespace:i.ns||i.namespace||""};i.bid&&(s.bid={bidder:i.bid.bidder||"",cpm:Number.isFinite(i.bid.cpm)?i.bid.cpm:0,currency:i.bid.currency||"",width:Number.isFinite(i.bid.width)?i.bid.width:0,height:Number.isFinite(i.bid.height)?i.bid.height:0,dealId:i.bid.dealId||"",mediaType:i.bid.mediaType||"",latencyMs:Number.isFinite(i.bid.latencyMs)?i.bid.latencyMs:0,advertiserDomain:i.bid.advertiserDomain||"",creativeId:i.bid.creativeId||""}),i.viewableDurationMs!==void 0&&(s.viewableDurationMs=Number.isFinite(i.viewableDurationMs)?i.viewableDurationMs:0);let o={...i.metadata};i.error!==void 0&&i.error!==null&&(o.error=typeof i.error=="object"&&i.error.message?String(i.error.message):String(i.error)),i.gpid&&(o.gpid=String(i.gpid)),i.refreshIndex!==void 0&&o.refresh_index===void 0&&(o.refresh_index=String(i.refreshIndex)),Object.keys(o).length>0&&(s.metadata=o),this.queue.push(s),this.queue.length>q&&this.queue.splice(0,this.queue.length-q),this.queue.length>=We?this.flush():Ze.has(e)&&!this.immediateFlushScheduled&&(this.immediateFlushScheduled=!0,setTimeout(()=>{this.immediateFlushScheduled=!1,this.flush()},0))}shouldSample(e,t){return e===f.ERROR?(this.errorCount++,this.errorCount>Ke?!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>q&&this.queue.splice(0,this.queue.length-q))}drainBatch(){if(this.queue.length===0||!this.config.endpoint)return null;let e=this.queue,t=typeof window<"u"?window.location.hostname:"",i=s=>({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:t,events:s}),r=$.encode(i(e)).finish();for(;e.length>1&&r.byteLength>ze;)e=e.slice(0,Math.floor(e.length/2)),r=$.encode(i(e)).finish();return this.queue=this.queue.slice(e.length),{url:`${this.config.endpoint}/${this.config.propertyId}`,encoded:r,events:e}}sendFetch(e,t=!1,i){let r={method:"POST",headers:{"Content-Type":Ae},body:e.encoded};t&&(r.keepalive=!0),fetch(e.url,r).then(o=>{if(o.ok)this.consecutiveSendFailures=0,this.nextSendAllowedAt=0,i&&i();else{if(this.log("WARN",`Failed to send batch: HTTP ${o.status}`),o.status>=400&&o.status<500&&o.status!==429&&o.status!==408){this.log("WARN",`Dropping batch due to non-retryable client error HTTP ${o.status}`);return}this.handleSendFailure(e.events)}}).catch(o=>{this.log("ERROR","Failed to send batch",o),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(Re*2**(this.consecutiveSendFailures-1),He);this.nextSendAllowedAt=Date.now()+t,this.consecutiveSendFailures<=Ge?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 i=new Blob([e.encoded],{type:Ae});t=navigator.sendBeacon(e.url,i)}catch{t=!1}if(!t){let i=this.persistBatch(e.encoded);this.sendFetch(e,!0,()=>this.removePersistedBatch(i))}e=this.drainBatch()}this.schedulePersistedCleanup()}persistBatch(e){try{if(typeof localStorage>"u")return null;let t=0;for(let r=0;r<localStorage.length;r++){let s=localStorage.key(r);s&&s.startsWith(W)&&t++}if(t>=Ye)return null;let i=`${W}${Date.now()}_${Math.floor(Math.random()*1e6)}`;return localStorage.setItem(i,Je(e)),this.persistedBatchKeys.push(i),i}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)},je))}resendPersistedBatches(){try{if(typeof localStorage>"u"||!this.config.endpoint)return;let e=[];for(let t=0;t<localStorage.length;t++){let i=localStorage.key(t);i&&i.startsWith(W)&&e.push(i)}for(let t of e){let i=null;try{i=localStorage.getItem(t),localStorage.removeItem(t)}catch{continue}if(!i)continue;let r=parseInt(t.slice(W.length),10);if(!Number.isFinite(r)||Date.now()-r>Qe)continue;let s;try{s=et(i)}catch{continue}s.byteLength!==0&&(this.log("DEBUG",`Resending persisted exit batch (${s.byteLength} bytes)`),this.sendFetch({url:`${this.config.endpoint}/${this.config.propertyId}`,encoded:s,events:[]}))}}catch{}}log(e,t,...i){let r={DEBUG:10,INFO:20,WARN:30,ERROR:40};if(r[e]<r[this.config.logLevel])return;let s=`[bidkernel][prebid-analytics][${e}]`;switch(e){case"DEBUG":console.debug(s,t,...i);break;case"INFO":console.info(s,t,...i);break;case"WARN":console.warn(s,t,...i);break;case"ERROR":console.error(s,t,...i);break}}}});var st=Ue(()=>{ke();var Me="https://by.bidkernel.io/t",rt=window._bidkernelPbjsGlobal||"pbjs";se(rt,{endpoint:Me});window.bidkernelPrebidAnalytics={...window.bidkernelPrebidAnalytics,register:(n,e)=>se(n,{endpoint:Me,...e}),attachVideoPlayer:(n,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.attachVideoPlayer?t.attachVideoPlayer(n,e):()=>{}},attachImaAdsManager:(n,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.attachImaAdsManager?t.attachImaAdsManager(n,e):()=>{}},recordImpression:(n,e)=>{let t=window._bidkernelPrebidAnalytics;return t?.recordImpression?t.recordImpression(n,e):!1}}});return st();})();
1
+ "use strict";var bidkernelPrebidAnalyticsBundle=(()=>{var S=(i,e)=>()=>(i&&(e=i(i=0)),e);var je=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);function ye(){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 q(i,e,t){for(let s=0;s<28;s=s+7){let o=i>>>s,d=!(!(o>>>7)&&e==0),a=(d?o|128:o)&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 s=3;s<31;s=s+7){let o=e>>>s,d=!!(o>>>7),a=(d?o|128:o)&255;if(t.push(a),!d)return}t.push(e>>>31&1)}}function Z(i){let e=i[0]==="-";e&&(i=i.slice(1));let t=1e6,n=0,r=0;function s(o,d){let a=Number(i.slice(o,d));r*=t,n=n*t+a,n>=W&&(r=r+(n/W|0),n=n%W)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?be(n,r):ee(n,r)}function me(i,e){let t=ee(i,e),n=t.hi&2147483648;n&&(t=be(t.lo,t.hi));let r=J(t.lo,t.hi);return n?"-"+r:r}function J(i,e){if({lo:i,hi:e}=ze(i,e),e<=2097151)return String(W*e+i);let t=i&16777215,n=(i>>>24|e<<8)&16777215,r=e>>16&65535,s=t+n*6777216+r*6710656,o=n+r*8147497,d=r*2,a=1e7;return s>=a&&(o+=Math.floor(s/a),s%=a),o>=a&&(d+=Math.floor(o/a),o%=a),d.toString()+pe(o)+pe(s)}function ze(i,e){return{lo:i>>>0,hi:e>>>0}}function ee(i,e){return{lo:i|0,hi:e|0}}function be(i,e){return e=~e,i?i=~i+1:e+=1,ee(i,e)}function te(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 Ie(){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 W,pe,ie=S(()=>{"use strict";W=4294967296;pe=i=>{let e=String(i);return"0000000".slice(e.length)+e}});function Xe(){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"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(o){let d=typeof o=="bigint"?o:BigInt(o);if(d>n||d<t)throw new Error(`invalid int64: ${o}`);return d},uParse(o){let d=typeof o=="bigint"?o:BigInt(o);if(d>s||d<r)throw new Error(`invalid uint64: ${o}`);return d},enc(o){return i.setBigInt64(0,this.parse(o),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(o){return i.setBigInt64(0,this.uParse(o),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(o,d){return i.setInt32(0,o,!0),i.setInt32(4,d,!0),i.getBigInt64(0,!0)},uDec(o,d){return i.setInt32(0,o,!0),i.setInt32(4,d,!0),i.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(t){return typeof t!="string"&&(t=t.toString()),ge(t),t},uParse(t){return typeof t!="string"&&(t=t.toString()),Te(t),t},enc(t){return typeof t!="string"&&(t=t.toString()),ge(t),Z(t)},uEnc(t){return typeof t!="string"&&(t=t.toString()),Te(t),Z(t)},dec(t,n){return me(t,n)},uDec(t,n){return J(t,n)}}}function ge(i){if(!/^-?[0-9]+$/.test(i))throw new Error("invalid int64: "+i)}function Te(i){if(!/^[0-9]+$/.test(i))throw new Error("invalid uint64: "+i)}var C,Ee=S(()=>{"use strict";ie();C=Xe()});function re(){if(globalThis[ne]==null){let i=new globalThis.TextEncoder,e=new globalThis.TextDecoder;globalThis[ne]={encodeUtf8(t){return i.encode(t)},decodeUtf8(t){return e.decode(t)},checkUtf8(t){try{return encodeURIComponent(t),!0}catch{return!1}}}}return globalThis[ne]}var ne,se=S(()=>{"use strict";ne=Symbol.for("@bufbuild/protobuf/text-encoding")});function oe(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>Je||i<et)throw new Error("invalid int32: "+i)}function ve(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>Ze||i<0)throw new Error("invalid uint32: "+i)}function tt(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>Ye||i<Qe))throw new Error("invalid float32: "+i)}var x,Ye,Qe,Ze,Je,et,M,R,we=S(()=>{"use strict";ie();Ee();se();(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"})(x||(x={}));Ye=34028234663852886e22,Qe=-34028234663852886e22,Ze=4294967295,Je=2147483647,et=-2147483648,M=class{constructor(e=re().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(ve(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return oe(e),te(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){tt(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){ve(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){oe(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return oe(e),e=(e<<1^e>>31)>>>0,te(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=C.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=C.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=C.enc(e);return q(t.lo,t.hi,this.buf),this}sint64(e){let t=C.enc(e),n=t.hi>>31,r=t.lo<<1^n,s=(t.hi<<1|t.lo>>>31)^n;return q(r,s,this.buf),this}uint64(e){let t=C.uEnc(e);return q(t.lo,t.hi,this.buf),this}},R=class{constructor(e,t=re().decodeUtf8){this.decodeUtf8=t,this.varint64=ye,this.uint32=Ie,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 x.Varint:for(;this.buf[this.pos++]&128;);break;case x.Bit64:this.pos+=4;case x.Bit32:this.pos+=4;break;case x.LengthDelimited:let r=this.uint32();this.pos+=r;break;case x.StartGroup:for(;;){let[s,o]=this.tag();if(o===x.EndGroup){if(t!==void 0&&s!==t)throw new Error("invalid end group tag");break}this.skip(o,s)}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 C.dec(...this.varint64())}uint64(){return C.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,C.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 C.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return C.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 Ae=S(()=>{"use strict"});var Be=S(()=>{"use strict"});var Re=S(()=>{"use strict"});var Ce=S(()=>{"use strict";we();Ae();se();Be();Re()});function Se(){return{propertyId:"",pageviewId:"",sessionId:"",pageUrl:"",country:"",region:"",deviceType:"",userId:"",domain:"",events:[],browser:"",deviceManufacturer:"",deviceModel:"",city:"",postalCode:""}}function De(){return{timestampMs:0,type:0,eventName:"",auctionId:"",transactionId:"",adUnitCode:"",bid:void 0,namespace:"",eventId:"",metadata:{},viewableDurationMs:void 0,bidderOutcomes:[]}}function _e(){return{key:"",value:""}}function xe(){return{bidder:"",adUnitCode:"",mediaType:"",outcome:0,latencyMs:0}}function Me(){return{bidder:"",cpm:0,currency:"",width:0,height:0,dealId:"",mediaType:"",latencyMs:0,advertiserDomain:"",creativeId:""}}var m,D,j,K,de,H,G,Oe=S(()=>{"use strict";Ce();m={TRACE_EVENT_TYPE_UNSPECIFIED:0,AUCTION_START:1,AUCTION_END:2,BID_RESPONSE:3,BID_WIN:4,IMPRESSION:5,VIEWABLE:6,TIME_IN_VIEW:7,REFRESH:8,ERROR:9,SLOT_DEFINED:10,SLOT_DESTROYED:11,CLICK:12,AD_RENDER_FAILED:13,UNRECOGNIZED:-1},D={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};j={encode(i,e=new M){if(i.propertyId!==void 0&&i.propertyId!==""&&e.uint32(10).string(i.propertyId),i.pageviewId!==void 0&&i.pageviewId!==""&&e.uint32(18).string(i.pageviewId),i.sessionId!==void 0&&i.sessionId!==""&&e.uint32(26).string(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!==""&&e.uint32(66).string(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)K.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=Se();for(;t.pos<n;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==10)break;r.propertyId=t.string();continue}case 2:{if(s!==18)break;r.pageviewId=t.string();continue}case 3:{if(s!==26)break;r.sessionId=t.string();continue}case 4:{if(s!==34)break;r.pageUrl=t.string();continue}case 5:{if(s!==42)break;r.country=t.string();continue}case 6:{if(s!==50)break;r.region=t.string();continue}case 7:{if(s!==58)break;r.deviceType=t.string();continue}case 8:{if(s!==66)break;r.userId=t.string();continue}case 9:{if(s!==74)break;r.domain=t.string();continue}case 10:{if(s!==82)break;let o=K.decode(t,t.uint32());o!==void 0&&r.events.push(o);continue}case 11:{if(s!==90)break;r.browser=t.string();continue}case 12:{if(s!==98)break;r.deviceManufacturer=t.string();continue}case 13:{if(s!==106)break;r.deviceModel=t.string();continue}case 14:{if(s!==114)break;r.city=t.string();continue}case 15:{if(s!==122)break;r.postalCode=t.string();continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(i){return j.fromPartial(i??{})},fromPartial(i){let e=Se();return e.propertyId=i.propertyId??"",e.pageviewId=i.pageviewId??"",e.sessionId=i.sessionId??"",e.pageUrl=i.pageUrl??"",e.country=i.country??"",e.region=i.region??"",e.deviceType=i.deviceType??"",e.userId=i.userId??"",e.domain=i.domain??"",e.events=i.events?.map(t=>K.fromPartial(t))||[],e.browser=i.browser??"",e.deviceManufacturer=i.deviceManufacturer??"",e.deviceModel=i.deviceModel??"",e.city=i.city??"",e.postalCode=i.postalCode??"",e}};K={encode(i,e=new M){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!==""&&e.uint32(34).string(i.auctionId),i.transactionId!==void 0&&i.transactionId!==""&&e.uint32(42).string(i.transactionId),i.adUnitCode!==void 0&&i.adUnitCode!==""&&e.uint32(50).string(i.adUnitCode),i.bid!==void 0&&G.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!==""&&e.uint32(74).string(i.eventId),globalThis.Object.entries(i.metadata||{}).forEach(([t,n])=>{de.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)H.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=De();for(;t.pos<n;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==9)break;r.timestampMs=t.double();continue}case 2:{if(s!==16)break;r.type=t.int32();continue}case 3:{if(s!==26)break;r.eventName=t.string();continue}case 4:{if(s!==34)break;r.auctionId=t.string();continue}case 5:{if(s!==42)break;r.transactionId=t.string();continue}case 6:{if(s!==50)break;r.adUnitCode=t.string();continue}case 7:{if(s!==58)break;r.bid=G.decode(t,t.uint32());continue}case 8:{if(s!==66)break;r.namespace=t.string();continue}case 9:{if(s!==74)break;r.eventId=t.string();continue}case 10:{if(s!==82)break;let o=de.decode(t,t.uint32());o.value!==void 0&&(r.metadata[o.key]=o.value);continue}case 11:{if(s!==89)break;r.viewableDurationMs=t.double();continue}case 12:{if(s!==98)break;let o=H.decode(t,t.uint32());o!==void 0&&r.bidderOutcomes.push(o);continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(i){return K.fromPartial(i??{})},fromPartial(i){let e=De();return e.timestampMs=i.timestampMs??0,e.type=i.type??0,e.eventName=i.eventName??"",e.auctionId=i.auctionId??"",e.transactionId=i.transactionId??"",e.adUnitCode=i.adUnitCode??"",e.bid=i.bid!==void 0&&i.bid!==null?G.fromPartial(i.bid):void 0,e.namespace=i.namespace??"",e.eventId=i.eventId??"",e.metadata=globalThis.Object.entries(i.metadata??{}).reduce((t,[n,r])=>(r!==void 0&&(t[n]=globalThis.String(r)),t),{}),e.viewableDurationMs=i.viewableDurationMs??void 0,e.bidderOutcomes=i.bidderOutcomes?.map(t=>H.fromPartial(t))||[],e}};de={encode(i,e=new M){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=_e();for(;t.pos<n;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==10)break;r.key=t.string();continue}case 2:{if(s!==18)break;r.value=t.string();continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(i){return de.fromPartial(i??{})},fromPartial(i){let e=_e();return e.key=i.key??"",e.value=i.value??"",e}};H={encode(i,e=new M){return i.bidder!==void 0&&i.bidder!==""&&e.uint32(10).string(i.bidder),i.adUnitCode!==void 0&&i.adUnitCode!==""&&e.uint32(18).string(i.adUnitCode),i.mediaType!==void 0&&i.mediaType!==""&&e.uint32(26).string(i.mediaType),i.outcome!==void 0&&i.outcome!==0&&e.uint32(32).int32(i.outcome),i.latencyMs!==void 0&&i.latencyMs!==0&&e.uint32(41).double(i.latencyMs),e},decode(i,e){let t=i instanceof R?i:new R(i),n=e===void 0?t.len:t.pos+e,r=xe();for(;t.pos<n;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==10)break;r.bidder=t.string();continue}case 2:{if(s!==18)break;r.adUnitCode=t.string();continue}case 3:{if(s!==26)break;r.mediaType=t.string();continue}case 4:{if(s!==32)break;r.outcome=t.int32();continue}case 5:{if(s!==41)break;r.latencyMs=t.double();continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(i){return H.fromPartial(i??{})},fromPartial(i){let e=xe();return e.bidder=i.bidder??"",e.adUnitCode=i.adUnitCode??"",e.mediaType=i.mediaType??"",e.outcome=i.outcome??0,e.latencyMs=i.latencyMs??0,e}};G={encode(i,e=new M){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=Me();for(;t.pos<n;){let s=t.uint32();switch(s>>>3){case 1:{if(s!==10)break;r.bidder=t.string();continue}case 2:{if(s!==17)break;r.cpm=t.double();continue}case 3:{if(s!==26)break;r.currency=t.string();continue}case 4:{if(s!==32)break;r.width=t.int32();continue}case 5:{if(s!==40)break;r.height=t.int32();continue}case 6:{if(s!==50)break;r.dealId=t.string();continue}case 7:{if(s!==58)break;r.mediaType=t.string();continue}case 8:{if(s!==65)break;r.latencyMs=t.double();continue}case 9:{if(s!==74)break;r.advertiserDomain=t.string();continue}case 10:{if(s!==82)break;r.creativeId=t.string();continue}}if((s&7)===4||s===0)break;t.skip(s&7)}return r},create(i){return G.fromPartial(i??{})},fromPartial(i){let e=Me();return e.bidder=i.bidder??"",e.cpm=i.cpm??0,e.currency=i.currency??"",e.width=i.width??0,e.height=i.height??0,e.dealId=i.dealId??"",e.mediaType=i.mediaType??"",e.latencyMs=i.latencyMs??0,e.advertiserDomain=i.advertiserDomain??"",e.creativeId=i.creativeId??"",e}}});function L(){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 mt(i){let e="";for(let n=0;n<i.length;n+=8192)e+=String.fromCharCode(...i.subarray(n,n+8192));return btoa(e)}function bt(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 It(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 gt(i){let e={},t=0;for(let n of Object.keys(i)){if(t>=dt)break;let r=i[n];if(r==null)continue;let s=String(r);e[n]=s.length>Ue?`${s.slice(0,Ue)}...[truncated]`:s,t++}return e}function Tt(i){let e=i.slice(Y.length).split("_");return e.length===2&&/^\d+$/.test(e[0])}function Et(i,e){if(!i||!e)return!1;try{return new URL(i).origin===new URL(e).origin}catch{return!1}}function Ve(){let i=Date.now();F=i;try{typeof localStorage<"u"&&localStorage.setItem(Q,i.toString())}catch{}}function vt(){let i=Date.now();try{if(typeof localStorage<"u"){let e=localStorage.getItem(Ne),t=localStorage.getItem(Q),n=t&&parseInt(t,10)||0;if(e&&n&&i-n<=Le)return localStorage.setItem(Q,i.toString()),e;let r=L();return localStorage.setItem(Ne,r),localStorage.setItem(Q,i.toString()),r}}catch{}return X&&F&&i-F<=Le?(F=i,X):(X=L(),F=i,X)}function l(i){return String(i??"").replace(/%/g,"%25").replace(/:/g,"%3A")}function wt(i,e){switch(i){case"auctionInit":return`auctionInit:${l(e?.auctionId)}`;case"auctionEnd":return`auctionEnd:${l(e?.auctionId)}`;case"bidRequested":{let t=Array.isArray(e?.bids)?e.bids.map(n=>l(n?.bidId||n?.transactionId||n?.adUnitCode)).join(","):"";return`bidRequested:${l(e?.auctionId)}:${l(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:${l(t.auctionId)}:${l(t.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(n)}:${l(r)}`}case"bidTimeout":return"bidTimeout:"+(Array.isArray(e)?e:e?[e]:[]).map(n=>`${l(n?.auctionId)}:${l(n?.bidderCode||n?.bidder)}:${l(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:${l(t.auctionId)}:${l(t.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(n)}:${l(r)}`}case"noBid":return`noBid:${l(e?.auctionId)}:${l(e?.adUnitCode)}:${l(e?.bidderCode||e?.bidder)}:${l(e?.bidId||e?.transactionId)}`;case"adRenderFailed":{let t=e?.bid||{};return`adRenderFailed:${l(t.auctionId||e?.auctionId)}:${l(t.adUnitCode||e?.adUnitCode)}:${l(t.bidderCode||t.bidder||e?.bidderCode||e?.bidder)}:${l(e?.reason)}:${l(e?.message)}`}case"adRenderSucceeded":{let t=e?.bid||e||{},n=t.creativeId||t.adId||e?.adId||"",r=t.originalCpm??t.cpm??"";return`adRenderSucceeded:${l(t.auctionId||e?.auctionId)}:${l(t.adUnitCode||e?.adUnitCode)}:${l(t.bidderCode||t.bidder)}:${l(n)}:${l(r)}`}case"setTargeting":return`setTargeting:${Object.keys(e||{}).sort().map(l).join(",")}`;case"auctionDebug":return`auctionDebug:${l(e?.type)}:${l(String(e?.arguments?.[0]??"").slice(0,50))}`;default:return""}}function O(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 Fe(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 s=t.apply(this,r);if(s)for(let o of N.getActiveInstances())try{o.attachImaAdsManager(s)}catch{}return s};n.__bidkernelHooked=!0,e.getAdsManager=n}}catch{}}function $e(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 s of N.getActiveInstances())try{s.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 s of N.getActiveInstances())try{s.attachImaAdsManager(this)}catch{}return t.apply(this,r)};n.__bidkernelHooked=!0,e.start=n}}catch{}}function We(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,s,...o){if((r==="adsManagerLoaded"||r===(this?.AdsManagerLoadedEvent?.Type?.ADS_MANAGER_LOADED||"adsManagerLoaded"))&&typeof s=="function"){let d=ce.get(s);return d||(d=function(a){if(a&&typeof a.getAdsManager=="function"&&!a.getAdsManager.__bidkernelHooked){let u=a.getAdsManager;a.getAdsManager=function(...h){let b=u.apply(this,h);if(b)for(let f of N.getActiveInstances())try{f.attachImaAdsManager(b)}catch{}return b},a.getAdsManager.__bidkernelHooked=!0}return s.apply(this,arguments)},ce.set(s,d)),t.call(this,r,d,...o)}return t.call(this,r,s,...o)};n.__bidkernelHooked=!0,e.addEventListener=n}if(typeof e.removeEventListener=="function"&&!e.removeEventListener.__bidkernelHooked){let t=e.removeEventListener,n=function(r,s,...o){let d=typeof s=="function"?ce.get(s):void 0;return t.call(this,r,d||s,...o)};n.__bidkernelHooked=!0,e.removeEventListener=n}}catch{}}function $(i){if(!(!i||typeof i!="object"))try{i.AdsManagerLoadedEvent&&Fe(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(s){r=s,Fe(s)}})}catch{}}i.AdsLoader&&We(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(s){r=s,We(s)}})}catch{}}i.AdsManager&&$e(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(s){r=s,$e(s)}})}catch{}}}catch{}}function le(){if(typeof window>"u")return;let i=window;if(i.google?.ima&&$(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,$(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&&$(t.ima);let r=Object.getOwnPropertyDescriptor(t,"ima");if(!r||r.configurable){let s=t.ima;try{Object.defineProperty(t,"ima",{configurable:!0,enumerable:!0,get(){return s},set(o){s=o,$(o)}})}catch{}}}}})}catch{}}}function V(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?V(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 At(i){if(!i)return null;if(i._bidkernelAnalyticsConfig){let e=V(i._bidkernelAnalyticsConfig);if(e)return e}if(i.bidkernelPrebidAnalytics){let e=i.bidkernelPrebidAnalytics;if(e.options){let t=V(e.options);if(t)return t}if(e.config){let t=V(e.config);if(t)return t}if(e.propertyId)return V(e)}return null}function fe(i="pbjs",e){let t=typeof window<"u"?window:{};t[i]=t[i]||{};let n=t[i],r=o=>{let d=t._bidkernelPrebidAnalytics,a=d?.getEndpoint?.()||"",u={pbjsGlobalName:i,...e,...o};if(a&&!Et(u.endpoint||"",a)&&(console.warn(`[bidkernel] Ignoring analytics endpoint change to ${u.endpoint||"(empty)"}: this page is pinned to ${a}. Reload to change the ingest endpoint.`),u.endpoint=a),d)try{d.disable()}catch(b){console.warn("[bidkernel] Failed to disable previous analytics instance:",b)}let h=new N(u);return h.enable(),t._bidkernelPrebidAnalytics=h,h},s=()=>{try{n.adapterManager&&typeof n.adapterManager.registerAnalyticsAdapter=="function"&&n.adapterManager.registerAnalyticsAdapter({adapter:{enableAnalytics:d=>{let a=V(d,!Array.isArray(d));a&&r(a)},disableAnalytics:()=>{t._bidkernelPrebidAnalytics&&t._bidkernelPrebidAnalytics.disable()}},code:"bidkernel"});let o=At(t);o&&(o.propertyId||e?.propertyId)&&r(o)}catch(o){console.warn("[bidkernel] Failed to register standard Prebid analytics adapter:",o)}};n.adapterManager&&typeof n.adapterManager.registerAnalyticsAdapter=="function"?s():(n.que=n.que||[],n.que.push(s))}var nt,ke,rt,z,st,ot,ae,Ue,dt,Pe,Y,at,ct,ut,lt,ft,P,ht,pt,yt,Ne,Q,Le,X,F,ue,ce,N,qe=S(()=>{"use strict";Oe();nt=20,ke=1e4,rt=50,z=200,st=300*1e3,ot=10,ae=32*1024,Ue=1024,dt=16,Pe="text/plain",Y="_bidkernel_pending_",at=20,ct=7200*1e3,ut=1e4,lt={auctionStart:m.AUCTION_START,auctionEnd:m.AUCTION_END,bidResponse:m.BID_RESPONSE,bidWin:m.BID_WIN,adRenderFailed:m.AD_RENDER_FAILED,click:m.CLICK,impression:m.IMPRESSION,refresh:m.REFRESH,timeInView:m.TIME_IN_VIEW,viewable:m.VIEWABLE},ft=new Set([m.IMPRESSION,m.BID_WIN,m.CLICK]),P=1800*1e3,ht=200,pt=1e3,yt=50,Ne="_bidkernel_session",Q="_bidkernel_session_ts",Le=1800*1e3,X=null,F=0;ue=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=wt(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}};ce=new WeakMap;typeof window<"u"&&le();N=class i{static activeInstances=new Set;static getActiveInstances(){return i.activeInstances}static initImaInterception(){le()}config;queue=[];errorCount=0;flushTimer=null;boundFlushBeacon;boundVisibilityChange;isEnabled=!1;boundPbjsHandlers=[];pageUrl="";deduper=new ue;consecutiveSendFailures=0;nextSendAllowedAt=0;replayedEventCount=0;immediateFlushScheduled=!1;persistedBatchKeys=[];persistedCleanupTimer=null;intersectionObserver=null;slotViewabilityRecords=new Map;elementToSlotId=new Map;slotRefreshIndices=new Map;slotLastAuctionIds=new Map;pendingThresholdListeners=new Map;slotEmittedImpressionKeys=new Set;cachedWinningBids=new Map;videoDetachCleanups=new Set;auctionBidderOutcomes=new Map;constructor(e){let t=e.endpoint||"",n=!t||It(t)?t:"";this.config={endpoint:n,propertyId:e.propertyId||"",pageviewId:e.pageviewId||L(),sessionId:e.sessionId||vt(),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,logLevel:e.logLevel||"INFO",pbjsGlobalName:e.pbjsGlobalName||"pbjs",attachPbjsListeners:e.attachPbjsListeners??!0},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.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){let t=(typeof window<"u"?window:{})[this.config.pbjsGlobalName]||{};if(typeof t.onEvent=="function"){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,s]of n)t.onEvent(r,s),this.boundPbjsHandlers.push({event:r,handler:s})}else this.log("WARN","pbjs.onEvent is not defined. Prebid analytics will not function.");if(typeof t.getEvents=="function")try{let n=t.getEvents();if(Array.isArray(n)){let r=n.slice(this.replayedEventCount);if(this.replayedEventCount=n.length,r.length>0){this.log("DEBUG",`Replaying ${r.length} historical events from pbjs.getEvents()`);let s={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 o of r){if(!o)continue;let d=o.eventType||o.event||o.name,a=o.args!==void 0?o.args:o.data!==void 0?o.data:o,u=s[d];u&&u(a)}}}}catch(n){this.log("WARN","Failed to replay historical events from pbjs.getEvents()",n)}}if(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),this.flushTimer=setInterval(()=>this.flush(),ke),this.resendPersistedBatches(),le(),window.google?.ima&&$(window.google.ima)}}}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{}if(this.videoDetachCleanups.clear(),this.cachedWinningBids.clear(),this.slotEmittedImpressionKeys.clear(),this.slotLastAuctionIds.clear(),this.auctionBidderOutcomes.clear(),this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=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 s=t.isIntersecting&&(t.intersectionRatio===void 0||t.intersectionRatio>=.5),o=typeof document>"u"||document.visibilityState==="visible",d=typeof performance<"u"&&performance.now?performance.now():Date.now();if(s){if(!r.inView&&(r.inView=!0,o)){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)}})))}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 s=this.getCurrentTimeInView(e);if(s>=n.thresholdMs){n.fired=!0;try{n.callback(e.slotId,s)}catch(o){this.log("ERROR","Error in threshold listener callback",o)}}}},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 s=t||n?.adUnitCode||(r?r.id:"")||L(),o=this.slotViewabilityRecords.get(s);if(o){if(n?.refreshIndex===void 0||n.refreshIndex>o.refreshIndex){this.flushSlotTimeInView(s);let a=n?.refreshIndex!==void 0?n.refreshIndex:(this.slotRefreshIndices.get(s)??o.refreshIndex)+1;this.slotRefreshIndices.set(s,a),n?.emitRefreshEvent!==!1&&this.enqueue(m.REFRESH,"refresh",{auctionId:n?.auctionId||o.auctionId,transactionId:n?.transactionId||o.transactionId,adUnitCode:s,bid:n?.bid??o.bidPayload,metadata:{...n?.metadata,refresh_index:String(a)}}),o.dwellTimer&&(clearTimeout(o.dwellTimer),o.dwellTimer=null,o.dwellStartedAt=null);for(let h of o.thresholdListeners)h.fired=!1,h.timer&&(clearTimeout(h.timer),h.timer=null);o.viewableFired=!1,o.accumulatedTimeInViewMs=0;let u=typeof performance<"u"&&performance.now?performance.now():Date.now();if(o.lastEnteredViewAt=o.inView?u:null,o.refreshIndex=a,o.auctionId=n?.auctionId||o.auctionId,o.transactionId=n?.transactionId||o.transactionId,o.mediaType=n?.mediaType||o.mediaType||"banner",o.bidPayload=n?.bid!==void 0?n.bid:o.bidPayload,o.metadata=n?.metadata??o.metadata,o.inView&&(typeof document>"u"||document.visibilityState==="visible")){let h=o.mediaType==="video"?2e3:1e3;o.dwellStartedAt=u,o.dwellTimer=setTimeout(()=>{this.handleDwellComplete(o)},h),this.scheduleThresholdTimers(o)}}else o.auctionId=n?.auctionId||o.auctionId,o.transactionId=n?.transactionId||o.transactionId,o.mediaType=n?.mediaType||o.mediaType,n?.bid!==void 0&&(o.bidPayload=n.bid),n?.metadata!==void 0&&(o.metadata=n.metadata);n?.auctionId&&this.slotLastAuctionIds.set(s,n.auctionId),r&&(o.element&&o.element!==r&&this.intersectionObserver&&(this.intersectionObserver.unobserve(o.element),this.elementToSlotId.delete(o.element)),o.element=r,this.elementToSlotId.set(r,s),this.intersectionObserver?.observe(r))}else{let d=n?.refreshIndex??this.slotRefreshIndices.get(s)??0;this.slotRefreshIndices.set(s,d),n?.auctionId&&this.slotLastAuctionIds.set(s,n.auctionId);let a=this.pendingThresholdListeners.get(s)||new Set;this.pendingThresholdListeners.delete(s);let u={slotId:s,element:r,adUnitCode:n?.adUnitCode||s,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};this.slotViewabilityRecords.set(s,u),r&&(this.elementToSlotId.set(r,s),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.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);let t=`${l(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>P){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>P&&this.cachedWinningBids.delete(t);for(;this.cachedWinningBids.size>ht;){let t=this.cachedWinningBids.keys().next();if(t.done)break;this.cachedWinningBids.delete(t.value)}}findCachedWinningBid(e){let t=Date.now(),n=o=>this.hasImpressionEmitted(o.adUnitCode,void 0,o.auctionId,o.bidTrace.creativeId);if(e?.creativeId||e?.adId){for(let o of Array.from(this.cachedWinningBids.values()))if(!(t-o.timestamp>P)&&(e.creativeId&&(o.bidTrace.creativeId===e.creativeId||o.rawBid?.creativeId===e.creativeId)||e.adId&&(o.rawBid?.adId===e.adId||o.adUnitCode===e.adId)))return o}let r;if(e?.mediaType){for(let d of Array.from(this.cachedWinningBids.values())){if(t-d.timestamp>P)continue;(d.bidTrace.mediaType===e.mediaType||d.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&d.rawBid?.mediaTypes?.video!==void 0)&&(n(d)||(!r||d.timestamp<r.timestamp)&&(r=d))}if(r)return r;let o;for(let d of Array.from(this.cachedWinningBids.values())){if(t-d.timestamp>P)continue;(d.bidTrace.mediaType===e.mediaType||d.rawBid?.mediaType===e.mediaType||e.mediaType==="video"&&d.rawBid?.mediaTypes?.video!==void 0)&&(!o||d.timestamp>o.timestamp)&&(o=d)}if(o)return o}for(let o of Array.from(this.cachedWinningBids.values()))t-o.timestamp>P||n(o)||(!r||o.timestamp>r.timestamp)&&(r=o);if(r)return r;let s;for(let o of Array.from(this.cachedWinningBids.values()))t-o.timestamp>P||(!s||o.timestamp>s.timestamp)&&(s=o);return s}addImpressionKey(e){if(!this.slotEmittedImpressionKeys.has(e)){for(;this.slotEmittedImpressionKeys.size>=pt;){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>yt;){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 s=t??this.slotRefreshIndices.get(e)??0,o=`${l(e)}:${s}`;return r?n?this.slotEmittedImpressionKeys.has(`${o}:auc:${l(n)}:${l(r)}`)||this.slotEmittedImpressionKeys.has(`${o}:${l(r)}`):this.slotEmittedImpressionKeys.has(`${o}:${l(r)}`):n?this.slotEmittedImpressionKeys.has(`${o}:auc:${l(n)}`):this.slotEmittedImpressionKeys.has(o)}markImpressionEmitted(e,t,n,r){let s=`${l(e)}:${t}`;this.addImpressionKey(s),r&&this.addImpressionKey(`${s}:${l(r)}`),n&&(this.addImpressionKey(`${s}:auc:${l(n)}`),r&&this.addImpressionKey(`${s}:auc:${l(n)}:${l(r)}`))}recordImpression(e,t){if(!this.isEnabled)return!1;let n=e||t?.adUnitCode||"",r=t?.adUnitCode||n,s=(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),o=t?.bid||s?.rawBid||{},d=t?.auctionId||o.auctionId||s?.auctionId||"",a=t?.transactionId||o.transactionId||s?.transactionId||"",u=o.creativeId||s?.bidTrace?.creativeId||t?.bid?.creativeId||"",h=t?.mediaType||o.mediaType||s?.bidTrace?.mediaType||"banner",b=n||r,f=(n?this.slotViewabilityRecords.get(n):void 0)||(r?this.slotViewabilityRecords.get(r):void 0),T=b?this.slotLastAuctionIds.get(b)||(f?f.auctionId:void 0):void 0,v=!!(b&&d&&T&&T!==d&&t?.refreshIndex===void 0),I={bidder:o.bidderCode||o.bidder||s?.bidTrace?.bidder||"",cpm:Number.isFinite(o.originalCpm)?o.originalCpm:Number.isFinite(o.cpm)?o.cpm:s?.bidTrace?.cpm??0,currency:o.originalCurrency??o.currency??s?.bidTrace?.currency??"USD",...O(o).width?O(o):s?.bidTrace?{width:s.bidTrace.width,height:s.bidTrace.height}:O(o),dealId:o.dealId||s?.bidTrace?.dealId||"",mediaType:h,latencyMs:Number.isFinite(o.timeToRespond)?o.timeToRespond:s?.bidTrace?.latencyMs??0,advertiserDomain:o.meta?.advertiserDomains?.[0]||s?.bidTrace?.advertiserDomain||"",creativeId:o.creativeId||s?.bidTrace?.creativeId||""};if(v&&b){this.flushSlotTimeInView(b);let w=(this.slotRefreshIndices.get(b)??(f?f.refreshIndex:0))+1;this.slotRefreshIndices.set(b,w),this.slotLastAuctionIds.set(b,d),f&&(f.refreshIndex=w,f.auctionId=d,f.transactionId=a,f.bidPayload=I,f.viewableFired=!1,f.accumulatedTimeInViewMs=0),this.enqueue(m.REFRESH,"refresh",{auctionId:d,transactionId:a,adUnitCode:b,bid:I,metadata:{...t?.metadata,refresh_index:String(w)}})}else b&&(d&&this.slotLastAuctionIds.set(b,d),this.slotRefreshIndices.has(b)||this.slotRefreshIndices.set(b,0));let B=t?.refreshIndex??(n?this.slotRefreshIndices.get(n)??(r?this.slotRefreshIndices.get(r):void 0)??(f?f.refreshIndex:0):0);return n&&this.hasImpressionEmitted(n,B,d,u)||r&&r!==n&&this.hasImpressionEmitted(r,B,d,u)?(this.log("DEBUG",`Impression already emitted for slot ${n||r} in cycle ${B}`),!1):(n&&this.markImpressionEmitted(n,B,d,u),r&&r!==n&&this.markImpressionEmitted(r,B,d,u),this.enqueue(m.IMPRESSION,"impression",{auctionId:d,transactionId:a,adUnitCode:r,bid:I,metadata:{...t?.metadata,refresh_index:String(B)}}),f&&(!f.bidPayload&&I&&(f.bidPayload=I),!f.auctionId&&d&&(f.auctionId=d),!f.transactionId&&a&&(f.transactionId=a)),!0)}attachImaAdsManager(e,t){if(!e||typeof e.addEventListener!="function")return this.log("WARN","Invalid AdsManager passed to attachImaAdsManager"),()=>{};if(!e.__bidkernelAttachedInstances)try{Object.defineProperty(e,"__bidkernelAttachedInstances",{value:new Set,configurable:!0,writable:!0})}catch{e.__bidkernelAttachedInstances=new Set}if(e.__bidkernelAttachedInstances.has(this))return()=>{};e.__bidkernelAttachedInstances.add(this);let n=t?.slotId||t?.adUnitCode||"video",r=t?.adUnitCode||n,s=t?.auctionId||"",o=t?.transactionId||"",d=p=>{let c=(s?this.getCachedBid(`${s}:${r}`):void 0)||(s&&n!==r?this.getCachedBid(`${s}:${n}`):void 0)||(r!=="video"?this.getCachedBid(r):void 0)||(n!==r&&n!=="video"?this.getCachedBid(n):void 0);return c||(c=this.findCachedWinningBid({creativeId:p?.creativeId,adId:p?.adId,mediaType:"video"})),c},a=!1,u=p=>{a=!0,this.log("DEBUG","IMA AdEvent.STARTED / IMPRESSION received",p);let c=typeof p?.getAd=="function"?p.getAd():p?.ad,y={};c&&(y.creativeId=(typeof c.getCreativeId=="function"?c.getCreativeId():c.creativeId)||"",y.adId=(typeof c.getAdId=="function"?c.getAdId():c.id)||"",y.title=(typeof c.getTitle=="function"?c.getTitle():c.title)||"",y.duration=typeof c.getDuration=="function"?c.getDuration():c.duration,y.advertiserName=typeof c.getAdvertiserName=="function"?c.getAdvertiserName():"");let g=d(y),A=t?.slotId&&t.slotId!=="video"?t.slotId:t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:g?.adUnitCode||t?.slotId||t?.adUnitCode||"video",_=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:g?.adUnitCode||A,U=s||g?.auctionId||"",He=o||g?.transactionId||"",he={...g?.rawBid||t?.bid,mediaType:"video",creativeId:y.creativeId||g?.bidTrace?.creativeId||t?.bid?.creativeId||""};if(this.recordImpression(A,{adUnitCode:_,auctionId:U,transactionId:He,mediaType:"video",bid:he,metadata:{...t?.metadata,media_type:"video",...y.title?{ad_title:y.title}:{},...Number.isFinite(y.duration)?{ad_duration_s:String(y.duration)}:{}}})&&t?.onImpression)try{t.onImpression(A,{ad:c,bid:he})}catch(Ge){this.log("ERROR","Error in onImpression callback",Ge)}},h=p=>{if(this.log("DEBUG",`IMA AdEvent milestone: ${p}`),t?.onMilestone)try{t.onMilestone(p,n)}catch(c){this.log("ERROR","Error in onMilestone callback",c)}},b=p=>{this.log("DEBUG","IMA AdEvent.CLICK received",p);let c=d(),y=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:c?.adUnitCode||n;this.enqueue(m.CLICK,"click",{auctionId:s||c?.auctionId,transactionId:o||c?.transactionId,adUnitCode:y,bid:c?.bidTrace||t?.bid,metadata:{...t?.metadata,media_type:"video"}})},f=p=>{this.log("WARN","IMA AdErrorEvent received",p);let c=typeof p?.getError=="function"?p.getError():p?.error||p,y=(c&&typeof c.getMessage=="function"?c.getMessage():c?.message)||String(c||"IMA ad error"),g=(c&&typeof c.getErrorCode=="function"?c.getErrorCode():c?.code)||"",A=d(),_=t?.adUnitCode&&t.adUnitCode!=="video"?t.adUnitCode:A?.adUnitCode||n;if(this.enqueue(m.AD_RENDER_FAILED,"adRenderFailed",{auctionId:s||A?.auctionId,transactionId:o||A?.transactionId,adUnitCode:_,bid:A?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:a?"ima_playback_error":"ima_ad_error",playback_phase:a?"post_start":"pre_start",message:y,...g?{ima_error_code:String(g)}:{}},error:typeof c=="object"?c:new Error(y)}),t?.onError)try{t.onError(c)}catch(U){this.log("ERROR","Error in onError callback",U)}},T=typeof window<"u"?window.google?.ima:void 0,v=T?.AdEvent?.Type||{},I=T?.AdErrorEvent?.Type||{},B=[{type:v.STARTED||"started",handler:u},{type:v.IMPRESSION||"impression",handler:u},{type:v.FIRST_QUARTILE||"firstQuartile",handler:()=>h("firstQuartile")},{type:v.MIDPOINT||"midpoint",handler:()=>h("midpoint")},{type:v.THIRD_QUARTILE||"thirdQuartile",handler:()=>h("thirdQuartile")},{type:v.COMPLETE||"complete",handler:()=>h("complete")},{type:v.CLICK||"click",handler:b},{type:I.AD_ERROR||"adError",handler:f}],k=new Set,w=[];for(let p of B)k.has(p.type)||(k.add(p.type),w.push(p));for(let{type:p,handler:c}of w)try{e.addEventListener(p,c)}catch{}let E=()=>{e.__bidkernelAttachedInstances?.delete(this);for(let{type:p,handler:c}of w)try{e.removeEventListener(p,c)}catch{}this.videoDetachCleanups.delete(E)};return this.videoDetachCleanups.add(E),E}attachVideoPlayer(e,t){if(!e)return this.log("WARN","attachVideoPlayer called with null/undefined target"),()=>{};let n=null;if(typeof e=="string"){if(typeof document<"u")try{n=document.querySelector(e)||document.getElementById(e)}catch{n=document.getElementById(e)}}else if(typeof HTMLElement<"u"&&e instanceof HTMLElement)n=e;else if(e&&typeof e=="object"&&e.nodeType===1)n=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 this.attachImaAdsManager(e,t);e&&typeof e.addEventListener=="function"&&(n=e)}let r=t?.slotId||t?.adUnitCode||(n?n.id:"")||"video",s=t?.adUnitCode||r,o=t?.auctionId||"",d=t?.transactionId||"",a=()=>(o?this.getCachedBid(`${o}:${s}`):void 0)||(o&&r!==s?this.getCachedBid(`${o}:${r}`):void 0)||this.getCachedBid(s)||(r!==s?this.getCachedBid(r):void 0),u=null;n&&(n.tagName&&n.tagName.toLowerCase()==="video"?u=n:u=n.querySelector("video"));let h={q1:!1,q2:!1,q3:!1,q4:!1},b=c=>{let y=c||u||(n?.querySelector?n.querySelector("video"):null),g=a(),A={...g?.rawBid||t?.bid,mediaType:"video"};if(this.recordImpression(r,{adUnitCode:s,auctionId:o||g?.auctionId,transactionId:d||g?.transactionId,mediaType:"video",bid:A,metadata:{...t?.metadata,media_type:"video",...y&&Number.isFinite(y.duration)?{video_duration_s:String(Math.round(y.duration))}:{}}})&&t?.onImpression)try{t.onImpression(r,{element:y||n,bid:A})}catch(U){this.log("ERROR","Error in onImpression callback",U)}},f=c=>{this.log("DEBUG","HTML5 video playing event received");let y=c?.target instanceof HTMLVideoElement?c.target:u;b(y)},T=c=>{let y=c?.target instanceof HTMLVideoElement?c.target:u;if(y&&y.currentTime>0&&(b(y),Number.isFinite(y.duration)&&y.duration>0)){let g=y.currentTime/y.duration;g>=.25&&!h.q1&&(h.q1=!0,t?.onMilestone?.("firstQuartile",r)),g>=.5&&!h.q2&&(h.q2=!0,t?.onMilestone?.("midpoint",r)),g>=.75&&!h.q3&&(h.q3=!0,t?.onMilestone?.("thirdQuartile",r))}},v=()=>{h.q4||(h.q4=!0,t?.onMilestone?.("complete",r))},I=c=>{let g=(c?.target instanceof HTMLVideoElement?c.target:u)?.error||u?.error,A=a(),_=g?`HTML5 video error code ${g.code}: ${g.message}`:"Video playback error";if(this.log("WARN",_),this.enqueue(m.AD_RENDER_FAILED,"adRenderFailed",{auctionId:o||A?.auctionId,transactionId:d||A?.transactionId,adUnitCode:s,bid:A?.bidTrace||t?.bid,metadata:{...t?.metadata,reason:"html5_video_error",message:_,...g?.code?{video_error_code:String(g.code)}:{}},error:g?new Error(_):void 0}),t?.onError)try{t.onError(g)}catch(U){this.log("ERROR","Error in onError callback",U)}},B=c=>{c.addEventListener("playing",f),c.addEventListener("play",f),c.addEventListener("timeupdate",T),c.addEventListener("ended",v),c.addEventListener("error",I)},k=c=>{c.removeEventListener("playing",f),c.removeEventListener("play",f),c.removeEventListener("timeupdate",T),c.removeEventListener("ended",v),c.removeEventListener("error",I)},w=null;n&&n!==u&&(n.addEventListener("playing",f,!0),n.addEventListener("play",f,!0),n.addEventListener("timeupdate",T,!0),n.addEventListener("ended",v,!0),n.addEventListener("error",I,!0)),u&&B(u),n&&n.tagName?.toLowerCase()!=="video"&&typeof MutationObserver<"u"&&(w=new MutationObserver(()=>{let c=n.querySelector("video");c&&c!==u&&(u&&k(u),u=c,u&&B(u))}),w.observe(n,{childList:!0,subtree:!0}));let E=a();t?.trackViewability!==!1&&n&&this.observeSlot(n,r,{adUnitCode:s,auctionId:o||E?.auctionId,transactionId:d||E?.transactionId,mediaType:"video",bid:E?.bidTrace||t?.bid,metadata:t?.metadata,emitRefreshEvent:!1});let p=()=>{w&&(w.disconnect(),w=null),n&&n!==u&&(n.removeEventListener("playing",f,!0),n.removeEventListener("play",f,!0),n.removeEventListener("timeupdate",T,!0),n.removeEventListener("ended",v,!0),n.removeEventListener("error",I,!0)),u&&k(u),this.videoDetachCleanups.delete(p)};return this.videoDetachCleanups.add(p),p}onTimeInViewThreshold(e,t,n){let r={thresholdMs:t,callback:n,timer:null,fired:!1},s=this.slotViewabilityRecords.get(e);if(s){s.thresholdListeners.add(r);let o=this.getCurrentTimeInView(s);if(o>=t){r.fired=!0;try{n(e,o)}catch(d){this.log("ERROR","Error in threshold callback",d)}}else if(s.inView&&(typeof document>"u"||document.visibilityState==="visible")){let d=t-o;r.timer=setTimeout(()=>{if(r.timer=null,!r.fired&&s.inView&&(typeof document>"u"||document.visibilityState==="visible")){let a=this.getCurrentTimeInView(s);if(a>=t){r.fired=!0;try{n(e,a)}catch(u){this.log("ERROR","Error in threshold callback",u)}}}},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),s&&s.thresholdListeners.delete(r);let o=this.pendingThresholdListeners.get(e);o&&o.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=lt[t]??(e==="ERROR"?m.ERROR:m.TRACE_EVENT_TYPE_UNSPECIFIED);this.enqueue(r,t,n,e)}setUserId(e){this.config.userId=e}setSessionId(e){this.config.sessionId=e}navigate(e,t){if(this.disable(),this.slotRefreshIndices.clear(),this.pendingThresholdListeners.clear(),this.config.pageviewId=e||L(),t)try{let n=new URL(t);this.pageUrl=n.origin+n.pathname}catch{this.pageUrl=t}else this.pageUrl="";Ve(),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})}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(s=>{let o=s.adUnitCode||"",d=Object.keys(s.mediaTypes||{}),a=d.length>0?d[0]:s.mediaType||"banner",u=`${n}:${o}`;r.has(u)||r.set(u,{bidder:n,adUnitCode:o,mediaType:a,outcome:D.BIDDER_OUTCOME_NO_RESPONSE,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||"",s=Number.isFinite(e.originalCpm)?e.originalCpm:Number.isFinite(e.cpm)?e.cpm:0,o=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){let u=this.getOrCreateAuctionOutcomes(t),h=`${n}:${r}`,b=u.get(h),f=s>0?D.BIDDER_OUTCOME_BID:D.BIDDER_OUTCOME_NO_BID;b?(b.outcome=f,b.latencyMs=o,a&&(b.mediaType=a)):u.set(h,{bidder:n,adUnitCode:r,mediaType:a,outcome:f,latencyMs:o})}s>0&&this.enqueue(m.BID_RESPONSE,"bidResponse",{auctionId:t,transactionId:e.transactionId||"",adUnitCode:r,bid:{bidder:n,cpm:s,currency:e.originalCurrency??e.currency??"USD",...O(e),dealId:e.dealId||"",mediaType:a,latencyMs:o,advertiserDomain:e.meta?.advertiserDomains?.[0]||"",creativeId:e.creativeId||""}})}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||"",s=n.bidderCode||n.bidder||"",o=n.adUnitCode||"",d=Number.isFinite(n.timeout)?n.timeout:0;if(r&&s){let a=this.getOrCreateAuctionOutcomes(r),u=`${s}:${o}`,h=a.get(u);h?(h.outcome=D.BIDDER_OUTCOME_TIMEOUT,d>0&&(h.latencyMs=d)):a.set(u,{bidder:s,adUnitCode:o,mediaType:"banner",outcome:D.BIDDER_OUTCOME_TIMEOUT,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||"",s=Object.keys(e.mediaTypes||{}),o=e.mediaType||(e.mediaTypes?.video?"video":s.length>0?s[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",...O(e),dealId:e.dealId||"",mediaType:o,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 s=this.getOrCreateAuctionOutcomes(t),o=`${n}:${r}`,d=s.get(o);d?d.outcome===D.BIDDER_OUTCOME_NO_RESPONSE&&(d.outcome=D.BIDDER_OUTCOME_NO_BID):s.set(o,{bidder:n,adUnitCode:r,mediaType:"banner",outcome:D.BIDDER_OUTCOME_NO_BID,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||"",s=t.transactionId||e.transactionId||"",o=t.mediaType||"banner",d=e.adUnitCode||t.adUnitCode||"",a=e.adId||t.adId||"",u=(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),h=o==="video"||t.mediaType==="video"||t.mediaTypes?.video!==void 0||u?.bidTrace?.mediaType==="video"||u?.rawBid?.mediaType==="video"||n&&this.slotViewabilityRecords.get(n)?.mediaType==="video",b=h?"video":o||u?.bidTrace?.mediaType||"banner",f={bidder:t.bidderCode||t.bidder||u?.bidTrace?.bidder||"",cpm:Number.isFinite(t.originalCpm)?t.originalCpm:Number.isFinite(t.cpm)?t.cpm:u?.bidTrace?.cpm??0,currency:t.originalCurrency??t.currency??u?.bidTrace?.currency??"USD",...O(t).width?O(t):u?.bidTrace?{width:u.bidTrace.width,height:u.bidTrace.height}:O(t),dealId:t.dealId||u?.bidTrace?.dealId||"",mediaType:b,latencyMs:Number.isFinite(t.timeToRespond)?t.timeToRespond:u?.bidTrace?.latencyMs??0,advertiserDomain:t.meta?.advertiserDomains?.[0]||u?.bidTrace?.advertiserDomain||"",creativeId:t.creativeId||u?.bidTrace?.creativeId||""},T=r||u?.auctionId||"",v=s||u?.transactionId||"",I=n?this.slotViewabilityRecords.get(n):void 0,B=I&&T&&I.auctionId&&I.auctionId!==T;if(!!(n&&I&&B)){this.flushSlotTimeInView(n);let E=(this.slotRefreshIndices.get(n)??(I?I.refreshIndex:0))+1;this.slotRefreshIndices.set(n,E),this.slotLastAuctionIds.set(n,T),I&&(I.refreshIndex=E,I.auctionId=T,I.transactionId=v,I.bidPayload=f,I.viewableFired=!1,I.accumulatedTimeInViewMs=0),this.enqueue(m.REFRESH,"refresh",{auctionId:T,transactionId:v,adUnitCode:n,bid:f,metadata:{refresh_index:String(E)}})}else n&&(T&&this.slotLastAuctionIds.set(n,T),this.slotRefreshIndices.has(n)||this.slotRefreshIndices.set(n,0));let w=n?this.slotRefreshIndices.get(n)??(I?I.refreshIndex:0):0;if(h?this.log("DEBUG",`adRenderSucceeded received for video ad unit ${n||"unknown"}: suppressing IMPRESSION until verified video lifecycle event`):n&&this.hasImpressionEmitted(n,w,T,f.creativeId)||(n&&this.markImpressionEmitted(n,w,T,f.creativeId),this.enqueue(m.IMPRESSION,"impression",{auctionId:T,transactionId:v,adUnitCode:n,bid:f,metadata:{refresh_index:String(w)}})),this.config.viewabilityEnabled&&typeof document<"u"){let E=null,p=n||e.adId||t.adId;if(p&&(E=document.getElementById(p)),!E&&typeof window<"u"&&window.googletag?.pubads)try{let c=window.googletag.pubads().getSlots();for(let y of c)if((y.getAdUnitPath?.()===n||y.getSlotElementId?.()===n)&&(E=document.getElementById(y.getSlotElementId()),E))break}catch{}if(!E&&p)try{for(let c of Array.from(document.querySelectorAll("[data-ad-slot]")))if(c.getAttribute("data-ad-slot")===p){E=c;break}}catch{}E&&this.observeSlot(E,n||p,{adUnitCode:n,auctionId:T,transactionId:v,mediaType:b,bid:f,refreshIndex:w,emitRefreshEvent:!1})}}isDuplicate(e,t){return this.deduper.isDuplicate(e,t)}enqueue(e,t,n,r){if(!this.isEnabled||!this.shouldSample(e,r))return;Ve();let s={eventId:L(),timestampMs:Date.now(),type:e,eventName:t,auctionId:n.auctionId||"",transactionId:n.transactionId||"",adUnitCode:n.adUnitCode||n.elementId||"",namespace:n.ns||n.namespace||""};n.bid&&(s.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&&(s.viewableDurationMs=Number.isFinite(n.viewableDurationMs)?n.viewableDurationMs:0),n.bidderOutcomes&&Array.isArray(n.bidderOutcomes)&&(s.bidderOutcomes=n.bidderOutcomes);let o={...n.metadata};n.error!==void 0&&n.error!==null&&(o.error=typeof n.error=="object"&&n.error.message?String(n.error.message):String(n.error)),n.gpid&&(o.gpid=String(n.gpid)),n.refreshIndex!==void 0&&o.refresh_index===void 0&&(o.refresh_index=String(n.refreshIndex));let d=gt(o);Object.keys(d).length>0&&(s.metadata=d),this.queue.push(s),this.queue.length>z&&this.queue.splice(0,this.queue.length-z),this.queue.length>=nt?this.flush():ft.has(e)&&!this.immediateFlushScheduled&&(this.immediateFlushScheduled=!0,setTimeout(()=>{this.immediateFlushScheduled=!1,this.flush()},0))}shouldSample(e,t){return e===m.ERROR?(this.errorCount++,this.errorCount>rt?!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=j.encode(t(n)).finish();for(;n.length>1&&r.byteLength>ae;)n=n.slice(0,Math.floor(n.length/2)),r=j.encode(t(n)).finish();if(r.byteLength>ae){let[s]=this.queue.splice(0,1);this.log("WARN",`Dropping oversized event ${s?.eventName||s?.eventId} (${r.byteLength} bytes exceeds the ${ae}-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 s={method:"POST",headers:{"Content-Type":Pe},body:e.encoded};t&&(s.keepalive=!0),fetch(e.url,s).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 o=typeof globalThis<"u"?globalThis.process:void 0;if(o&&typeof o._tickCallback=="function")try{o._tickCallback()}catch{}}handleSendFailure(e){this.consecutiveSendFailures++;let t=Math.min(ke*2**(this.consecutiveSendFailures-1),st);this.nextSendAllowedAt=Date.now()+t,this.consecutiveSendFailures<=ot?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:Pe});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`${Y}${encodeURIComponent(this.config.propertyId)}_`}persistBatch(e){try{if(typeof localStorage>"u"||!this.config.propertyId)return null;let t=0;for(let r=0;r<localStorage.length;r++){let s=localStorage.key(r);s&&s.startsWith(Y)&&t++}if(t>=at)return null;let n=`${this.pendingKeyPrefix()}${Date.now()}_${Math.floor(Math.random()*1e6)}`;return localStorage.setItem(n,mt(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)},ut))}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 s=localStorage.key(r);!s||!s.startsWith(Y)||(s.startsWith(e)?t.push(s):Tt(s)&&n.push(s))}for(let r of n)try{localStorage.removeItem(r)}catch{}for(let r of t){let s=null;try{s=localStorage.getItem(r),localStorage.removeItem(r)}catch{continue}if(!s)continue;let o=parseInt(r.slice(e.length),10);if(!Number.isFinite(o)||Date.now()-o>ct)continue;let d;try{d=bt(s)}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){let r={DEBUG:10,INFO:20,WARN:30,ERROR:40};if(r[e]<r[this.config.logLevel])return;let s=`[bidkernel][prebid-analytics][${e}]`;switch(e){case"DEBUG":console.debug(s,t,...n);break;case"INFO":console.info(s,t,...n);break;case"WARN":console.warn(s,t,...n);break;case"ERROR":console.error(s,t,...n);break}}}});var Rt=je(()=>{qe();var Ke="https://by.bidkernel.io/t",Bt=window._bidkernelPbjsGlobal||"pbjs";fe(Bt,{endpoint:Ke});window.bidkernelPrebidAnalytics={...window.bidkernelPrebidAnalytics,register:(i,e)=>fe(i,{endpoint:Ke,...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 Rt();})();
package/dist/index.d.mts CHANGED
@@ -102,6 +102,21 @@ interface SlotViewabilityState {
102
102
  timeInViewMs: number;
103
103
  refreshIndex: number;
104
104
  }
105
+ /**
106
+ * The ingest endpoint decides where auction telemetry -- CPMs, deal IDs,
107
+ * advertiser domains, user and session IDs -- is shipped, and it arrives from
108
+ * page context (enableAnalytics options, or the _bidkernelAnalyticsConfig
109
+ * global). Anything running in the page can reach that, including a banner
110
+ * creative rendered into a same-origin Prebid friendly iframe, so the value is
111
+ * validated rather than trusted: HTTPS only, absolute, no credentials in the
112
+ * URL. Plain HTTP is allowed only for loopback so local development works.
113
+ *
114
+ * This deliberately does not allowlist hosts: properties on branded ingest
115
+ * domains legitimately point at their own. Hijacking a live instance to a
116
+ * different origin is prevented separately, by pinning in
117
+ * registerPrebidAnalytics.
118
+ */
119
+ declare function isTrustedEndpoint(raw: string): boolean;
105
120
  /**
106
121
  * Canonical duplicate-detection key for a Prebid event. Shared by the adapter
107
122
  * and the diagnostic extension so the two can never drift apart. Covers the
@@ -117,8 +132,17 @@ declare class PrebidEventDeduper {
117
132
  private seenKeys;
118
133
  isDuplicate(eventName: string, data: any): boolean;
119
134
  }
135
+ /**
136
+ * Hooks Google IMA SDK methods to automatically intercept AdsManager creation
137
+ * across active BidkernelPrebidAnalytics instances without requiring manual
138
+ * publisher calls to attachImaAdsManager.
139
+ */
140
+ declare function hookImaPrototype(ima: any): void;
141
+ declare function initImaInterception(): void;
120
142
  declare class BidkernelPrebidAnalytics {
121
143
  private static activeInstances;
144
+ static getActiveInstances(): Set<BidkernelPrebidAnalytics>;
145
+ static initImaInterception(): void;
122
146
  private config;
123
147
  private queue;
124
148
  private errorCount;
@@ -144,6 +168,7 @@ declare class BidkernelPrebidAnalytics {
144
168
  private slotEmittedImpressionKeys;
145
169
  private cachedWinningBids;
146
170
  private videoDetachCleanups;
171
+ private auctionBidderOutcomes;
147
172
  constructor(config: AnalyticsConfig);
148
173
  enable(): void;
149
174
  disable(): void;
@@ -158,6 +183,33 @@ declare class BidkernelPrebidAnalytics {
158
183
  observeSlot(element: HTMLElement | string, slotId?: string, options?: SlotObserveOptions): void;
159
184
  unobserveSlot(slotId: string): void;
160
185
  destroySlot(slotId: string): void;
186
+ /**
187
+ * Reads a cached winning bid, treating an entry past CACHED_BID_TTL_MS as
188
+ * absent and dropping it. Every read goes through here so a stale bid can
189
+ * never be married to a much later render.
190
+ */
191
+ private getCachedBid;
192
+ /** Removes every alias pointing at one entry. Aliases are stored by identity. */
193
+ private deleteCachedBidEntry;
194
+ /**
195
+ * Drops expired entries, then evicts oldest-first until the key cap holds.
196
+ * Map iterates in insertion order and one win's aliases are written
197
+ * consecutively, so eviction takes a whole bid's aliases together.
198
+ */
199
+ private pruneCachedWinningBids;
200
+ /**
201
+ * Searches cached winning bids for an entry matching the given filters (creativeId,
202
+ * adId, or mediaType), falling back to the most recent winning video bid.
203
+ */
204
+ private findCachedWinningBid;
205
+ /** Records a dedup key, evicting oldest-first at the cap. */
206
+ private addImpressionKey;
207
+ /**
208
+ * The bidder-outcome map for an auction, creating it if absent. Evicts the
209
+ * oldest auction at the cap: without this, any auction whose auctionEnd never
210
+ * fires (abandoned, navigated away from mid-flight) leaks its map forever.
211
+ */
212
+ private getOrCreateAuctionOutcomes;
161
213
  hasImpressionEmitted(slotId: string, refreshIndex?: number, auctionId?: string, creativeId?: string): boolean;
162
214
  private markImpressionEmitted;
163
215
  recordImpression(slotId: string, options?: SlotObserveOptions & {
@@ -177,6 +229,8 @@ declare class BidkernelPrebidAnalytics {
177
229
  attachVideoPlayer(target: any, options?: VideoPlayerOptions): () => void;
178
230
  onTimeInViewThreshold(slotId: string, thresholdMs: number, callback: (slotId: string, durationMs: number) => void): () => void;
179
231
  getViewabilityState(slotId: string): SlotViewabilityState | undefined;
232
+ /** The validated ingest endpoint in use, or "" when none passed validation. */
233
+ getEndpoint(): string;
180
234
  getRefreshIndex(slotId: string): number;
181
235
  triggerSlotRefresh(slotId: string, options?: SlotObserveOptions): void;
182
236
  trackRawEvent(level: string, eventName: string, data: any): void;
@@ -201,6 +255,7 @@ declare class BidkernelPrebidAnalytics {
201
255
  private handleSendFailure;
202
256
  private flush;
203
257
  private flushBeacon;
258
+ private pendingKeyPrefix;
204
259
  private persistBatch;
205
260
  private removePersistedBatch;
206
261
  private schedulePersistedCleanup;
@@ -275,4 +330,4 @@ interface AdsGlobal {
275
330
  */
276
331
  declare function getbidkernel(alias?: string): AdsGlobal;
277
332
 
278
- export { type AdsGlobal, type AnalyticsConfig, BidkernelPrebidAnalytics, type CachedWinningBid, PrebidEventDeduper, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, type VideoPlayerOptions, getPrebidEventKey, getbidkernel, registerPrebidAnalytics };
333
+ export { type AdsGlobal, type AnalyticsConfig, BidkernelPrebidAnalytics, type CachedWinningBid, PrebidEventDeduper, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, type VideoPlayerOptions, getPrebidEventKey, getbidkernel, hookImaPrototype, initImaInterception, isTrustedEndpoint, registerPrebidAnalytics };
package/dist/index.d.ts CHANGED
@@ -102,6 +102,21 @@ interface SlotViewabilityState {
102
102
  timeInViewMs: number;
103
103
  refreshIndex: number;
104
104
  }
105
+ /**
106
+ * The ingest endpoint decides where auction telemetry -- CPMs, deal IDs,
107
+ * advertiser domains, user and session IDs -- is shipped, and it arrives from
108
+ * page context (enableAnalytics options, or the _bidkernelAnalyticsConfig
109
+ * global). Anything running in the page can reach that, including a banner
110
+ * creative rendered into a same-origin Prebid friendly iframe, so the value is
111
+ * validated rather than trusted: HTTPS only, absolute, no credentials in the
112
+ * URL. Plain HTTP is allowed only for loopback so local development works.
113
+ *
114
+ * This deliberately does not allowlist hosts: properties on branded ingest
115
+ * domains legitimately point at their own. Hijacking a live instance to a
116
+ * different origin is prevented separately, by pinning in
117
+ * registerPrebidAnalytics.
118
+ */
119
+ declare function isTrustedEndpoint(raw: string): boolean;
105
120
  /**
106
121
  * Canonical duplicate-detection key for a Prebid event. Shared by the adapter
107
122
  * and the diagnostic extension so the two can never drift apart. Covers the
@@ -117,8 +132,17 @@ declare class PrebidEventDeduper {
117
132
  private seenKeys;
118
133
  isDuplicate(eventName: string, data: any): boolean;
119
134
  }
135
+ /**
136
+ * Hooks Google IMA SDK methods to automatically intercept AdsManager creation
137
+ * across active BidkernelPrebidAnalytics instances without requiring manual
138
+ * publisher calls to attachImaAdsManager.
139
+ */
140
+ declare function hookImaPrototype(ima: any): void;
141
+ declare function initImaInterception(): void;
120
142
  declare class BidkernelPrebidAnalytics {
121
143
  private static activeInstances;
144
+ static getActiveInstances(): Set<BidkernelPrebidAnalytics>;
145
+ static initImaInterception(): void;
122
146
  private config;
123
147
  private queue;
124
148
  private errorCount;
@@ -144,6 +168,7 @@ declare class BidkernelPrebidAnalytics {
144
168
  private slotEmittedImpressionKeys;
145
169
  private cachedWinningBids;
146
170
  private videoDetachCleanups;
171
+ private auctionBidderOutcomes;
147
172
  constructor(config: AnalyticsConfig);
148
173
  enable(): void;
149
174
  disable(): void;
@@ -158,6 +183,33 @@ declare class BidkernelPrebidAnalytics {
158
183
  observeSlot(element: HTMLElement | string, slotId?: string, options?: SlotObserveOptions): void;
159
184
  unobserveSlot(slotId: string): void;
160
185
  destroySlot(slotId: string): void;
186
+ /**
187
+ * Reads a cached winning bid, treating an entry past CACHED_BID_TTL_MS as
188
+ * absent and dropping it. Every read goes through here so a stale bid can
189
+ * never be married to a much later render.
190
+ */
191
+ private getCachedBid;
192
+ /** Removes every alias pointing at one entry. Aliases are stored by identity. */
193
+ private deleteCachedBidEntry;
194
+ /**
195
+ * Drops expired entries, then evicts oldest-first until the key cap holds.
196
+ * Map iterates in insertion order and one win's aliases are written
197
+ * consecutively, so eviction takes a whole bid's aliases together.
198
+ */
199
+ private pruneCachedWinningBids;
200
+ /**
201
+ * Searches cached winning bids for an entry matching the given filters (creativeId,
202
+ * adId, or mediaType), falling back to the most recent winning video bid.
203
+ */
204
+ private findCachedWinningBid;
205
+ /** Records a dedup key, evicting oldest-first at the cap. */
206
+ private addImpressionKey;
207
+ /**
208
+ * The bidder-outcome map for an auction, creating it if absent. Evicts the
209
+ * oldest auction at the cap: without this, any auction whose auctionEnd never
210
+ * fires (abandoned, navigated away from mid-flight) leaks its map forever.
211
+ */
212
+ private getOrCreateAuctionOutcomes;
161
213
  hasImpressionEmitted(slotId: string, refreshIndex?: number, auctionId?: string, creativeId?: string): boolean;
162
214
  private markImpressionEmitted;
163
215
  recordImpression(slotId: string, options?: SlotObserveOptions & {
@@ -177,6 +229,8 @@ declare class BidkernelPrebidAnalytics {
177
229
  attachVideoPlayer(target: any, options?: VideoPlayerOptions): () => void;
178
230
  onTimeInViewThreshold(slotId: string, thresholdMs: number, callback: (slotId: string, durationMs: number) => void): () => void;
179
231
  getViewabilityState(slotId: string): SlotViewabilityState | undefined;
232
+ /** The validated ingest endpoint in use, or "" when none passed validation. */
233
+ getEndpoint(): string;
180
234
  getRefreshIndex(slotId: string): number;
181
235
  triggerSlotRefresh(slotId: string, options?: SlotObserveOptions): void;
182
236
  trackRawEvent(level: string, eventName: string, data: any): void;
@@ -201,6 +255,7 @@ declare class BidkernelPrebidAnalytics {
201
255
  private handleSendFailure;
202
256
  private flush;
203
257
  private flushBeacon;
258
+ private pendingKeyPrefix;
204
259
  private persistBatch;
205
260
  private removePersistedBatch;
206
261
  private schedulePersistedCleanup;
@@ -275,4 +330,4 @@ interface AdsGlobal {
275
330
  */
276
331
  declare function getbidkernel(alias?: string): AdsGlobal;
277
332
 
278
- export { type AdsGlobal, type AnalyticsConfig, BidkernelPrebidAnalytics, type CachedWinningBid, PrebidEventDeduper, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, type VideoPlayerOptions, getPrebidEventKey, getbidkernel, registerPrebidAnalytics };
333
+ export { type AdsGlobal, type AnalyticsConfig, BidkernelPrebidAnalytics, type CachedWinningBid, PrebidEventDeduper, type SizeMapping, type SlotConfig, type SlotObserveOptions, type SlotSize, type SlotSizes, type SlotViewabilityState, type VideoPlayerOptions, getPrebidEventKey, getbidkernel, hookImaPrototype, initImaInterception, isTrustedEndpoint, registerPrebidAnalytics };